You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23644 lines
891 KiB

  1. /*
  2. @license
  3. Rollup.js v4.40.0
  4. Sat, 12 Apr 2025 08:39:04 GMT - commit 1f2d579ccd4b39f223fed14ac7d031a6c848cd80
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { EMPTY_OBJECT, ExportDefaultDeclaration as ExportDefaultDeclaration$1, CallExpression as CallExpression$1, EMPTY_ARRAY, LOGLEVEL_WARN, logUnusedExternalImports, ANNOTATION_KEY, INVALID_ANNOTATION_KEY, ObjectExpression as ObjectExpression$1, Property as Property$1, Program as Program$1, logIllegalImportReassignment, BLANK, logRedeclarationError, StaticBlock as StaticBlock$1, CatchClause as CatchClause$1, logDuplicateArgumentNameError, logModuleLevelDirective, ReturnStatement as ReturnStatement$1, VariableDeclarator as VariableDeclarator$1, ExpressionStatement as ExpressionStatement$1, logMissingExport, normalize, getImportPath, logMissingNodeBuiltins, logReservedNamespace, error, logIllegalIdentifierAsName, logMissingNameOptionForIifeExport, logMissingNameOptionForUmdExport, RestElement as RestElement$1, logConstVariableReassignError, ArrowFunctionExpression as ArrowFunctionExpression$1, EMPTY_SET, logCannotCallNamespace, logEval, BlockStatement as BlockStatement$1, getRollupError, logModuleParseError, logParseError, LOGLEVEL_INFO, logFirstSideEffect, locate, logInvalidAnnotation, Identifier as Identifier$1, logThisIsUndefined, getAstBuffer, convertAnnotations, FIXED_STRINGS, convertNode as convertNode$1, logImportAttributeIsInvalid, logImportOptionsAreInvalid, logSyntheticNamedExportsNeedNamespaceExport, logMissingEntryExport, logDuplicateExportError, logInvalidSourcemapForError, augmentCodeLocation, logInconsistentImportAttributes, logMissingJsxExport, logNamespaceConflict, logAmbiguousExternalNamespaces, logShimmedExport, parseAst, logInvalidFormatForTopLevelAwait, TemplateLiteral as TemplateLiteral$1, Literal as Literal$1, logCircularReexport, logAddonNotGenerated, logIncompatibleExportOptionValue, logMixedExport, logFailedValidation, isPathFragment, logCyclicCrossChunkReexport, getAliasName, logUnexpectedNamedImport, isAbsolute as isAbsolute$1, relative as relative$1, logUnexpectedNamespaceReexport, logEmptyChunk, logMissingGlobalName, logOptimizeChunkStatus, logSourcemapBroken, logConflictingSourcemapSources, logChunkInvalid, logInvalidOption, logCannotAssignModuleToChunk, URL_OUTPUT_FORMAT, URL_OUTPUT_DIR, URL_OUTPUT_SOURCEMAPFILE, URL_OUTPUT_AMD_ID, logAnonymousPluginCache, logDuplicatePluginName, logUnknownOption, LOGLEVEL_ERROR, logLevelPriority, LOGLEVEL_DEBUG, printQuotedStringList, logInvalidSetAssetSourceCall, logPluginError, logNoTransformMapOrAstWithoutCode, relativeId, logBadLoader, logExternalModulesCannotBeTransformedToModules, logInternalIdCannotBeExternal, isRelative, logUnresolvedImport, logUnresolvedImportTreatedAsExternal, logExternalSyntheticExports, logUnresolvedEntry, logUnresolvedImplicitDependant, logExternalModulesCannotBeIncludedInManualChunks, logEntryCannotBeExternal, logImplicitDependantCannotBeExternal, logNoAssetSourceSet, logFileReferenceIdNotFoundForFilename, logAssetReferenceIdNotFoundForSetSource, logAssetSourceAlreadySet, logInvalidRollupPhaseForChunkEmission, warnDeprecation, logChunkNotGeneratedForFileName, logAssetNotFinalisedForFileName, logFileNameConflict, URL_GENERATEBUNDLE, logInvalidLogPosition, logInputHookInOutputPlugin, logInvalidAddonPluginHook, logInvalidFunctionPluginHook, logImplicitDependantIsNotIncluded, logCircularDependency, augmentLogMessage, URL_TREESHAKE, URL_JSX, URL_TREESHAKE_MODULESIDEEFFECTS, URL_OUTPUT_INLINEDYNAMICIMPORTS, URL_PRESERVEENTRYSIGNATURES, URL_OUTPUT_GENERATEDCODE, isValidUrl, addTrailingSlashIfMissed, URL_OUTPUT_SOURCEMAPBASEURL, URL_OUTPUT_MANUALCHUNKS, logInvalidExportOptionValue, URL_OUTPUT_AMD_BASEPATH, URL_OUTPUT_INTEROP, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, logAlreadyClosed, logMissingFileOrDirOption, logCannotEmitFromOptionsHook, URL_WATCH } from './parseAst.js';
  9. import { relative, dirname, basename, extname, resolve as resolve$1 } from 'node:path';
  10. import { posix, isAbsolute, resolve, win32 } from 'path';
  11. import { parseAsync, xxhashBase16, xxhashBase64Url, xxhashBase36 } from '../../native.js';
  12. import process$1, { env } from 'node:process';
  13. import { performance } from 'node:perf_hooks';
  14. import { lstat, realpath, readdir, readFile, mkdir, writeFile } from 'node:fs/promises';
  15. var version = "4.40.0";
  16. const comma = ','.charCodeAt(0);
  17. const semicolon = ';'.charCodeAt(0);
  18. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  19. const intToChar = new Uint8Array(64); // 64 possible chars.
  20. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  21. for (let i = 0; i < chars$1.length; i++) {
  22. const c = chars$1.charCodeAt(i);
  23. intToChar[i] = c;
  24. charToInt[c] = i;
  25. }
  26. function decodeInteger(reader, relative) {
  27. let value = 0;
  28. let shift = 0;
  29. let integer = 0;
  30. do {
  31. const c = reader.next();
  32. integer = charToInt[c];
  33. value |= (integer & 31) << shift;
  34. shift += 5;
  35. } while (integer & 32);
  36. const shouldNegate = value & 1;
  37. value >>>= 1;
  38. if (shouldNegate) {
  39. value = -2147483648 | -value;
  40. }
  41. return relative + value;
  42. }
  43. function encodeInteger(builder, num, relative) {
  44. let delta = num - relative;
  45. delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
  46. do {
  47. let clamped = delta & 0b011111;
  48. delta >>>= 5;
  49. if (delta > 0)
  50. clamped |= 0b100000;
  51. builder.write(intToChar[clamped]);
  52. } while (delta > 0);
  53. return num;
  54. }
  55. function hasMoreVlq(reader, max) {
  56. if (reader.pos >= max)
  57. return false;
  58. return reader.peek() !== comma;
  59. }
  60. const bufLength = 1024 * 16;
  61. // Provide a fallback for older environments.
  62. const td = typeof TextDecoder !== 'undefined'
  63. ? /* #__PURE__ */ new TextDecoder()
  64. : typeof Buffer !== 'undefined'
  65. ? {
  66. decode(buf) {
  67. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  68. return out.toString();
  69. },
  70. }
  71. : {
  72. decode(buf) {
  73. let out = '';
  74. for (let i = 0; i < buf.length; i++) {
  75. out += String.fromCharCode(buf[i]);
  76. }
  77. return out;
  78. },
  79. };
  80. class StringWriter {
  81. constructor() {
  82. this.pos = 0;
  83. this.out = '';
  84. this.buffer = new Uint8Array(bufLength);
  85. }
  86. write(v) {
  87. const { buffer } = this;
  88. buffer[this.pos++] = v;
  89. if (this.pos === bufLength) {
  90. this.out += td.decode(buffer);
  91. this.pos = 0;
  92. }
  93. }
  94. flush() {
  95. const { buffer, out, pos } = this;
  96. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  97. }
  98. }
  99. class StringReader {
  100. constructor(buffer) {
  101. this.pos = 0;
  102. this.buffer = buffer;
  103. }
  104. next() {
  105. return this.buffer.charCodeAt(this.pos++);
  106. }
  107. peek() {
  108. return this.buffer.charCodeAt(this.pos);
  109. }
  110. indexOf(char) {
  111. const { buffer, pos } = this;
  112. const idx = buffer.indexOf(char, pos);
  113. return idx === -1 ? buffer.length : idx;
  114. }
  115. }
  116. function decode(mappings) {
  117. const { length } = mappings;
  118. const reader = new StringReader(mappings);
  119. const decoded = [];
  120. let genColumn = 0;
  121. let sourcesIndex = 0;
  122. let sourceLine = 0;
  123. let sourceColumn = 0;
  124. let namesIndex = 0;
  125. do {
  126. const semi = reader.indexOf(';');
  127. const line = [];
  128. let sorted = true;
  129. let lastCol = 0;
  130. genColumn = 0;
  131. while (reader.pos < semi) {
  132. let seg;
  133. genColumn = decodeInteger(reader, genColumn);
  134. if (genColumn < lastCol)
  135. sorted = false;
  136. lastCol = genColumn;
  137. if (hasMoreVlq(reader, semi)) {
  138. sourcesIndex = decodeInteger(reader, sourcesIndex);
  139. sourceLine = decodeInteger(reader, sourceLine);
  140. sourceColumn = decodeInteger(reader, sourceColumn);
  141. if (hasMoreVlq(reader, semi)) {
  142. namesIndex = decodeInteger(reader, namesIndex);
  143. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  144. }
  145. else {
  146. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  147. }
  148. }
  149. else {
  150. seg = [genColumn];
  151. }
  152. line.push(seg);
  153. reader.pos++;
  154. }
  155. if (!sorted)
  156. sort(line);
  157. decoded.push(line);
  158. reader.pos = semi + 1;
  159. } while (reader.pos <= length);
  160. return decoded;
  161. }
  162. function sort(line) {
  163. line.sort(sortComparator);
  164. }
  165. function sortComparator(a, b) {
  166. return a[0] - b[0];
  167. }
  168. function encode(decoded) {
  169. const writer = new StringWriter();
  170. let sourcesIndex = 0;
  171. let sourceLine = 0;
  172. let sourceColumn = 0;
  173. let namesIndex = 0;
  174. for (let i = 0; i < decoded.length; i++) {
  175. const line = decoded[i];
  176. if (i > 0)
  177. writer.write(semicolon);
  178. if (line.length === 0)
  179. continue;
  180. let genColumn = 0;
  181. for (let j = 0; j < line.length; j++) {
  182. const segment = line[j];
  183. if (j > 0)
  184. writer.write(comma);
  185. genColumn = encodeInteger(writer, segment[0], genColumn);
  186. if (segment.length === 1)
  187. continue;
  188. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  189. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  190. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  191. if (segment.length === 4)
  192. continue;
  193. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  194. }
  195. }
  196. return writer.flush();
  197. }
  198. class BitSet {
  199. constructor(arg) {
  200. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  201. }
  202. add(n) {
  203. this.bits[n >> 5] |= 1 << (n & 31);
  204. }
  205. has(n) {
  206. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  207. }
  208. }
  209. let Chunk$1 = class Chunk {
  210. constructor(start, end, content) {
  211. this.start = start;
  212. this.end = end;
  213. this.original = content;
  214. this.intro = '';
  215. this.outro = '';
  216. this.content = content;
  217. this.storeName = false;
  218. this.edited = false;
  219. {
  220. this.previous = null;
  221. this.next = null;
  222. }
  223. }
  224. appendLeft(content) {
  225. this.outro += content;
  226. }
  227. appendRight(content) {
  228. this.intro = this.intro + content;
  229. }
  230. clone() {
  231. const chunk = new Chunk(this.start, this.end, this.original);
  232. chunk.intro = this.intro;
  233. chunk.outro = this.outro;
  234. chunk.content = this.content;
  235. chunk.storeName = this.storeName;
  236. chunk.edited = this.edited;
  237. return chunk;
  238. }
  239. contains(index) {
  240. return this.start < index && index < this.end;
  241. }
  242. eachNext(fn) {
  243. let chunk = this;
  244. while (chunk) {
  245. fn(chunk);
  246. chunk = chunk.next;
  247. }
  248. }
  249. eachPrevious(fn) {
  250. let chunk = this;
  251. while (chunk) {
  252. fn(chunk);
  253. chunk = chunk.previous;
  254. }
  255. }
  256. edit(content, storeName, contentOnly) {
  257. this.content = content;
  258. if (!contentOnly) {
  259. this.intro = '';
  260. this.outro = '';
  261. }
  262. this.storeName = storeName;
  263. this.edited = true;
  264. return this;
  265. }
  266. prependLeft(content) {
  267. this.outro = content + this.outro;
  268. }
  269. prependRight(content) {
  270. this.intro = content + this.intro;
  271. }
  272. reset() {
  273. this.intro = '';
  274. this.outro = '';
  275. if (this.edited) {
  276. this.content = this.original;
  277. this.storeName = false;
  278. this.edited = false;
  279. }
  280. }
  281. split(index) {
  282. const sliceIndex = index - this.start;
  283. const originalBefore = this.original.slice(0, sliceIndex);
  284. const originalAfter = this.original.slice(sliceIndex);
  285. this.original = originalBefore;
  286. const newChunk = new Chunk(index, this.end, originalAfter);
  287. newChunk.outro = this.outro;
  288. this.outro = '';
  289. this.end = index;
  290. if (this.edited) {
  291. // after split we should save the edit content record into the correct chunk
  292. // to make sure sourcemap correct
  293. // For example:
  294. // ' test'.trim()
  295. // split -> ' ' + 'test'
  296. // ✔️ edit -> '' + 'test'
  297. // ✖️ edit -> 'test' + ''
  298. // TODO is this block necessary?...
  299. newChunk.edit('', false);
  300. this.content = '';
  301. } else {
  302. this.content = originalBefore;
  303. }
  304. newChunk.next = this.next;
  305. if (newChunk.next) newChunk.next.previous = newChunk;
  306. newChunk.previous = this;
  307. this.next = newChunk;
  308. return newChunk;
  309. }
  310. toString() {
  311. return this.intro + this.content + this.outro;
  312. }
  313. trimEnd(rx) {
  314. this.outro = this.outro.replace(rx, '');
  315. if (this.outro.length) return true;
  316. const trimmed = this.content.replace(rx, '');
  317. if (trimmed.length) {
  318. if (trimmed !== this.content) {
  319. this.split(this.start + trimmed.length).edit('', undefined, true);
  320. if (this.edited) {
  321. // save the change, if it has been edited
  322. this.edit(trimmed, this.storeName, true);
  323. }
  324. }
  325. return true;
  326. } else {
  327. this.edit('', undefined, true);
  328. this.intro = this.intro.replace(rx, '');
  329. if (this.intro.length) return true;
  330. }
  331. }
  332. trimStart(rx) {
  333. this.intro = this.intro.replace(rx, '');
  334. if (this.intro.length) return true;
  335. const trimmed = this.content.replace(rx, '');
  336. if (trimmed.length) {
  337. if (trimmed !== this.content) {
  338. const newChunk = this.split(this.end - trimmed.length);
  339. if (this.edited) {
  340. // save the change, if it has been edited
  341. newChunk.edit(trimmed, this.storeName, true);
  342. }
  343. this.edit('', undefined, true);
  344. }
  345. return true;
  346. } else {
  347. this.edit('', undefined, true);
  348. this.outro = this.outro.replace(rx, '');
  349. if (this.outro.length) return true;
  350. }
  351. }
  352. };
  353. function getBtoa() {
  354. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  355. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  356. } else if (typeof Buffer === 'function') {
  357. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  358. } else {
  359. return () => {
  360. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  361. };
  362. }
  363. }
  364. const btoa = /*#__PURE__*/ getBtoa();
  365. class SourceMap {
  366. constructor(properties) {
  367. this.version = 3;
  368. this.file = properties.file;
  369. this.sources = properties.sources;
  370. this.sourcesContent = properties.sourcesContent;
  371. this.names = properties.names;
  372. this.mappings = encode(properties.mappings);
  373. if (typeof properties.x_google_ignoreList !== 'undefined') {
  374. this.x_google_ignoreList = properties.x_google_ignoreList;
  375. }
  376. if (typeof properties.debugId !== 'undefined') {
  377. this.debugId = properties.debugId;
  378. }
  379. }
  380. toString() {
  381. return JSON.stringify(this);
  382. }
  383. toUrl() {
  384. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  385. }
  386. }
  387. function guessIndent(code) {
  388. const lines = code.split('\n');
  389. const tabbed = lines.filter((line) => /^\t+/.test(line));
  390. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  391. if (tabbed.length === 0 && spaced.length === 0) {
  392. return null;
  393. }
  394. // More lines tabbed than spaced? Assume tabs, and
  395. // default to tabs in the case of a tie (or nothing
  396. // to go on)
  397. if (tabbed.length >= spaced.length) {
  398. return '\t';
  399. }
  400. // Otherwise, we need to guess the multiple
  401. const min = spaced.reduce((previous, current) => {
  402. const numSpaces = /^ +/.exec(current)[0].length;
  403. return Math.min(numSpaces, previous);
  404. }, Infinity);
  405. return new Array(min + 1).join(' ');
  406. }
  407. function getRelativePath(from, to) {
  408. const fromParts = from.split(/[/\\]/);
  409. const toParts = to.split(/[/\\]/);
  410. fromParts.pop(); // get dirname
  411. while (fromParts[0] === toParts[0]) {
  412. fromParts.shift();
  413. toParts.shift();
  414. }
  415. if (fromParts.length) {
  416. let i = fromParts.length;
  417. while (i--) fromParts[i] = '..';
  418. }
  419. return fromParts.concat(toParts).join('/');
  420. }
  421. const toString = Object.prototype.toString;
  422. function isObject(thing) {
  423. return toString.call(thing) === '[object Object]';
  424. }
  425. function getLocator(source) {
  426. const originalLines = source.split('\n');
  427. const lineOffsets = [];
  428. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  429. lineOffsets.push(pos);
  430. pos += originalLines[i].length + 1;
  431. }
  432. return function locate(index) {
  433. let i = 0;
  434. let j = lineOffsets.length;
  435. while (i < j) {
  436. const m = (i + j) >> 1;
  437. if (index < lineOffsets[m]) {
  438. j = m;
  439. } else {
  440. i = m + 1;
  441. }
  442. }
  443. const line = i - 1;
  444. const column = index - lineOffsets[line];
  445. return { line, column };
  446. };
  447. }
  448. const wordRegex = /\w/;
  449. class Mappings {
  450. constructor(hires) {
  451. this.hires = hires;
  452. this.generatedCodeLine = 0;
  453. this.generatedCodeColumn = 0;
  454. this.raw = [];
  455. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  456. this.pending = null;
  457. }
  458. addEdit(sourceIndex, content, loc, nameIndex) {
  459. if (content.length) {
  460. const contentLengthMinusOne = content.length - 1;
  461. let contentLineEnd = content.indexOf('\n', 0);
  462. let previousContentLineEnd = -1;
  463. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  464. // else code afterwards would fill one line too many
  465. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  466. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  467. if (nameIndex >= 0) {
  468. segment.push(nameIndex);
  469. }
  470. this.rawSegments.push(segment);
  471. this.generatedCodeLine += 1;
  472. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  473. this.generatedCodeColumn = 0;
  474. previousContentLineEnd = contentLineEnd;
  475. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  476. }
  477. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  478. if (nameIndex >= 0) {
  479. segment.push(nameIndex);
  480. }
  481. this.rawSegments.push(segment);
  482. this.advance(content.slice(previousContentLineEnd + 1));
  483. } else if (this.pending) {
  484. this.rawSegments.push(this.pending);
  485. this.advance(content);
  486. }
  487. this.pending = null;
  488. }
  489. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  490. let originalCharIndex = chunk.start;
  491. let first = true;
  492. // when iterating each char, check if it's in a word boundary
  493. let charInHiresBoundary = false;
  494. while (originalCharIndex < chunk.end) {
  495. if (original[originalCharIndex] === '\n') {
  496. loc.line += 1;
  497. loc.column = 0;
  498. this.generatedCodeLine += 1;
  499. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  500. this.generatedCodeColumn = 0;
  501. first = true;
  502. charInHiresBoundary = false;
  503. } else {
  504. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  505. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  506. if (this.hires === 'boundary') {
  507. // in hires "boundary", group segments per word boundary than per char
  508. if (wordRegex.test(original[originalCharIndex])) {
  509. // for first char in the boundary found, start the boundary by pushing a segment
  510. if (!charInHiresBoundary) {
  511. this.rawSegments.push(segment);
  512. charInHiresBoundary = true;
  513. }
  514. } else {
  515. // for non-word char, end the boundary by pushing a segment
  516. this.rawSegments.push(segment);
  517. charInHiresBoundary = false;
  518. }
  519. } else {
  520. this.rawSegments.push(segment);
  521. }
  522. }
  523. loc.column += 1;
  524. this.generatedCodeColumn += 1;
  525. first = false;
  526. }
  527. originalCharIndex += 1;
  528. }
  529. this.pending = null;
  530. }
  531. advance(str) {
  532. if (!str) return;
  533. const lines = str.split('\n');
  534. if (lines.length > 1) {
  535. for (let i = 0; i < lines.length - 1; i++) {
  536. this.generatedCodeLine++;
  537. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  538. }
  539. this.generatedCodeColumn = 0;
  540. }
  541. this.generatedCodeColumn += lines[lines.length - 1].length;
  542. }
  543. }
  544. const n = '\n';
  545. const warned = {
  546. insertLeft: false,
  547. insertRight: false,
  548. storeName: false,
  549. };
  550. class MagicString {
  551. constructor(string, options = {}) {
  552. const chunk = new Chunk$1(0, string.length, string);
  553. Object.defineProperties(this, {
  554. original: { writable: true, value: string },
  555. outro: { writable: true, value: '' },
  556. intro: { writable: true, value: '' },
  557. firstChunk: { writable: true, value: chunk },
  558. lastChunk: { writable: true, value: chunk },
  559. lastSearchedChunk: { writable: true, value: chunk },
  560. byStart: { writable: true, value: {} },
  561. byEnd: { writable: true, value: {} },
  562. filename: { writable: true, value: options.filename },
  563. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  564. sourcemapLocations: { writable: true, value: new BitSet() },
  565. storedNames: { writable: true, value: {} },
  566. indentStr: { writable: true, value: undefined },
  567. ignoreList: { writable: true, value: options.ignoreList },
  568. offset: { writable: true, value: options.offset || 0 },
  569. });
  570. this.byStart[0] = chunk;
  571. this.byEnd[string.length] = chunk;
  572. }
  573. addSourcemapLocation(char) {
  574. this.sourcemapLocations.add(char);
  575. }
  576. append(content) {
  577. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  578. this.outro += content;
  579. return this;
  580. }
  581. appendLeft(index, content) {
  582. index = index + this.offset;
  583. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  584. this._split(index);
  585. const chunk = this.byEnd[index];
  586. if (chunk) {
  587. chunk.appendLeft(content);
  588. } else {
  589. this.intro += content;
  590. }
  591. return this;
  592. }
  593. appendRight(index, content) {
  594. index = index + this.offset;
  595. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  596. this._split(index);
  597. const chunk = this.byStart[index];
  598. if (chunk) {
  599. chunk.appendRight(content);
  600. } else {
  601. this.outro += content;
  602. }
  603. return this;
  604. }
  605. clone() {
  606. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  607. let originalChunk = this.firstChunk;
  608. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  609. while (originalChunk) {
  610. cloned.byStart[clonedChunk.start] = clonedChunk;
  611. cloned.byEnd[clonedChunk.end] = clonedChunk;
  612. const nextOriginalChunk = originalChunk.next;
  613. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  614. if (nextClonedChunk) {
  615. clonedChunk.next = nextClonedChunk;
  616. nextClonedChunk.previous = clonedChunk;
  617. clonedChunk = nextClonedChunk;
  618. }
  619. originalChunk = nextOriginalChunk;
  620. }
  621. cloned.lastChunk = clonedChunk;
  622. if (this.indentExclusionRanges) {
  623. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  624. }
  625. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  626. cloned.intro = this.intro;
  627. cloned.outro = this.outro;
  628. return cloned;
  629. }
  630. generateDecodedMap(options) {
  631. options = options || {};
  632. const sourceIndex = 0;
  633. const names = Object.keys(this.storedNames);
  634. const mappings = new Mappings(options.hires);
  635. const locate = getLocator(this.original);
  636. if (this.intro) {
  637. mappings.advance(this.intro);
  638. }
  639. this.firstChunk.eachNext((chunk) => {
  640. const loc = locate(chunk.start);
  641. if (chunk.intro.length) mappings.advance(chunk.intro);
  642. if (chunk.edited) {
  643. mappings.addEdit(
  644. sourceIndex,
  645. chunk.content,
  646. loc,
  647. chunk.storeName ? names.indexOf(chunk.original) : -1,
  648. );
  649. } else {
  650. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  651. }
  652. if (chunk.outro.length) mappings.advance(chunk.outro);
  653. });
  654. return {
  655. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  656. sources: [
  657. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  658. ],
  659. sourcesContent: options.includeContent ? [this.original] : undefined,
  660. names,
  661. mappings: mappings.raw,
  662. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  663. };
  664. }
  665. generateMap(options) {
  666. return new SourceMap(this.generateDecodedMap(options));
  667. }
  668. _ensureindentStr() {
  669. if (this.indentStr === undefined) {
  670. this.indentStr = guessIndent(this.original);
  671. }
  672. }
  673. _getRawIndentString() {
  674. this._ensureindentStr();
  675. return this.indentStr;
  676. }
  677. getIndentString() {
  678. this._ensureindentStr();
  679. return this.indentStr === null ? '\t' : this.indentStr;
  680. }
  681. indent(indentStr, options) {
  682. const pattern = /^[^\r\n]/gm;
  683. if (isObject(indentStr)) {
  684. options = indentStr;
  685. indentStr = undefined;
  686. }
  687. if (indentStr === undefined) {
  688. this._ensureindentStr();
  689. indentStr = this.indentStr || '\t';
  690. }
  691. if (indentStr === '') return this; // noop
  692. options = options || {};
  693. // Process exclusion ranges
  694. const isExcluded = {};
  695. if (options.exclude) {
  696. const exclusions =
  697. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  698. exclusions.forEach((exclusion) => {
  699. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  700. isExcluded[i] = true;
  701. }
  702. });
  703. }
  704. let shouldIndentNextCharacter = options.indentStart !== false;
  705. const replacer = (match) => {
  706. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  707. shouldIndentNextCharacter = true;
  708. return match;
  709. };
  710. this.intro = this.intro.replace(pattern, replacer);
  711. let charIndex = 0;
  712. let chunk = this.firstChunk;
  713. while (chunk) {
  714. const end = chunk.end;
  715. if (chunk.edited) {
  716. if (!isExcluded[charIndex]) {
  717. chunk.content = chunk.content.replace(pattern, replacer);
  718. if (chunk.content.length) {
  719. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  720. }
  721. }
  722. } else {
  723. charIndex = chunk.start;
  724. while (charIndex < end) {
  725. if (!isExcluded[charIndex]) {
  726. const char = this.original[charIndex];
  727. if (char === '\n') {
  728. shouldIndentNextCharacter = true;
  729. } else if (char !== '\r' && shouldIndentNextCharacter) {
  730. shouldIndentNextCharacter = false;
  731. if (charIndex === chunk.start) {
  732. chunk.prependRight(indentStr);
  733. } else {
  734. this._splitChunk(chunk, charIndex);
  735. chunk = chunk.next;
  736. chunk.prependRight(indentStr);
  737. }
  738. }
  739. }
  740. charIndex += 1;
  741. }
  742. }
  743. charIndex = chunk.end;
  744. chunk = chunk.next;
  745. }
  746. this.outro = this.outro.replace(pattern, replacer);
  747. return this;
  748. }
  749. insert() {
  750. throw new Error(
  751. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  752. );
  753. }
  754. insertLeft(index, content) {
  755. if (!warned.insertLeft) {
  756. console.warn(
  757. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  758. );
  759. warned.insertLeft = true;
  760. }
  761. return this.appendLeft(index, content);
  762. }
  763. insertRight(index, content) {
  764. if (!warned.insertRight) {
  765. console.warn(
  766. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  767. );
  768. warned.insertRight = true;
  769. }
  770. return this.prependRight(index, content);
  771. }
  772. move(start, end, index) {
  773. start = start + this.offset;
  774. end = end + this.offset;
  775. index = index + this.offset;
  776. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  777. this._split(start);
  778. this._split(end);
  779. this._split(index);
  780. const first = this.byStart[start];
  781. const last = this.byEnd[end];
  782. const oldLeft = first.previous;
  783. const oldRight = last.next;
  784. const newRight = this.byStart[index];
  785. if (!newRight && last === this.lastChunk) return this;
  786. const newLeft = newRight ? newRight.previous : this.lastChunk;
  787. if (oldLeft) oldLeft.next = oldRight;
  788. if (oldRight) oldRight.previous = oldLeft;
  789. if (newLeft) newLeft.next = first;
  790. if (newRight) newRight.previous = last;
  791. if (!first.previous) this.firstChunk = last.next;
  792. if (!last.next) {
  793. this.lastChunk = first.previous;
  794. this.lastChunk.next = null;
  795. }
  796. first.previous = newLeft;
  797. last.next = newRight || null;
  798. if (!newLeft) this.firstChunk = first;
  799. if (!newRight) this.lastChunk = last;
  800. return this;
  801. }
  802. overwrite(start, end, content, options) {
  803. options = options || {};
  804. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  805. }
  806. update(start, end, content, options) {
  807. start = start + this.offset;
  808. end = end + this.offset;
  809. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  810. if (this.original.length !== 0) {
  811. while (start < 0) start += this.original.length;
  812. while (end < 0) end += this.original.length;
  813. }
  814. if (end > this.original.length) throw new Error('end is out of bounds');
  815. if (start === end)
  816. throw new Error(
  817. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  818. );
  819. this._split(start);
  820. this._split(end);
  821. if (options === true) {
  822. if (!warned.storeName) {
  823. console.warn(
  824. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  825. );
  826. warned.storeName = true;
  827. }
  828. options = { storeName: true };
  829. }
  830. const storeName = options !== undefined ? options.storeName : false;
  831. const overwrite = options !== undefined ? options.overwrite : false;
  832. if (storeName) {
  833. const original = this.original.slice(start, end);
  834. Object.defineProperty(this.storedNames, original, {
  835. writable: true,
  836. value: true,
  837. enumerable: true,
  838. });
  839. }
  840. const first = this.byStart[start];
  841. const last = this.byEnd[end];
  842. if (first) {
  843. let chunk = first;
  844. while (chunk !== last) {
  845. if (chunk.next !== this.byStart[chunk.end]) {
  846. throw new Error('Cannot overwrite across a split point');
  847. }
  848. chunk = chunk.next;
  849. chunk.edit('', false);
  850. }
  851. first.edit(content, storeName, !overwrite);
  852. } else {
  853. // must be inserting at the end
  854. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  855. // TODO last chunk in the array may not be the last chunk, if it's moved...
  856. last.next = newChunk;
  857. newChunk.previous = last;
  858. }
  859. return this;
  860. }
  861. prepend(content) {
  862. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  863. this.intro = content + this.intro;
  864. return this;
  865. }
  866. prependLeft(index, content) {
  867. index = index + this.offset;
  868. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  869. this._split(index);
  870. const chunk = this.byEnd[index];
  871. if (chunk) {
  872. chunk.prependLeft(content);
  873. } else {
  874. this.intro = content + this.intro;
  875. }
  876. return this;
  877. }
  878. prependRight(index, content) {
  879. index = index + this.offset;
  880. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  881. this._split(index);
  882. const chunk = this.byStart[index];
  883. if (chunk) {
  884. chunk.prependRight(content);
  885. } else {
  886. this.outro = content + this.outro;
  887. }
  888. return this;
  889. }
  890. remove(start, end) {
  891. start = start + this.offset;
  892. end = end + this.offset;
  893. if (this.original.length !== 0) {
  894. while (start < 0) start += this.original.length;
  895. while (end < 0) end += this.original.length;
  896. }
  897. if (start === end) return this;
  898. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  899. if (start > end) throw new Error('end must be greater than start');
  900. this._split(start);
  901. this._split(end);
  902. let chunk = this.byStart[start];
  903. while (chunk) {
  904. chunk.intro = '';
  905. chunk.outro = '';
  906. chunk.edit('');
  907. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  908. }
  909. return this;
  910. }
  911. reset(start, end) {
  912. start = start + this.offset;
  913. end = end + this.offset;
  914. if (this.original.length !== 0) {
  915. while (start < 0) start += this.original.length;
  916. while (end < 0) end += this.original.length;
  917. }
  918. if (start === end) return this;
  919. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  920. if (start > end) throw new Error('end must be greater than start');
  921. this._split(start);
  922. this._split(end);
  923. let chunk = this.byStart[start];
  924. while (chunk) {
  925. chunk.reset();
  926. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  927. }
  928. return this;
  929. }
  930. lastChar() {
  931. if (this.outro.length) return this.outro[this.outro.length - 1];
  932. let chunk = this.lastChunk;
  933. do {
  934. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  935. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  936. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  937. } while ((chunk = chunk.previous));
  938. if (this.intro.length) return this.intro[this.intro.length - 1];
  939. return '';
  940. }
  941. lastLine() {
  942. let lineIndex = this.outro.lastIndexOf(n);
  943. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  944. let lineStr = this.outro;
  945. let chunk = this.lastChunk;
  946. do {
  947. if (chunk.outro.length > 0) {
  948. lineIndex = chunk.outro.lastIndexOf(n);
  949. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  950. lineStr = chunk.outro + lineStr;
  951. }
  952. if (chunk.content.length > 0) {
  953. lineIndex = chunk.content.lastIndexOf(n);
  954. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  955. lineStr = chunk.content + lineStr;
  956. }
  957. if (chunk.intro.length > 0) {
  958. lineIndex = chunk.intro.lastIndexOf(n);
  959. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  960. lineStr = chunk.intro + lineStr;
  961. }
  962. } while ((chunk = chunk.previous));
  963. lineIndex = this.intro.lastIndexOf(n);
  964. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  965. return this.intro + lineStr;
  966. }
  967. slice(start = 0, end = this.original.length - this.offset) {
  968. start = start + this.offset;
  969. end = end + this.offset;
  970. if (this.original.length !== 0) {
  971. while (start < 0) start += this.original.length;
  972. while (end < 0) end += this.original.length;
  973. }
  974. let result = '';
  975. // find start chunk
  976. let chunk = this.firstChunk;
  977. while (chunk && (chunk.start > start || chunk.end <= start)) {
  978. // found end chunk before start
  979. if (chunk.start < end && chunk.end >= end) {
  980. return result;
  981. }
  982. chunk = chunk.next;
  983. }
  984. if (chunk && chunk.edited && chunk.start !== start)
  985. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  986. const startChunk = chunk;
  987. while (chunk) {
  988. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  989. result += chunk.intro;
  990. }
  991. const containsEnd = chunk.start < end && chunk.end >= end;
  992. if (containsEnd && chunk.edited && chunk.end !== end)
  993. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  994. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  995. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  996. result += chunk.content.slice(sliceStart, sliceEnd);
  997. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  998. result += chunk.outro;
  999. }
  1000. if (containsEnd) {
  1001. break;
  1002. }
  1003. chunk = chunk.next;
  1004. }
  1005. return result;
  1006. }
  1007. // TODO deprecate this? not really very useful
  1008. snip(start, end) {
  1009. const clone = this.clone();
  1010. clone.remove(0, start);
  1011. clone.remove(end, clone.original.length);
  1012. return clone;
  1013. }
  1014. _split(index) {
  1015. if (this.byStart[index] || this.byEnd[index]) return;
  1016. let chunk = this.lastSearchedChunk;
  1017. const searchForward = index > chunk.end;
  1018. while (chunk) {
  1019. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  1020. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1021. }
  1022. }
  1023. _splitChunk(chunk, index) {
  1024. if (chunk.edited && chunk.content.length) {
  1025. // zero-length edited chunks are a special case (overlapping replacements)
  1026. const loc = getLocator(this.original)(index);
  1027. throw new Error(
  1028. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  1029. );
  1030. }
  1031. const newChunk = chunk.split(index);
  1032. this.byEnd[index] = chunk;
  1033. this.byStart[index] = newChunk;
  1034. this.byEnd[newChunk.end] = newChunk;
  1035. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  1036. this.lastSearchedChunk = chunk;
  1037. return true;
  1038. }
  1039. toString() {
  1040. let str = this.intro;
  1041. let chunk = this.firstChunk;
  1042. while (chunk) {
  1043. str += chunk.toString();
  1044. chunk = chunk.next;
  1045. }
  1046. return str + this.outro;
  1047. }
  1048. isEmpty() {
  1049. let chunk = this.firstChunk;
  1050. do {
  1051. if (
  1052. (chunk.intro.length && chunk.intro.trim()) ||
  1053. (chunk.content.length && chunk.content.trim()) ||
  1054. (chunk.outro.length && chunk.outro.trim())
  1055. )
  1056. return false;
  1057. } while ((chunk = chunk.next));
  1058. return true;
  1059. }
  1060. length() {
  1061. let chunk = this.firstChunk;
  1062. let length = 0;
  1063. do {
  1064. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1065. } while ((chunk = chunk.next));
  1066. return length;
  1067. }
  1068. trimLines() {
  1069. return this.trim('[\\r\\n]');
  1070. }
  1071. trim(charType) {
  1072. return this.trimStart(charType).trimEnd(charType);
  1073. }
  1074. trimEndAborted(charType) {
  1075. const rx = new RegExp((charType || '\\s') + '+$');
  1076. this.outro = this.outro.replace(rx, '');
  1077. if (this.outro.length) return true;
  1078. let chunk = this.lastChunk;
  1079. do {
  1080. const end = chunk.end;
  1081. const aborted = chunk.trimEnd(rx);
  1082. // if chunk was trimmed, we have a new lastChunk
  1083. if (chunk.end !== end) {
  1084. if (this.lastChunk === chunk) {
  1085. this.lastChunk = chunk.next;
  1086. }
  1087. this.byEnd[chunk.end] = chunk;
  1088. this.byStart[chunk.next.start] = chunk.next;
  1089. this.byEnd[chunk.next.end] = chunk.next;
  1090. }
  1091. if (aborted) return true;
  1092. chunk = chunk.previous;
  1093. } while (chunk);
  1094. return false;
  1095. }
  1096. trimEnd(charType) {
  1097. this.trimEndAborted(charType);
  1098. return this;
  1099. }
  1100. trimStartAborted(charType) {
  1101. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1102. this.intro = this.intro.replace(rx, '');
  1103. if (this.intro.length) return true;
  1104. let chunk = this.firstChunk;
  1105. do {
  1106. const end = chunk.end;
  1107. const aborted = chunk.trimStart(rx);
  1108. if (chunk.end !== end) {
  1109. // special case...
  1110. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1111. this.byEnd[chunk.end] = chunk;
  1112. this.byStart[chunk.next.start] = chunk.next;
  1113. this.byEnd[chunk.next.end] = chunk.next;
  1114. }
  1115. if (aborted) return true;
  1116. chunk = chunk.next;
  1117. } while (chunk);
  1118. return false;
  1119. }
  1120. trimStart(charType) {
  1121. this.trimStartAborted(charType);
  1122. return this;
  1123. }
  1124. hasChanged() {
  1125. return this.original !== this.toString();
  1126. }
  1127. _replaceRegexp(searchValue, replacement) {
  1128. function getReplacement(match, str) {
  1129. if (typeof replacement === 'string') {
  1130. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1131. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1132. if (i === '$') return '$';
  1133. if (i === '&') return match[0];
  1134. const num = +i;
  1135. if (num < match.length) return match[+i];
  1136. return `$${i}`;
  1137. });
  1138. } else {
  1139. return replacement(...match, match.index, str, match.groups);
  1140. }
  1141. }
  1142. function matchAll(re, str) {
  1143. let match;
  1144. const matches = [];
  1145. while ((match = re.exec(str))) {
  1146. matches.push(match);
  1147. }
  1148. return matches;
  1149. }
  1150. if (searchValue.global) {
  1151. const matches = matchAll(searchValue, this.original);
  1152. matches.forEach((match) => {
  1153. if (match.index != null) {
  1154. const replacement = getReplacement(match, this.original);
  1155. if (replacement !== match[0]) {
  1156. this.overwrite(match.index, match.index + match[0].length, replacement);
  1157. }
  1158. }
  1159. });
  1160. } else {
  1161. const match = this.original.match(searchValue);
  1162. if (match && match.index != null) {
  1163. const replacement = getReplacement(match, this.original);
  1164. if (replacement !== match[0]) {
  1165. this.overwrite(match.index, match.index + match[0].length, replacement);
  1166. }
  1167. }
  1168. }
  1169. return this;
  1170. }
  1171. _replaceString(string, replacement) {
  1172. const { original } = this;
  1173. const index = original.indexOf(string);
  1174. if (index !== -1) {
  1175. this.overwrite(index, index + string.length, replacement);
  1176. }
  1177. return this;
  1178. }
  1179. replace(searchValue, replacement) {
  1180. if (typeof searchValue === 'string') {
  1181. return this._replaceString(searchValue, replacement);
  1182. }
  1183. return this._replaceRegexp(searchValue, replacement);
  1184. }
  1185. _replaceAllString(string, replacement) {
  1186. const { original } = this;
  1187. const stringLength = string.length;
  1188. for (
  1189. let index = original.indexOf(string);
  1190. index !== -1;
  1191. index = original.indexOf(string, index + stringLength)
  1192. ) {
  1193. const previous = original.slice(index, index + stringLength);
  1194. if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
  1195. }
  1196. return this;
  1197. }
  1198. replaceAll(searchValue, replacement) {
  1199. if (typeof searchValue === 'string') {
  1200. return this._replaceAllString(searchValue, replacement);
  1201. }
  1202. if (!searchValue.global) {
  1203. throw new TypeError(
  1204. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1205. );
  1206. }
  1207. return this._replaceRegexp(searchValue, replacement);
  1208. }
  1209. }
  1210. const hasOwnProp = Object.prototype.hasOwnProperty;
  1211. let Bundle$1 = class Bundle {
  1212. constructor(options = {}) {
  1213. this.intro = options.intro || '';
  1214. this.separator = options.separator !== undefined ? options.separator : '\n';
  1215. this.sources = [];
  1216. this.uniqueSources = [];
  1217. this.uniqueSourceIndexByFilename = {};
  1218. }
  1219. addSource(source) {
  1220. if (source instanceof MagicString) {
  1221. return this.addSource({
  1222. content: source,
  1223. filename: source.filename,
  1224. separator: this.separator,
  1225. });
  1226. }
  1227. if (!isObject(source) || !source.content) {
  1228. throw new Error(
  1229. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1230. );
  1231. }
  1232. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1233. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1234. });
  1235. if (source.separator === undefined) {
  1236. // TODO there's a bunch of this sort of thing, needs cleaning up
  1237. source.separator = this.separator;
  1238. }
  1239. if (source.filename) {
  1240. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1241. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1242. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1243. } else {
  1244. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1245. if (source.content.original !== uniqueSource.content) {
  1246. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1247. }
  1248. }
  1249. }
  1250. this.sources.push(source);
  1251. return this;
  1252. }
  1253. append(str, options) {
  1254. this.addSource({
  1255. content: new MagicString(str),
  1256. separator: (options && options.separator) || '',
  1257. });
  1258. return this;
  1259. }
  1260. clone() {
  1261. const bundle = new Bundle({
  1262. intro: this.intro,
  1263. separator: this.separator,
  1264. });
  1265. this.sources.forEach((source) => {
  1266. bundle.addSource({
  1267. filename: source.filename,
  1268. content: source.content.clone(),
  1269. separator: source.separator,
  1270. });
  1271. });
  1272. return bundle;
  1273. }
  1274. generateDecodedMap(options = {}) {
  1275. const names = [];
  1276. let x_google_ignoreList = undefined;
  1277. this.sources.forEach((source) => {
  1278. Object.keys(source.content.storedNames).forEach((name) => {
  1279. if (!~names.indexOf(name)) names.push(name);
  1280. });
  1281. });
  1282. const mappings = new Mappings(options.hires);
  1283. if (this.intro) {
  1284. mappings.advance(this.intro);
  1285. }
  1286. this.sources.forEach((source, i) => {
  1287. if (i > 0) {
  1288. mappings.advance(this.separator);
  1289. }
  1290. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1291. const magicString = source.content;
  1292. const locate = getLocator(magicString.original);
  1293. if (magicString.intro) {
  1294. mappings.advance(magicString.intro);
  1295. }
  1296. magicString.firstChunk.eachNext((chunk) => {
  1297. const loc = locate(chunk.start);
  1298. if (chunk.intro.length) mappings.advance(chunk.intro);
  1299. if (source.filename) {
  1300. if (chunk.edited) {
  1301. mappings.addEdit(
  1302. sourceIndex,
  1303. chunk.content,
  1304. loc,
  1305. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1306. );
  1307. } else {
  1308. mappings.addUneditedChunk(
  1309. sourceIndex,
  1310. chunk,
  1311. magicString.original,
  1312. loc,
  1313. magicString.sourcemapLocations,
  1314. );
  1315. }
  1316. } else {
  1317. mappings.advance(chunk.content);
  1318. }
  1319. if (chunk.outro.length) mappings.advance(chunk.outro);
  1320. });
  1321. if (magicString.outro) {
  1322. mappings.advance(magicString.outro);
  1323. }
  1324. if (source.ignoreList && sourceIndex !== -1) {
  1325. if (x_google_ignoreList === undefined) {
  1326. x_google_ignoreList = [];
  1327. }
  1328. x_google_ignoreList.push(sourceIndex);
  1329. }
  1330. });
  1331. return {
  1332. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1333. sources: this.uniqueSources.map((source) => {
  1334. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1335. }),
  1336. sourcesContent: this.uniqueSources.map((source) => {
  1337. return options.includeContent ? source.content : null;
  1338. }),
  1339. names,
  1340. mappings: mappings.raw,
  1341. x_google_ignoreList,
  1342. };
  1343. }
  1344. generateMap(options) {
  1345. return new SourceMap(this.generateDecodedMap(options));
  1346. }
  1347. getIndentString() {
  1348. const indentStringCounts = {};
  1349. this.sources.forEach((source) => {
  1350. const indentStr = source.content._getRawIndentString();
  1351. if (indentStr === null) return;
  1352. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1353. indentStringCounts[indentStr] += 1;
  1354. });
  1355. return (
  1356. Object.keys(indentStringCounts).sort((a, b) => {
  1357. return indentStringCounts[a] - indentStringCounts[b];
  1358. })[0] || '\t'
  1359. );
  1360. }
  1361. indent(indentStr) {
  1362. if (!arguments.length) {
  1363. indentStr = this.getIndentString();
  1364. }
  1365. if (indentStr === '') return this; // noop
  1366. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1367. this.sources.forEach((source, i) => {
  1368. const separator = source.separator !== undefined ? source.separator : this.separator;
  1369. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1370. source.content.indent(indentStr, {
  1371. exclude: source.indentExclusionRanges,
  1372. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1373. });
  1374. trailingNewline = source.content.lastChar() === '\n';
  1375. });
  1376. if (this.intro) {
  1377. this.intro =
  1378. indentStr +
  1379. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1380. return index > 0 ? indentStr + match : match;
  1381. });
  1382. }
  1383. return this;
  1384. }
  1385. prepend(str) {
  1386. this.intro = str + this.intro;
  1387. return this;
  1388. }
  1389. toString() {
  1390. const body = this.sources
  1391. .map((source, i) => {
  1392. const separator = source.separator !== undefined ? source.separator : this.separator;
  1393. const str = (i > 0 ? separator : '') + source.content.toString();
  1394. return str;
  1395. })
  1396. .join('');
  1397. return this.intro + body;
  1398. }
  1399. isEmpty() {
  1400. if (this.intro.length && this.intro.trim()) return false;
  1401. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1402. return true;
  1403. }
  1404. length() {
  1405. return this.sources.reduce(
  1406. (length, source) => length + source.content.length(),
  1407. this.intro.length,
  1408. );
  1409. }
  1410. trimLines() {
  1411. return this.trim('[\\r\\n]');
  1412. }
  1413. trim(charType) {
  1414. return this.trimStart(charType).trimEnd(charType);
  1415. }
  1416. trimStart(charType) {
  1417. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1418. this.intro = this.intro.replace(rx, '');
  1419. if (!this.intro) {
  1420. let source;
  1421. let i = 0;
  1422. do {
  1423. source = this.sources[i++];
  1424. if (!source) {
  1425. break;
  1426. }
  1427. } while (!source.content.trimStartAborted(charType));
  1428. }
  1429. return this;
  1430. }
  1431. trimEnd(charType) {
  1432. const rx = new RegExp((charType || '\\s') + '+$');
  1433. let source;
  1434. let i = this.sources.length - 1;
  1435. do {
  1436. source = this.sources[i--];
  1437. if (!source) {
  1438. this.intro = this.intro.replace(rx, '');
  1439. break;
  1440. }
  1441. } while (!source.content.trimEndAborted(charType));
  1442. return this;
  1443. }
  1444. };
  1445. function treeshakeNode(node, code, start, end) {
  1446. code.remove(start, end);
  1447. node.removeAnnotations(code);
  1448. }
  1449. const NO_SEMICOLON = { isNoStatement: true };
  1450. // This assumes there are only white-space and comments between start and the string we are looking for
  1451. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  1452. let searchPos, charCodeAfterSlash;
  1453. searchPos = code.indexOf(searchString, start);
  1454. while (true) {
  1455. start = code.indexOf('/', start);
  1456. if (start === -1 || start >= searchPos)
  1457. return searchPos;
  1458. charCodeAfterSlash = code.charCodeAt(++start);
  1459. ++start;
  1460. // With our assumption, '/' always starts a comment. Determine comment type:
  1461. start =
  1462. charCodeAfterSlash === 47 /*"/"*/
  1463. ? code.indexOf('\n', start) + 1
  1464. : code.indexOf('*/', start) + 2;
  1465. if (start > searchPos) {
  1466. searchPos = code.indexOf(searchString, start);
  1467. }
  1468. }
  1469. }
  1470. const NON_WHITESPACE = /\S/g;
  1471. function findNonWhiteSpace(code, index) {
  1472. NON_WHITESPACE.lastIndex = index;
  1473. const result = NON_WHITESPACE.exec(code);
  1474. return result.index;
  1475. }
  1476. const WHITESPACE = /\s/;
  1477. function findLastWhiteSpaceReverse(code, start, end) {
  1478. while (true) {
  1479. if (start >= end) {
  1480. return end;
  1481. }
  1482. if (WHITESPACE.test(code[end - 1])) {
  1483. end--;
  1484. }
  1485. else {
  1486. return end;
  1487. }
  1488. }
  1489. }
  1490. // This assumes "code" only contains white-space and comments
  1491. // Returns position of line-comment if applicable
  1492. function findFirstLineBreakOutsideComment(code) {
  1493. let lineBreakPos, charCodeAfterSlash, start = 0;
  1494. lineBreakPos = code.indexOf('\n', start);
  1495. while (true) {
  1496. start = code.indexOf('/', start);
  1497. if (start === -1 || start > lineBreakPos)
  1498. return [lineBreakPos, lineBreakPos + 1];
  1499. // With our assumption, '/' always starts a comment. Determine comment type:
  1500. charCodeAfterSlash = code.charCodeAt(start + 1);
  1501. if (charCodeAfterSlash === 47 /*"/"*/)
  1502. return [start, lineBreakPos + 1];
  1503. start = code.indexOf('*/', start + 2) + 2;
  1504. if (start > lineBreakPos) {
  1505. lineBreakPos = code.indexOf('\n', start);
  1506. }
  1507. }
  1508. }
  1509. function renderStatementList(statements, code, start, end, options) {
  1510. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  1511. let nextNode = statements[0];
  1512. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  1513. if (nextNodeNeedsBoundaries) {
  1514. nextNodeStart =
  1515. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  1516. }
  1517. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  1518. currentNode = nextNode;
  1519. currentNodeStart = nextNodeStart;
  1520. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  1521. nextNode = statements[nextIndex];
  1522. nextNodeNeedsBoundaries =
  1523. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  1524. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  1525. nextNodeStart =
  1526. currentNode.end +
  1527. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  1528. if (currentNode.included) {
  1529. if (currentNodeNeedsBoundaries) {
  1530. currentNode.render(code, options, {
  1531. end: nextNodeStart,
  1532. start: currentNodeStart
  1533. });
  1534. }
  1535. else {
  1536. currentNode.render(code, options);
  1537. }
  1538. }
  1539. else {
  1540. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  1541. }
  1542. }
  1543. else {
  1544. currentNode.render(code, options);
  1545. }
  1546. }
  1547. }
  1548. // This assumes that the first character is not part of the first node
  1549. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  1550. const splitUpNodes = [];
  1551. let node, nextNodeStart, contentEnd, char;
  1552. let separator = start - 1;
  1553. for (const nextNode of nodes) {
  1554. if (node !== undefined) {
  1555. separator =
  1556. node.end +
  1557. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  1558. }
  1559. nextNodeStart = contentEnd =
  1560. separator +
  1561. 1 +
  1562. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  1563. while (((char = code.original.charCodeAt(nextNodeStart)),
  1564. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  1565. nextNodeStart++;
  1566. if (node !== undefined) {
  1567. splitUpNodes.push({
  1568. contentEnd,
  1569. end: nextNodeStart,
  1570. node,
  1571. separator,
  1572. start
  1573. });
  1574. }
  1575. node = nextNode;
  1576. start = nextNodeStart;
  1577. }
  1578. splitUpNodes.push({
  1579. contentEnd: end,
  1580. end,
  1581. node: node,
  1582. separator: null,
  1583. start
  1584. });
  1585. return splitUpNodes;
  1586. }
  1587. // This assumes there are only white-space and comments between start and end
  1588. function removeLineBreaks(code, start, end) {
  1589. while (true) {
  1590. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  1591. if (removeStart === -1) {
  1592. break;
  1593. }
  1594. code.remove(start + removeStart, (start += removeEnd));
  1595. }
  1596. }
  1597. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  1598. if (exportedVariables.length === 1 &&
  1599. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  1600. const variable = exportedVariables[0];
  1601. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  1602. }
  1603. else {
  1604. const fields = [];
  1605. for (const variable of exportedVariables) {
  1606. for (const exportName of exportNamesByVariable.get(variable)) {
  1607. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  1608. }
  1609. }
  1610. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  1611. }
  1612. }
  1613. // This is only invoked if there is exactly one export name
  1614. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  1615. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  1616. code.appendLeft(expressionEnd, ')');
  1617. }
  1618. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  1619. const { _, getDirectReturnIifeLeft } = options.snippets;
  1620. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  1621. code.appendLeft(expressionEnd, ')');
  1622. }
  1623. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  1624. const { _, getPropertyAccess } = options.snippets;
  1625. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  1626. if (needsParens) {
  1627. code.prependRight(expressionStart, '(');
  1628. code.appendLeft(expressionEnd, ')');
  1629. }
  1630. }
  1631. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  1632. const { _ } = options.snippets;
  1633. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  1634. if (needsParens) {
  1635. code.prependRight(expressionStart, '(');
  1636. code.appendLeft(expressionEnd, ')');
  1637. }
  1638. }
  1639. function getOrCreate(map, key, init) {
  1640. const existing = map.get(key);
  1641. if (existing !== undefined) {
  1642. return existing;
  1643. }
  1644. const value = init();
  1645. map.set(key, value);
  1646. return value;
  1647. }
  1648. function getNewSet() {
  1649. return new Set();
  1650. }
  1651. function getNewArray() {
  1652. return [];
  1653. }
  1654. const UnknownKey = Symbol('Unknown Key');
  1655. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1656. const UnknownInteger = Symbol('Unknown Integer');
  1657. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  1658. const EMPTY_PATH = [];
  1659. const UNKNOWN_PATH = [UnknownKey];
  1660. // For deoptimizations, this means we are modifying an unknown property but did
  1661. // not lose track of the object or are creating a setter/getter;
  1662. // For assignment effects it means we do not check for setter/getter effects
  1663. // but only if something is mutated that is included, which is relevant for
  1664. // Object.defineProperty
  1665. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1666. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1667. const EntitiesKey = Symbol('Entities');
  1668. class EntityPathTracker {
  1669. constructor() {
  1670. this.entityPaths = Object.create(null, {
  1671. [EntitiesKey]: { value: new Set() }
  1672. });
  1673. }
  1674. trackEntityAtPathAndGetIfTracked(path, entity) {
  1675. const trackedEntities = this.getEntities(path);
  1676. if (trackedEntities.has(entity))
  1677. return true;
  1678. trackedEntities.add(entity);
  1679. return false;
  1680. }
  1681. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1682. const trackedEntities = this.getEntities(path);
  1683. if (trackedEntities.has(entity))
  1684. return returnIfTracked;
  1685. trackedEntities.add(entity);
  1686. const result = onUntracked();
  1687. trackedEntities.delete(entity);
  1688. return result;
  1689. }
  1690. getEntities(path) {
  1691. let currentPaths = this.entityPaths;
  1692. for (const pathSegment of path) {
  1693. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1694. [EntitiesKey]: { value: new Set() }
  1695. });
  1696. }
  1697. return currentPaths[EntitiesKey];
  1698. }
  1699. }
  1700. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  1701. class DiscriminatedPathTracker {
  1702. constructor() {
  1703. this.entityPaths = Object.create(null, {
  1704. [EntitiesKey]: { value: new Map() }
  1705. });
  1706. }
  1707. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1708. let currentPaths = this.entityPaths;
  1709. for (const pathSegment of path) {
  1710. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1711. [EntitiesKey]: { value: new Map() }
  1712. });
  1713. }
  1714. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  1715. if (trackedEntities.has(entity))
  1716. return true;
  1717. trackedEntities.add(entity);
  1718. return false;
  1719. }
  1720. }
  1721. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: EMPTY_OBJECT });
  1722. class IncludedFullPathTracker {
  1723. constructor() {
  1724. this.includedPaths = null;
  1725. }
  1726. includePathAndGetIfIncluded(path) {
  1727. let included = true;
  1728. let parent = this;
  1729. let parentSegment = 'includedPaths';
  1730. let currentPaths = (this.includedPaths ||=
  1731. ((included = false), Object.create(null)));
  1732. for (const pathSegment of path) {
  1733. // This means from here, all paths are included
  1734. if (currentPaths[UnknownKey]) {
  1735. return true;
  1736. }
  1737. // Including UnknownKey automatically includes all nested paths.
  1738. // From above, we know that UnknownKey is not included yet.
  1739. if (typeof pathSegment === 'symbol') {
  1740. // Hopefully, this saves some memory over just setting
  1741. // currentPaths[UnknownKey] = EMPTY_OBJECT
  1742. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  1743. return false;
  1744. }
  1745. parent = currentPaths;
  1746. parentSegment = pathSegment;
  1747. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  1748. }
  1749. return included;
  1750. }
  1751. }
  1752. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  1753. [UnknownKey]: true
  1754. });
  1755. class IncludedTopLevelPathTracker {
  1756. constructor() {
  1757. this.includedPaths = null;
  1758. }
  1759. includePathAndGetIfIncluded(path) {
  1760. let included = true;
  1761. const includedPaths = (this.includedPaths ||=
  1762. ((included = false), Object.create(null)));
  1763. if (includedPaths[UnknownKey]) {
  1764. return true;
  1765. }
  1766. const [firstPathSegment, secondPathSegment] = path;
  1767. if (!firstPathSegment) {
  1768. return included;
  1769. }
  1770. if (typeof firstPathSegment === 'symbol') {
  1771. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  1772. return false;
  1773. }
  1774. if (secondPathSegment) {
  1775. if (includedPaths[firstPathSegment] === UnknownKey) {
  1776. return true;
  1777. }
  1778. includedPaths[firstPathSegment] = UnknownKey;
  1779. return false;
  1780. }
  1781. if (includedPaths[firstPathSegment]) {
  1782. return true;
  1783. }
  1784. includedPaths[firstPathSegment] = true;
  1785. return false;
  1786. }
  1787. includeAllPaths(entity, context, basePath) {
  1788. const { includedPaths } = this;
  1789. if (includedPaths) {
  1790. if (includedPaths[UnknownKey]) {
  1791. entity.includePath([...basePath, UnknownKey], context);
  1792. }
  1793. else {
  1794. const inclusionEntries = Object.entries(includedPaths);
  1795. if (inclusionEntries.length === 0) {
  1796. entity.includePath(basePath, context);
  1797. }
  1798. else {
  1799. for (const [key, value] of inclusionEntries) {
  1800. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  1801. }
  1802. }
  1803. }
  1804. }
  1805. }
  1806. }
  1807. /** @import { Node } from 'estree' */
  1808. /**
  1809. * @param {Node} node
  1810. * @param {Node} parent
  1811. * @returns {boolean}
  1812. */
  1813. function is_reference(node, parent) {
  1814. if (node.type === 'MemberExpression') {
  1815. return !node.computed && is_reference(node.object, node);
  1816. }
  1817. if (node.type !== 'Identifier') return false;
  1818. switch (parent?.type) {
  1819. // disregard `bar` in `foo.bar`
  1820. case 'MemberExpression':
  1821. return parent.computed || node === parent.object;
  1822. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  1823. case 'MethodDefinition':
  1824. return parent.computed;
  1825. // disregard the `meta` in `import.meta`
  1826. case 'MetaProperty':
  1827. return parent.meta === node;
  1828. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  1829. case 'PropertyDefinition':
  1830. return parent.computed || node === parent.value;
  1831. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  1832. case 'Property':
  1833. return parent.computed || node === parent.value;
  1834. // disregard the `bar` in `export { foo as bar }` or
  1835. // the foo in `import { foo as bar }`
  1836. case 'ExportSpecifier':
  1837. case 'ImportSpecifier':
  1838. return node === parent.local;
  1839. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  1840. case 'LabeledStatement':
  1841. case 'BreakStatement':
  1842. case 'ContinueStatement':
  1843. return false;
  1844. default:
  1845. return true;
  1846. }
  1847. }
  1848. function createInclusionContext() {
  1849. return {
  1850. brokenFlow: false,
  1851. hasBreak: false,
  1852. hasContinue: false,
  1853. includedCallArguments: new Set(),
  1854. includedLabels: new Set(),
  1855. withinTopLevelAwait: false
  1856. };
  1857. }
  1858. function createHasEffectsContext() {
  1859. return {
  1860. accessed: new EntityPathTracker(),
  1861. assigned: new EntityPathTracker(),
  1862. brokenFlow: false,
  1863. called: new DiscriminatedPathTracker(),
  1864. hasBreak: false,
  1865. hasContinue: false,
  1866. ignore: {
  1867. breaks: false,
  1868. continues: false,
  1869. labels: new Set(),
  1870. returnYield: false,
  1871. this: false
  1872. },
  1873. includedLabels: new Set(),
  1874. instantiated: new DiscriminatedPathTracker(),
  1875. replacedVariableInits: new Map()
  1876. };
  1877. }
  1878. function isFlagSet(flags, flag) {
  1879. return (flags & flag) !== 0;
  1880. }
  1881. function setFlag(flags, flag, value) {
  1882. return (flags & ~flag) | (-value & flag);
  1883. }
  1884. const UnknownValue = Symbol('Unknown Value');
  1885. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1886. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  1887. class ExpressionEntity {
  1888. constructor() {
  1889. this.flags = 0;
  1890. }
  1891. get included() {
  1892. return isFlagSet(this.flags, 1 /* Flag.included */);
  1893. }
  1894. set included(value) {
  1895. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  1896. }
  1897. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  1898. deoptimizeInteraction(interaction);
  1899. }
  1900. deoptimizePath(_path) { }
  1901. /**
  1902. * If possible it returns a stringifyable literal value for this node that
  1903. * can be used for inlining or comparing values. Otherwise, it should return
  1904. * UnknownValue.
  1905. */
  1906. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1907. return UnknownValue;
  1908. }
  1909. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1910. return UNKNOWN_RETURN_EXPRESSION;
  1911. }
  1912. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1913. return true;
  1914. }
  1915. include(context, _includeChildrenRecursively, _options) {
  1916. if (!this.included)
  1917. this.includeNode(context);
  1918. }
  1919. includeNode(_context) {
  1920. this.included = true;
  1921. }
  1922. includePath(_path, context) {
  1923. if (!this.included)
  1924. this.includeNode(context);
  1925. }
  1926. /* We are both including and including an unknown path here as the former
  1927. * ensures that nested nodes are included while the latter ensures that all
  1928. * paths of the expression are included.
  1929. * */
  1930. includeCallArguments(interaction, context) {
  1931. includeInteraction(interaction, context);
  1932. }
  1933. shouldBeIncluded(_context) {
  1934. return true;
  1935. }
  1936. }
  1937. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1938. })();
  1939. const UNKNOWN_RETURN_EXPRESSION = [
  1940. UNKNOWN_EXPRESSION,
  1941. false
  1942. ];
  1943. const deoptimizeInteraction = (interaction) => {
  1944. for (const argument of interaction.args) {
  1945. argument?.deoptimizePath(UNKNOWN_PATH);
  1946. }
  1947. };
  1948. const includeInteraction = ({ args }, context) => {
  1949. // We do not re-include the "this" argument as we expect this is already
  1950. // re-included at the call site
  1951. args[0]?.includePath(UNKNOWN_PATH, context);
  1952. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  1953. const argument = args[argumentIndex];
  1954. if (argument) {
  1955. argument.includePath(UNKNOWN_PATH, context);
  1956. argument.include(context, false);
  1957. }
  1958. }
  1959. };
  1960. const INTERACTION_ACCESSED = 0;
  1961. const INTERACTION_ASSIGNED = 1;
  1962. const INTERACTION_CALLED = 2;
  1963. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1964. args: [null],
  1965. type: INTERACTION_ACCESSED
  1966. };
  1967. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1968. args: [null, UNKNOWN_EXPRESSION],
  1969. type: INTERACTION_ASSIGNED
  1970. };
  1971. // While this is technically a call without arguments, we can compare against
  1972. // this reference in places where precise values or this argument would make a
  1973. // difference
  1974. const NODE_INTERACTION_UNKNOWN_CALL = {
  1975. args: [null],
  1976. type: INTERACTION_CALLED,
  1977. withNew: false
  1978. };
  1979. const PureFunctionKey = Symbol('PureFunction');
  1980. const getPureFunctions = ({ treeshake }) => {
  1981. const pureFunctions = Object.create(null);
  1982. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  1983. let currentFunctions = pureFunctions;
  1984. for (const pathSegment of functionName.split('.')) {
  1985. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  1986. }
  1987. currentFunctions[PureFunctionKey] = true;
  1988. }
  1989. return pureFunctions;
  1990. };
  1991. class Variable extends ExpressionEntity {
  1992. markReassigned() {
  1993. this.isReassigned = true;
  1994. }
  1995. constructor(name) {
  1996. super();
  1997. this.name = name;
  1998. this.alwaysRendered = false;
  1999. this.forbiddenNames = null;
  2000. this.globalName = null;
  2001. this.initReached = false;
  2002. this.isId = false;
  2003. this.kind = null;
  2004. this.renderBaseName = null;
  2005. this.renderName = null;
  2006. this.isReassigned = false;
  2007. this.onlyFunctionCallUsed = true;
  2008. }
  2009. /**
  2010. * Binds identifiers that reference this variable to this variable.
  2011. * Necessary to be able to change variable names.
  2012. */
  2013. addReference(_identifier) { }
  2014. /**
  2015. * Check if the identifier variable is only used as function call
  2016. * @returns true if the variable is only used as function call
  2017. */
  2018. getOnlyFunctionCallUsed() {
  2019. return this.onlyFunctionCallUsed;
  2020. }
  2021. /**
  2022. * Collect the places where the identifier variable is used
  2023. * @param usedPlace Where the variable is used
  2024. */
  2025. addUsedPlace(usedPlace) {
  2026. const isFunctionCall = usedPlace.parent.type === CallExpression$1 &&
  2027. usedPlace.parent.callee === usedPlace;
  2028. if (!isFunctionCall && usedPlace.parent.type !== ExportDefaultDeclaration$1) {
  2029. this.onlyFunctionCallUsed = false;
  2030. }
  2031. }
  2032. /**
  2033. * Prevent this variable from being renamed to this name to avoid name
  2034. * collisions
  2035. */
  2036. forbidName(name) {
  2037. (this.forbiddenNames ||= new Set()).add(name);
  2038. }
  2039. getBaseVariableName() {
  2040. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  2041. this.renderBaseName ||
  2042. this.renderName ||
  2043. this.name);
  2044. }
  2045. getName(getPropertyAccess, useOriginalName) {
  2046. if (this.globalName) {
  2047. return this.globalName;
  2048. }
  2049. if (useOriginalName?.(this)) {
  2050. return this.name;
  2051. }
  2052. if (this.renderedLikeHoisted) {
  2053. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  2054. }
  2055. const name = this.renderName || this.name;
  2056. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2057. }
  2058. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2059. return type !== INTERACTION_ACCESSED || path.length > 0;
  2060. }
  2061. /**
  2062. * Marks this variable as being part of the bundle, which is usually the case
  2063. * when one of its identifiers becomes part of the bundle. Returns true if it
  2064. * has not been included previously. Once a variable is included, it should
  2065. * take care all its declarations are included.
  2066. */
  2067. includePath(path, context) {
  2068. this.included = true;
  2069. this.renderedLikeHoisted?.includePath(path, context);
  2070. }
  2071. /**
  2072. * Links the rendered name of this variable to another variable and includes
  2073. * this variable if the other variable is included.
  2074. */
  2075. renderLikeHoisted(variable) {
  2076. this.renderedLikeHoisted = variable;
  2077. }
  2078. markCalledFromTryStatement() { }
  2079. setRenderNames(baseName, name) {
  2080. this.renderBaseName = baseName;
  2081. this.renderName = name;
  2082. }
  2083. }
  2084. class ExternalVariable extends Variable {
  2085. constructor(module, name) {
  2086. super(name);
  2087. this.referenced = false;
  2088. this.module = module;
  2089. this.isNamespace = name === '*';
  2090. }
  2091. addReference(identifier) {
  2092. this.referenced = true;
  2093. if (this.name === 'default' || this.name === '*') {
  2094. this.module.suggestName(identifier.name);
  2095. }
  2096. }
  2097. hasEffectsOnInteractionAtPath(path, { type }) {
  2098. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2099. }
  2100. includePath(path, context) {
  2101. super.includePath(path, context);
  2102. this.module.used = true;
  2103. }
  2104. }
  2105. function cacheObjectGetters(object, getterProperties) {
  2106. for (const property of getterProperties) {
  2107. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  2108. Object.defineProperty(object, property, {
  2109. get() {
  2110. const value = propertyGetter.call(object);
  2111. // This replaces the getter with a fixed value for subsequent calls
  2112. Object.defineProperty(object, property, { value });
  2113. return value;
  2114. }
  2115. });
  2116. }
  2117. }
  2118. const RESERVED_NAMES = new Set([
  2119. 'await',
  2120. 'break',
  2121. 'case',
  2122. 'catch',
  2123. 'class',
  2124. 'const',
  2125. 'continue',
  2126. 'debugger',
  2127. 'default',
  2128. 'delete',
  2129. 'do',
  2130. 'else',
  2131. 'enum',
  2132. 'eval',
  2133. 'export',
  2134. 'extends',
  2135. 'false',
  2136. 'finally',
  2137. 'for',
  2138. 'function',
  2139. 'if',
  2140. 'implements',
  2141. 'import',
  2142. 'in',
  2143. 'instanceof',
  2144. 'interface',
  2145. 'let',
  2146. 'NaN',
  2147. 'new',
  2148. 'null',
  2149. 'package',
  2150. 'private',
  2151. 'protected',
  2152. 'public',
  2153. 'return',
  2154. 'static',
  2155. 'super',
  2156. 'switch',
  2157. 'this',
  2158. 'throw',
  2159. 'true',
  2160. 'try',
  2161. 'typeof',
  2162. 'undefined',
  2163. 'var',
  2164. 'void',
  2165. 'while',
  2166. 'with',
  2167. 'yield'
  2168. ]);
  2169. const illegalCharacters = /[^\w$]/g;
  2170. const startsWithDigit = (value) => /\d/.test(value[0]);
  2171. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  2172. function isLegal(value) {
  2173. if (needsEscape(value)) {
  2174. return false;
  2175. }
  2176. return !illegalCharacters.test(value);
  2177. }
  2178. function makeLegal(value) {
  2179. value = value
  2180. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2181. .replace(illegalCharacters, '_');
  2182. if (needsEscape(value))
  2183. value = `_${value}`;
  2184. return value || '_';
  2185. }
  2186. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  2187. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  2188. function stringifyObjectKeyIfNeeded(key) {
  2189. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2190. return key === '__proto__' ? '["__proto__"]' : key;
  2191. }
  2192. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  2193. return key;
  2194. }
  2195. return JSON.stringify(key);
  2196. }
  2197. function stringifyIdentifierIfNeeded(key) {
  2198. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2199. return key;
  2200. }
  2201. return JSON.stringify(key);
  2202. }
  2203. class ExternalModule {
  2204. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  2205. this.options = options;
  2206. this.id = id;
  2207. this.renormalizeRenderPath = renormalizeRenderPath;
  2208. this.dynamicImporters = [];
  2209. this.execIndex = Infinity;
  2210. this.exportedVariables = new Map();
  2211. this.importers = [];
  2212. this.reexported = false;
  2213. this.used = false;
  2214. this.declarations = new Map();
  2215. this.mostCommonSuggestion = 0;
  2216. this.nameSuggestions = new Map();
  2217. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2218. const { importers, dynamicImporters } = this;
  2219. this.info = {
  2220. ast: null,
  2221. attributes,
  2222. code: null,
  2223. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2224. dynamicallyImportedIds: EMPTY_ARRAY,
  2225. get dynamicImporters() {
  2226. return dynamicImporters.sort();
  2227. },
  2228. exportedBindings: null,
  2229. exports: null,
  2230. hasDefaultExport: null,
  2231. id,
  2232. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2233. implicitlyLoadedBefore: EMPTY_ARRAY,
  2234. importedIdResolutions: EMPTY_ARRAY,
  2235. importedIds: EMPTY_ARRAY,
  2236. get importers() {
  2237. return importers.sort();
  2238. },
  2239. isEntry: false,
  2240. isExternal: true,
  2241. isIncluded: null,
  2242. meta,
  2243. moduleSideEffects,
  2244. syntheticNamedExports: false
  2245. };
  2246. }
  2247. cacheInfoGetters() {
  2248. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  2249. }
  2250. getVariableForExportName(name) {
  2251. const declaration = this.declarations.get(name);
  2252. if (declaration)
  2253. return [declaration];
  2254. const externalVariable = new ExternalVariable(this, name);
  2255. this.declarations.set(name, externalVariable);
  2256. this.exportedVariables.set(externalVariable, name);
  2257. return [externalVariable];
  2258. }
  2259. suggestName(name) {
  2260. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2261. this.nameSuggestions.set(name, value);
  2262. if (value > this.mostCommonSuggestion) {
  2263. this.mostCommonSuggestion = value;
  2264. this.suggestedVariableName = name;
  2265. }
  2266. }
  2267. warnUnusedImports() {
  2268. const unused = [...this.declarations]
  2269. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2270. .map(([name]) => name);
  2271. if (unused.length === 0)
  2272. return;
  2273. const importersSet = new Set();
  2274. for (const name of unused) {
  2275. for (const importer of this.declarations.get(name).module.importers) {
  2276. importersSet.add(importer);
  2277. }
  2278. }
  2279. const importersArray = [...importersSet];
  2280. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  2281. }
  2282. }
  2283. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  2284. baseModule.isExecuted = true;
  2285. const modules = [baseModule];
  2286. const visitedModules = new Set();
  2287. for (const module of modules) {
  2288. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  2289. if (!(dependency instanceof ExternalModule) &&
  2290. !dependency.isExecuted &&
  2291. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  2292. !visitedModules.has(dependency.id)) {
  2293. dependency.isExecuted = true;
  2294. visitedModules.add(dependency.id);
  2295. modules.push(dependency);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. const doNothing = () => { };
  2301. // This file is generated by scripts/generate-child-node-keys.js.
  2302. // Do not edit this file directly.
  2303. const childNodeKeys = {
  2304. ArrayExpression: ['elements'],
  2305. ArrayPattern: ['elements'],
  2306. ArrowFunctionExpression: ['params', 'body'],
  2307. AssignmentExpression: ['left', 'right'],
  2308. AssignmentPattern: ['left', 'right'],
  2309. AwaitExpression: ['argument'],
  2310. BinaryExpression: ['left', 'right'],
  2311. BlockStatement: ['body'],
  2312. BreakStatement: ['label'],
  2313. CallExpression: ['callee', 'arguments'],
  2314. CatchClause: ['param', 'body'],
  2315. ChainExpression: ['expression'],
  2316. ClassBody: ['body'],
  2317. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  2318. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  2319. ConditionalExpression: ['test', 'consequent', 'alternate'],
  2320. ContinueStatement: ['label'],
  2321. DebuggerStatement: [],
  2322. Decorator: ['expression'],
  2323. DoWhileStatement: ['body', 'test'],
  2324. EmptyStatement: [],
  2325. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  2326. ExportDefaultDeclaration: ['declaration'],
  2327. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  2328. ExportSpecifier: ['local', 'exported'],
  2329. ExpressionStatement: ['expression'],
  2330. ForInStatement: ['left', 'right', 'body'],
  2331. ForOfStatement: ['left', 'right', 'body'],
  2332. ForStatement: ['init', 'test', 'update', 'body'],
  2333. FunctionDeclaration: ['id', 'params', 'body'],
  2334. FunctionExpression: ['id', 'params', 'body'],
  2335. Identifier: [],
  2336. IfStatement: ['test', 'consequent', 'alternate'],
  2337. ImportAttribute: ['key', 'value'],
  2338. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  2339. ImportDefaultSpecifier: ['local'],
  2340. ImportExpression: ['source', 'options'],
  2341. ImportNamespaceSpecifier: ['local'],
  2342. ImportSpecifier: ['imported', 'local'],
  2343. JSXAttribute: ['name', 'value'],
  2344. JSXClosingElement: ['name'],
  2345. JSXClosingFragment: [],
  2346. JSXElement: ['openingElement', 'children', 'closingElement'],
  2347. JSXEmptyExpression: [],
  2348. JSXExpressionContainer: ['expression'],
  2349. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  2350. JSXIdentifier: [],
  2351. JSXMemberExpression: ['object', 'property'],
  2352. JSXNamespacedName: ['namespace', 'name'],
  2353. JSXOpeningElement: ['name', 'attributes'],
  2354. JSXOpeningFragment: [],
  2355. JSXSpreadAttribute: ['argument'],
  2356. JSXSpreadChild: ['expression'],
  2357. JSXText: [],
  2358. LabeledStatement: ['label', 'body'],
  2359. Literal: [],
  2360. LogicalExpression: ['left', 'right'],
  2361. MemberExpression: ['object', 'property'],
  2362. MetaProperty: ['meta', 'property'],
  2363. MethodDefinition: ['decorators', 'key', 'value'],
  2364. NewExpression: ['callee', 'arguments'],
  2365. ObjectExpression: ['properties'],
  2366. ObjectPattern: ['properties'],
  2367. PanicError: [],
  2368. ParseError: [],
  2369. PrivateIdentifier: [],
  2370. Program: ['body'],
  2371. Property: ['key', 'value'],
  2372. PropertyDefinition: ['decorators', 'key', 'value'],
  2373. RestElement: ['argument'],
  2374. ReturnStatement: ['argument'],
  2375. SequenceExpression: ['expressions'],
  2376. SpreadElement: ['argument'],
  2377. StaticBlock: ['body'],
  2378. Super: [],
  2379. SwitchCase: ['test', 'consequent'],
  2380. SwitchStatement: ['discriminant', 'cases'],
  2381. TaggedTemplateExpression: ['tag', 'quasi'],
  2382. TemplateElement: [],
  2383. TemplateLiteral: ['quasis', 'expressions'],
  2384. ThisExpression: [],
  2385. ThrowStatement: ['argument'],
  2386. TryStatement: ['block', 'handler', 'finalizer'],
  2387. UnaryExpression: ['argument'],
  2388. UpdateExpression: ['argument'],
  2389. VariableDeclaration: ['declarations'],
  2390. VariableDeclarator: ['id', 'init'],
  2391. WhileStatement: ['test', 'body'],
  2392. YieldExpression: ['argument']
  2393. };
  2394. const INCLUDE_PARAMETERS = 'variables';
  2395. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  2396. class NodeBase extends ExpressionEntity {
  2397. /**
  2398. * Nodes can apply custom deoptimizations once they become part of the
  2399. * executed code. To do this, they must initialize this as false, implement
  2400. * applyDeoptimizations and call this from include and hasEffects if they have
  2401. * custom handlers
  2402. */
  2403. get deoptimized() {
  2404. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  2405. }
  2406. set deoptimized(value) {
  2407. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  2408. }
  2409. constructor(parent, parentScope) {
  2410. super();
  2411. this.parent = parent;
  2412. this.scope = parentScope;
  2413. this.createScope(parentScope);
  2414. }
  2415. addExportedVariables(_variables, _exportNamesByVariable) { }
  2416. /**
  2417. * Override this to bind assignments to variables and do any initialisations
  2418. * that require the scopes to be populated with variables.
  2419. */
  2420. bind() {
  2421. for (const key of childNodeKeys[this.type]) {
  2422. const value = this[key];
  2423. if (Array.isArray(value)) {
  2424. for (const child of value) {
  2425. child?.bind();
  2426. }
  2427. }
  2428. else if (value) {
  2429. value.bind();
  2430. }
  2431. }
  2432. }
  2433. /**
  2434. * Override if this node should receive a different scope than the parent
  2435. * scope.
  2436. */
  2437. createScope(parentScope) {
  2438. this.scope = parentScope;
  2439. }
  2440. hasEffects(context) {
  2441. if (!this.deoptimized)
  2442. this.applyDeoptimizations();
  2443. for (const key of childNodeKeys[this.type]) {
  2444. const value = this[key];
  2445. if (value === null)
  2446. continue;
  2447. if (Array.isArray(value)) {
  2448. for (const child of value) {
  2449. if (child?.hasEffects(context))
  2450. return true;
  2451. }
  2452. }
  2453. else if (value.hasEffects(context))
  2454. return true;
  2455. }
  2456. return false;
  2457. }
  2458. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  2459. return (this.hasEffects(context) ||
  2460. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  2461. }
  2462. include(context, includeChildrenRecursively, _options) {
  2463. if (!this.included)
  2464. this.includeNode(context);
  2465. for (const key of childNodeKeys[this.type]) {
  2466. const value = this[key];
  2467. if (value === null)
  2468. continue;
  2469. if (Array.isArray(value)) {
  2470. for (const child of value) {
  2471. child?.include(context, includeChildrenRecursively);
  2472. }
  2473. }
  2474. else {
  2475. value.include(context, includeChildrenRecursively);
  2476. }
  2477. }
  2478. }
  2479. includeNode(context) {
  2480. this.included = true;
  2481. if (!this.deoptimized)
  2482. this.applyDeoptimizations();
  2483. for (const key of childNodeKeys[this.type]) {
  2484. const value = this[key];
  2485. if (value === null)
  2486. continue;
  2487. if (Array.isArray(value)) {
  2488. for (const child of value) {
  2489. child?.includePath(UNKNOWN_PATH, context);
  2490. }
  2491. }
  2492. else {
  2493. value.includePath(UNKNOWN_PATH, context);
  2494. }
  2495. }
  2496. }
  2497. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  2498. this.include(context, includeChildrenRecursively);
  2499. }
  2500. /**
  2501. * Override to perform special initialisation steps after the scope is
  2502. * initialised
  2503. */
  2504. initialise() {
  2505. this.scope.context.magicString.addSourcemapLocation(this.start);
  2506. this.scope.context.magicString.addSourcemapLocation(this.end);
  2507. }
  2508. parseNode(esTreeNode) {
  2509. for (const [key, value] of Object.entries(esTreeNode)) {
  2510. // Skip properties defined on the class already.
  2511. // This way, we can override this function to add custom initialisation and then call super.parseNode
  2512. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  2513. // in bitfields. Those are still assigned from the value in the esTreeNode.
  2514. if (this.hasOwnProperty(key))
  2515. continue;
  2516. if (key.charCodeAt(0) === 95 /* _ */) {
  2517. if (key === ANNOTATION_KEY) {
  2518. this.annotations = value;
  2519. }
  2520. else if (key === INVALID_ANNOTATION_KEY) {
  2521. this.invalidAnnotations = value;
  2522. }
  2523. }
  2524. else if (typeof value !== 'object' || value === null) {
  2525. this[key] = value;
  2526. }
  2527. else if (Array.isArray(value)) {
  2528. this[key] = new Array(value.length);
  2529. let index = 0;
  2530. for (const child of value) {
  2531. this[key][index++] =
  2532. child === null
  2533. ? null
  2534. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  2535. }
  2536. }
  2537. else {
  2538. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  2539. }
  2540. }
  2541. // extend child keys for unknown node types
  2542. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  2543. this.initialise();
  2544. return this;
  2545. }
  2546. removeAnnotations(code) {
  2547. if (this.annotations) {
  2548. for (const annotation of this.annotations) {
  2549. code.remove(annotation.start, annotation.end);
  2550. }
  2551. }
  2552. }
  2553. render(code, options) {
  2554. for (const key of childNodeKeys[this.type]) {
  2555. const value = this[key];
  2556. if (value === null)
  2557. continue;
  2558. if (Array.isArray(value)) {
  2559. for (const child of value) {
  2560. child?.render(code, options);
  2561. }
  2562. }
  2563. else {
  2564. value.render(code, options);
  2565. }
  2566. }
  2567. }
  2568. setAssignedValue(value) {
  2569. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  2570. }
  2571. shouldBeIncluded(context) {
  2572. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2573. }
  2574. /**
  2575. * Just deoptimize everything by default so that when e.g. we do not track
  2576. * something properly, it is deoptimized.
  2577. * @protected
  2578. */
  2579. applyDeoptimizations() {
  2580. this.deoptimized = true;
  2581. for (const key of childNodeKeys[this.type]) {
  2582. const value = this[key];
  2583. if (value === null)
  2584. continue;
  2585. if (Array.isArray(value)) {
  2586. for (const child of value) {
  2587. child?.deoptimizePath(UNKNOWN_PATH);
  2588. }
  2589. }
  2590. else {
  2591. value.deoptimizePath(UNKNOWN_PATH);
  2592. }
  2593. }
  2594. this.scope.context.requestTreeshakingPass();
  2595. }
  2596. }
  2597. function createChildNodeKeysForNode(esTreeNode) {
  2598. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  2599. }
  2600. function onlyIncludeSelf() {
  2601. this.included = true;
  2602. if (!this.deoptimized)
  2603. this.applyDeoptimizations();
  2604. }
  2605. function onlyIncludeSelfNoDeoptimize() {
  2606. this.included = true;
  2607. }
  2608. function doNotDeoptimize() {
  2609. this.deoptimized = true;
  2610. }
  2611. function isObjectExpressionNode(node) {
  2612. return node instanceof NodeBase && node.type === ObjectExpression$1;
  2613. }
  2614. function isPropertyNode(node) {
  2615. return node.type === Property$1;
  2616. }
  2617. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2618. return Object.create(inheritedDescriptions, memberDescriptions);
  2619. }
  2620. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  2621. getLiteralValueAtPath(path) {
  2622. return path.length > 0 ? UnknownValue : undefined;
  2623. }
  2624. })();
  2625. const returnsUnknown = {
  2626. value: {
  2627. hasEffectsWhenCalled: null,
  2628. returns: UNKNOWN_EXPRESSION
  2629. }
  2630. };
  2631. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  2632. getReturnExpressionWhenCalledAtPath(path) {
  2633. if (path.length === 1) {
  2634. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2635. }
  2636. return UNKNOWN_RETURN_EXPRESSION;
  2637. }
  2638. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2639. if (interaction.type === INTERACTION_ACCESSED) {
  2640. return path.length > 1;
  2641. }
  2642. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2643. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  2644. }
  2645. return true;
  2646. }
  2647. })();
  2648. const returnsBoolean = {
  2649. value: {
  2650. hasEffectsWhenCalled: null,
  2651. returns: UNKNOWN_LITERAL_BOOLEAN
  2652. }
  2653. };
  2654. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  2655. getReturnExpressionWhenCalledAtPath(path) {
  2656. if (path.length === 1) {
  2657. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2658. }
  2659. return UNKNOWN_RETURN_EXPRESSION;
  2660. }
  2661. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2662. if (interaction.type === INTERACTION_ACCESSED) {
  2663. return path.length > 1;
  2664. }
  2665. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2666. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  2667. }
  2668. return true;
  2669. }
  2670. })();
  2671. const returnsNumber = {
  2672. value: {
  2673. hasEffectsWhenCalled: null,
  2674. returns: UNKNOWN_LITERAL_NUMBER
  2675. }
  2676. };
  2677. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  2678. getReturnExpressionWhenCalledAtPath(path) {
  2679. if (path.length === 1) {
  2680. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2681. }
  2682. return UNKNOWN_RETURN_EXPRESSION;
  2683. }
  2684. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2685. if (interaction.type === INTERACTION_ACCESSED) {
  2686. return path.length > 1;
  2687. }
  2688. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2689. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  2690. }
  2691. return true;
  2692. }
  2693. })();
  2694. const returnsString = {
  2695. value: {
  2696. hasEffectsWhenCalled: null,
  2697. returns: UNKNOWN_LITERAL_STRING
  2698. }
  2699. };
  2700. const stringReplace = {
  2701. value: {
  2702. hasEffectsWhenCalled({ args }, context) {
  2703. const argument1 = args[2];
  2704. return (args.length < 3 ||
  2705. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  2706. deoptimizeCache() { }
  2707. }) === 'symbol' &&
  2708. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  2709. },
  2710. returns: UNKNOWN_LITERAL_STRING
  2711. }
  2712. };
  2713. const objectMembers = assembleMemberDescriptions({
  2714. hasOwnProperty: returnsBoolean,
  2715. isPrototypeOf: returnsBoolean,
  2716. propertyIsEnumerable: returnsBoolean,
  2717. toLocaleString: returnsString,
  2718. toString: returnsString,
  2719. valueOf: returnsUnknown
  2720. });
  2721. const literalBooleanMembers = assembleMemberDescriptions({
  2722. valueOf: returnsBoolean
  2723. }, objectMembers);
  2724. const literalNumberMembers = assembleMemberDescriptions({
  2725. toExponential: returnsString,
  2726. toFixed: returnsString,
  2727. toLocaleString: returnsString,
  2728. toPrecision: returnsString,
  2729. valueOf: returnsNumber
  2730. }, objectMembers);
  2731. /**
  2732. * RegExp are stateful when they have the global or sticky flags set.
  2733. * But if we actually don't use them, the side effect does not matter.
  2734. * the check logic in `hasEffectsOnInteractionAtPath`.
  2735. */
  2736. const literalRegExpMembers = assembleMemberDescriptions({
  2737. exec: returnsUnknown,
  2738. test: returnsBoolean
  2739. }, objectMembers);
  2740. const literalStringMembers = assembleMemberDescriptions({
  2741. anchor: returnsString,
  2742. at: returnsUnknown,
  2743. big: returnsString,
  2744. blink: returnsString,
  2745. bold: returnsString,
  2746. charAt: returnsString,
  2747. charCodeAt: returnsNumber,
  2748. codePointAt: returnsUnknown,
  2749. concat: returnsString,
  2750. endsWith: returnsBoolean,
  2751. fixed: returnsString,
  2752. fontcolor: returnsString,
  2753. fontsize: returnsString,
  2754. includes: returnsBoolean,
  2755. indexOf: returnsNumber,
  2756. italics: returnsString,
  2757. lastIndexOf: returnsNumber,
  2758. link: returnsString,
  2759. localeCompare: returnsNumber,
  2760. match: returnsUnknown,
  2761. matchAll: returnsUnknown,
  2762. normalize: returnsString,
  2763. padEnd: returnsString,
  2764. padStart: returnsString,
  2765. repeat: returnsString,
  2766. replace: stringReplace,
  2767. replaceAll: stringReplace,
  2768. search: returnsNumber,
  2769. slice: returnsString,
  2770. small: returnsString,
  2771. split: returnsUnknown,
  2772. startsWith: returnsBoolean,
  2773. strike: returnsString,
  2774. sub: returnsString,
  2775. substr: returnsString,
  2776. substring: returnsString,
  2777. sup: returnsString,
  2778. toLocaleLowerCase: returnsString,
  2779. toLocaleUpperCase: returnsString,
  2780. toLowerCase: returnsString,
  2781. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  2782. toUpperCase: returnsString,
  2783. trim: returnsString,
  2784. trimEnd: returnsString,
  2785. trimLeft: returnsString,
  2786. trimRight: returnsString,
  2787. trimStart: returnsString,
  2788. valueOf: returnsString
  2789. }, objectMembers);
  2790. function getLiteralMembersForValue(value) {
  2791. if (value instanceof RegExp) {
  2792. return literalRegExpMembers;
  2793. }
  2794. switch (typeof value) {
  2795. case 'boolean': {
  2796. return literalBooleanMembers;
  2797. }
  2798. case 'number': {
  2799. return literalNumberMembers;
  2800. }
  2801. case 'string': {
  2802. return literalStringMembers;
  2803. }
  2804. }
  2805. return Object.create(null);
  2806. }
  2807. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  2808. if (typeof memberName !== 'string' || !members[memberName]) {
  2809. return true;
  2810. }
  2811. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  2812. }
  2813. function getMemberReturnExpressionWhenCalled(members, memberName) {
  2814. if (typeof memberName !== 'string' || !members[memberName])
  2815. return UNKNOWN_RETURN_EXPRESSION;
  2816. return [members[memberName].returns, false];
  2817. }
  2818. class Method extends ExpressionEntity {
  2819. constructor(description) {
  2820. super();
  2821. this.description = description;
  2822. }
  2823. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  2824. if (type === INTERACTION_CALLED && path.length === 0) {
  2825. if (this.description.mutatesSelfAsArray) {
  2826. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  2827. }
  2828. if (this.description.mutatesArgs) {
  2829. for (let index = 1; index < args.length; index++) {
  2830. args[index].deoptimizePath(UNKNOWN_PATH);
  2831. }
  2832. }
  2833. }
  2834. }
  2835. getReturnExpressionWhenCalledAtPath(path, { args }) {
  2836. if (path.length > 0) {
  2837. return UNKNOWN_RETURN_EXPRESSION;
  2838. }
  2839. return [
  2840. this.description.returnsPrimitive ||
  2841. (this.description.returns === 'self'
  2842. ? args[0] || UNKNOWN_EXPRESSION
  2843. : this.description.returns()),
  2844. false
  2845. ];
  2846. }
  2847. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  2848. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  2849. return true;
  2850. }
  2851. if (type === INTERACTION_CALLED) {
  2852. if (this.description.mutatesSelfAsArray === true &&
  2853. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  2854. return true;
  2855. }
  2856. if (this.description.callsArgs) {
  2857. for (const argumentIndex of this.description.callsArgs) {
  2858. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  2859. return true;
  2860. }
  2861. }
  2862. }
  2863. }
  2864. return false;
  2865. }
  2866. }
  2867. const METHOD_RETURNS_BOOLEAN = [
  2868. new Method({
  2869. callsArgs: null,
  2870. mutatesArgs: false,
  2871. mutatesSelfAsArray: false,
  2872. returns: null,
  2873. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  2874. })
  2875. ];
  2876. const METHOD_RETURNS_STRING = [
  2877. new Method({
  2878. callsArgs: null,
  2879. mutatesArgs: false,
  2880. mutatesSelfAsArray: false,
  2881. returns: null,
  2882. returnsPrimitive: UNKNOWN_LITERAL_STRING
  2883. })
  2884. ];
  2885. const METHOD_RETURNS_NUMBER = [
  2886. new Method({
  2887. callsArgs: null,
  2888. mutatesArgs: false,
  2889. mutatesSelfAsArray: false,
  2890. returns: null,
  2891. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2892. })
  2893. ];
  2894. const METHOD_RETURNS_UNKNOWN = [
  2895. new Method({
  2896. callsArgs: null,
  2897. mutatesArgs: false,
  2898. mutatesSelfAsArray: false,
  2899. returns: null,
  2900. returnsPrimitive: UNKNOWN_EXPRESSION
  2901. })
  2902. ];
  2903. const INTEGER_REG_EXP = /^\d+$/;
  2904. class ObjectEntity extends ExpressionEntity {
  2905. get hasLostTrack() {
  2906. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  2907. }
  2908. set hasLostTrack(value) {
  2909. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  2910. }
  2911. get hasUnknownDeoptimizedInteger() {
  2912. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  2913. }
  2914. set hasUnknownDeoptimizedInteger(value) {
  2915. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  2916. }
  2917. get hasUnknownDeoptimizedProperty() {
  2918. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  2919. }
  2920. set hasUnknownDeoptimizedProperty(value) {
  2921. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  2922. }
  2923. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  2924. // and we assume there are no setters or getters
  2925. constructor(properties, prototypeExpression, immutable = false) {
  2926. super();
  2927. this.prototypeExpression = prototypeExpression;
  2928. this.immutable = immutable;
  2929. this.additionalExpressionsToBeDeoptimized = new Set();
  2930. this.allProperties = [];
  2931. this.deoptimizedPaths = Object.create(null);
  2932. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  2933. this.gettersByKey = Object.create(null);
  2934. this.propertiesAndGettersByKey = Object.create(null);
  2935. this.propertiesAndSettersByKey = Object.create(null);
  2936. this.settersByKey = Object.create(null);
  2937. this.unknownIntegerProps = [];
  2938. this.unmatchableGetters = [];
  2939. this.unmatchablePropertiesAndGetters = [];
  2940. this.unmatchablePropertiesAndSetters = [];
  2941. this.unmatchableSetters = [];
  2942. if (Array.isArray(properties)) {
  2943. this.buildPropertyMaps(properties);
  2944. }
  2945. else {
  2946. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  2947. for (const propertiesForKey of Object.values(properties)) {
  2948. this.allProperties.push(...propertiesForKey);
  2949. }
  2950. }
  2951. }
  2952. deoptimizeAllProperties(noAccessors) {
  2953. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  2954. if (noAccessors) {
  2955. this.hasUnknownDeoptimizedProperty = true;
  2956. }
  2957. else {
  2958. this.hasLostTrack = true;
  2959. }
  2960. if (isDeoptimized) {
  2961. return;
  2962. }
  2963. for (const properties of [
  2964. ...Object.values(this.propertiesAndGettersByKey),
  2965. ...Object.values(this.settersByKey)
  2966. ]) {
  2967. for (const property of properties) {
  2968. property.deoptimizePath(UNKNOWN_PATH);
  2969. }
  2970. }
  2971. // While the prototype itself cannot be mutated, each property can
  2972. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  2973. this.deoptimizeCachedEntities();
  2974. }
  2975. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  2976. const [key, ...subPath] = path;
  2977. const { args, type } = interaction;
  2978. if (this.hasLostTrack ||
  2979. // single paths that are deoptimized will not become getters or setters
  2980. ((type === INTERACTION_CALLED || path.length > 1) &&
  2981. (this.hasUnknownDeoptimizedProperty ||
  2982. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  2983. deoptimizeInteraction(interaction);
  2984. return;
  2985. }
  2986. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  2987. ? [
  2988. this.propertiesAndGettersByKey,
  2989. this.propertiesAndGettersByKey,
  2990. this.unmatchablePropertiesAndGetters
  2991. ]
  2992. : type === INTERACTION_ACCESSED
  2993. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  2994. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  2995. if (typeof key === 'string') {
  2996. if (propertiesForExactMatchByKey[key]) {
  2997. const properties = relevantPropertiesByKey[key];
  2998. if (properties) {
  2999. for (const property of properties) {
  3000. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3001. }
  3002. }
  3003. if (!this.immutable) {
  3004. for (const argument of args) {
  3005. if (argument) {
  3006. this.additionalExpressionsToBeDeoptimized.add(argument);
  3007. }
  3008. }
  3009. }
  3010. return;
  3011. }
  3012. for (const property of relevantUnmatchableProperties) {
  3013. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3014. }
  3015. if (INTEGER_REG_EXP.test(key)) {
  3016. for (const property of this.unknownIntegerProps) {
  3017. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3018. }
  3019. }
  3020. }
  3021. else {
  3022. for (const properties of [
  3023. ...Object.values(relevantPropertiesByKey),
  3024. relevantUnmatchableProperties
  3025. ]) {
  3026. for (const property of properties) {
  3027. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3028. }
  3029. }
  3030. for (const property of this.unknownIntegerProps) {
  3031. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3032. }
  3033. }
  3034. if (!this.immutable) {
  3035. for (const argument of args) {
  3036. if (argument) {
  3037. this.additionalExpressionsToBeDeoptimized.add(argument);
  3038. }
  3039. }
  3040. }
  3041. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3042. }
  3043. deoptimizeIntegerProperties() {
  3044. if (this.hasLostTrack ||
  3045. this.hasUnknownDeoptimizedProperty ||
  3046. this.hasUnknownDeoptimizedInteger) {
  3047. return;
  3048. }
  3049. this.hasUnknownDeoptimizedInteger = true;
  3050. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  3051. if (INTEGER_REG_EXP.test(key)) {
  3052. for (const property of propertiesAndGetters) {
  3053. property.deoptimizePath(UNKNOWN_PATH);
  3054. }
  3055. }
  3056. }
  3057. this.deoptimizeCachedIntegerEntities();
  3058. }
  3059. // Assumption: If only a specific path is deoptimized, no accessors are created
  3060. deoptimizePath(path) {
  3061. if (this.hasLostTrack || this.immutable) {
  3062. return;
  3063. }
  3064. const key = path[0];
  3065. if (path.length === 1) {
  3066. if (key === UnknownInteger) {
  3067. return this.deoptimizeIntegerProperties();
  3068. }
  3069. else if (typeof key !== 'string') {
  3070. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  3071. }
  3072. if (!this.deoptimizedPaths[key]) {
  3073. this.deoptimizedPaths[key] = true;
  3074. // we only deoptimizeCache exact matches as in all other cases,
  3075. // we do not return a literal value or return expression
  3076. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  3077. if (expressionsToBeDeoptimized) {
  3078. for (const expression of expressionsToBeDeoptimized) {
  3079. expression.deoptimizeCache();
  3080. }
  3081. }
  3082. }
  3083. }
  3084. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  3085. for (const property of typeof key === 'string'
  3086. ? [
  3087. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  3088. ...(this.settersByKey[key] || this.unmatchableSetters)
  3089. ]
  3090. : this.allProperties) {
  3091. property.deoptimizePath(subPath);
  3092. }
  3093. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  3094. }
  3095. getLiteralValueAtPath(path, recursionTracker, origin) {
  3096. if (path.length === 0) {
  3097. // This should actually be "UnknownTruthyValue". However, this currently
  3098. // causes an issue with TypeScript enums in files with moduleSideEffects:
  3099. // false because we cannot properly track whether a "var" has been
  3100. // initialized. This should be reverted once we can properly track this.
  3101. // return UnknownTruthyValue;
  3102. return UnknownValue;
  3103. }
  3104. const key = path[0];
  3105. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3106. if (expressionAtPath) {
  3107. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  3108. }
  3109. if (this.prototypeExpression) {
  3110. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  3111. }
  3112. if (path.length === 1) {
  3113. return undefined;
  3114. }
  3115. return UnknownValue;
  3116. }
  3117. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3118. if (path.length === 0) {
  3119. return UNKNOWN_RETURN_EXPRESSION;
  3120. }
  3121. const [key, ...subPath] = path;
  3122. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3123. if (expressionAtPath) {
  3124. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  3125. }
  3126. if (this.prototypeExpression) {
  3127. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3128. }
  3129. return UNKNOWN_RETURN_EXPRESSION;
  3130. }
  3131. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3132. const [key, ...subPath] = path;
  3133. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  3134. const expressionAtPath = this.getMemberExpression(key);
  3135. if (expressionAtPath) {
  3136. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  3137. }
  3138. if (this.prototypeExpression) {
  3139. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3140. }
  3141. return true;
  3142. }
  3143. if (key === UnknownNonAccessorKey)
  3144. return false;
  3145. if (this.hasLostTrack)
  3146. return true;
  3147. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  3148. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3149. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3150. if (typeof key === 'string') {
  3151. if (propertiesAndAccessorsByKey[key]) {
  3152. const accessors = accessorsByKey[key];
  3153. if (accessors) {
  3154. for (const accessor of accessors) {
  3155. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3156. return true;
  3157. }
  3158. }
  3159. return false;
  3160. }
  3161. for (const accessor of unmatchableAccessors) {
  3162. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  3163. return true;
  3164. }
  3165. }
  3166. }
  3167. else {
  3168. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  3169. for (const accessor of accessors) {
  3170. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3171. return true;
  3172. }
  3173. }
  3174. }
  3175. if (this.prototypeExpression) {
  3176. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3177. }
  3178. return false;
  3179. }
  3180. include(context, includeChildrenRecursively) {
  3181. this.included = true;
  3182. for (const property of this.allProperties) {
  3183. if (includeChildrenRecursively || property.shouldBeIncluded(context)) {
  3184. property.include(context, includeChildrenRecursively);
  3185. }
  3186. }
  3187. this.prototypeExpression?.include(context, includeChildrenRecursively);
  3188. }
  3189. includePath(path, context) {
  3190. this.included = true;
  3191. if (path.length === 0)
  3192. return;
  3193. const [key, ...subPath] = path;
  3194. const [includedMembers, includedPath] = typeof key === 'string'
  3195. ? [
  3196. new Set([
  3197. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  3198. ...(this.propertiesAndSettersByKey[key] || this.unmatchablePropertiesAndSetters)
  3199. ]),
  3200. subPath
  3201. ]
  3202. : [this.allProperties, UNKNOWN_PATH];
  3203. for (const property of includedMembers) {
  3204. property.includePath(includedPath, context);
  3205. }
  3206. this.prototypeExpression?.includePath(path, context);
  3207. }
  3208. buildPropertyMaps(properties) {
  3209. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  3210. for (let index = properties.length - 1; index >= 0; index--) {
  3211. const { key, kind, property } = properties[index];
  3212. allProperties.push(property);
  3213. if (typeof key === 'string') {
  3214. if (kind === 'set') {
  3215. if (!propertiesAndSettersByKey[key]) {
  3216. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3217. settersByKey[key] = [property, ...unmatchableSetters];
  3218. }
  3219. }
  3220. else if (kind === 'get') {
  3221. if (!propertiesAndGettersByKey[key]) {
  3222. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3223. gettersByKey[key] = [property, ...unmatchableGetters];
  3224. }
  3225. }
  3226. else {
  3227. if (!propertiesAndSettersByKey[key]) {
  3228. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3229. }
  3230. if (!propertiesAndGettersByKey[key]) {
  3231. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3232. }
  3233. }
  3234. }
  3235. else {
  3236. if (key === UnknownInteger) {
  3237. unknownIntegerProps.push(property);
  3238. continue;
  3239. }
  3240. if (kind === 'set')
  3241. unmatchableSetters.push(property);
  3242. if (kind === 'get')
  3243. unmatchableGetters.push(property);
  3244. if (kind !== 'get')
  3245. unmatchablePropertiesAndSetters.push(property);
  3246. if (kind !== 'set')
  3247. unmatchablePropertiesAndGetters.push(property);
  3248. }
  3249. }
  3250. }
  3251. deoptimizeCachedEntities() {
  3252. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  3253. for (const expression of expressionsToBeDeoptimized) {
  3254. expression.deoptimizeCache();
  3255. }
  3256. }
  3257. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3258. expression.deoptimizePath(UNKNOWN_PATH);
  3259. }
  3260. }
  3261. deoptimizeCachedIntegerEntities() {
  3262. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  3263. if (INTEGER_REG_EXP.test(key)) {
  3264. for (const expression of expressionsToBeDeoptimized) {
  3265. expression.deoptimizeCache();
  3266. }
  3267. }
  3268. }
  3269. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3270. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  3271. }
  3272. }
  3273. getMemberExpression(key) {
  3274. if (this.hasLostTrack ||
  3275. this.hasUnknownDeoptimizedProperty ||
  3276. typeof key !== 'string' ||
  3277. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  3278. this.deoptimizedPaths[key]) {
  3279. return UNKNOWN_EXPRESSION;
  3280. }
  3281. const properties = this.propertiesAndGettersByKey[key];
  3282. if (properties?.length === 1) {
  3283. return properties[0];
  3284. }
  3285. if (properties ||
  3286. this.unmatchablePropertiesAndGetters.length > 0 ||
  3287. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  3288. return UNKNOWN_EXPRESSION;
  3289. }
  3290. return null;
  3291. }
  3292. getMemberExpressionAndTrackDeopt(key, origin) {
  3293. if (typeof key !== 'string') {
  3294. return UNKNOWN_EXPRESSION;
  3295. }
  3296. const expression = this.getMemberExpression(key);
  3297. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  3298. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  3299. this.expressionsToBeDeoptimizedByKey[key] || []);
  3300. expressionsToBeDeoptimized.push(origin);
  3301. }
  3302. return expression;
  3303. }
  3304. }
  3305. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  3306. // This makes sure unknown properties are not handled as "undefined" but as
  3307. // "unknown" but without access side effects. An exception is done for numeric
  3308. // properties as we do not expect new builtin properties to be numbers, this
  3309. // will improve tree-shaking for out-of-bounds array properties
  3310. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  3311. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  3312. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  3313. deoptimizeInteraction(interaction);
  3314. }
  3315. }
  3316. getLiteralValueAtPath(path) {
  3317. // We ignore number properties as we do not expect new properties to be
  3318. // numbers and also want to keep handling out-of-bound array elements as
  3319. // "undefined"
  3320. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  3321. }
  3322. hasEffectsOnInteractionAtPath(path, { type }) {
  3323. return path.length > 1 || type === INTERACTION_CALLED;
  3324. }
  3325. })();
  3326. const OBJECT_PROTOTYPE = new ObjectEntity({
  3327. __proto__: null,
  3328. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  3329. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  3330. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  3331. toLocaleString: METHOD_RETURNS_STRING,
  3332. toString: METHOD_RETURNS_STRING,
  3333. valueOf: METHOD_RETURNS_UNKNOWN
  3334. }, OBJECT_PROTOTYPE_FALLBACK, true);
  3335. const NEW_ARRAY_PROPERTIES = [
  3336. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  3337. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3338. ];
  3339. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  3340. new Method({
  3341. callsArgs: [0],
  3342. mutatesArgs: false,
  3343. mutatesSelfAsArray: 'deopt-only',
  3344. returns: null,
  3345. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  3346. })
  3347. ];
  3348. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  3349. new Method({
  3350. callsArgs: [0],
  3351. mutatesArgs: false,
  3352. mutatesSelfAsArray: 'deopt-only',
  3353. returns: null,
  3354. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3355. })
  3356. ];
  3357. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  3358. new Method({
  3359. callsArgs: null,
  3360. mutatesArgs: false,
  3361. mutatesSelfAsArray: true,
  3362. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3363. returnsPrimitive: null
  3364. })
  3365. ];
  3366. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3367. new Method({
  3368. callsArgs: null,
  3369. mutatesArgs: false,
  3370. mutatesSelfAsArray: 'deopt-only',
  3371. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3372. returnsPrimitive: null
  3373. })
  3374. ];
  3375. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3376. new Method({
  3377. callsArgs: [0],
  3378. mutatesArgs: false,
  3379. mutatesSelfAsArray: 'deopt-only',
  3380. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3381. returnsPrimitive: null
  3382. })
  3383. ];
  3384. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  3385. new Method({
  3386. callsArgs: null,
  3387. mutatesArgs: true,
  3388. mutatesSelfAsArray: true,
  3389. returns: null,
  3390. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3391. })
  3392. ];
  3393. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  3394. new Method({
  3395. callsArgs: null,
  3396. mutatesArgs: false,
  3397. mutatesSelfAsArray: true,
  3398. returns: null,
  3399. returnsPrimitive: UNKNOWN_EXPRESSION
  3400. })
  3401. ];
  3402. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3403. new Method({
  3404. callsArgs: null,
  3405. mutatesArgs: false,
  3406. mutatesSelfAsArray: 'deopt-only',
  3407. returns: null,
  3408. returnsPrimitive: UNKNOWN_EXPRESSION
  3409. })
  3410. ];
  3411. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3412. new Method({
  3413. callsArgs: [0],
  3414. mutatesArgs: false,
  3415. mutatesSelfAsArray: 'deopt-only',
  3416. returns: null,
  3417. returnsPrimitive: UNKNOWN_EXPRESSION
  3418. })
  3419. ];
  3420. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  3421. new Method({
  3422. callsArgs: null,
  3423. mutatesArgs: false,
  3424. mutatesSelfAsArray: true,
  3425. returns: 'self',
  3426. returnsPrimitive: null
  3427. })
  3428. ];
  3429. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  3430. new Method({
  3431. callsArgs: [0],
  3432. mutatesArgs: false,
  3433. mutatesSelfAsArray: true,
  3434. returns: 'self',
  3435. returnsPrimitive: null
  3436. })
  3437. ];
  3438. const ARRAY_PROTOTYPE = new ObjectEntity({
  3439. __proto__: null,
  3440. // We assume that accessors have effects as we do not track the accessed value afterwards
  3441. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  3442. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3443. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  3444. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3445. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3446. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  3447. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3448. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3449. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3450. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3451. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3452. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3453. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3454. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3455. includes: METHOD_RETURNS_BOOLEAN,
  3456. indexOf: METHOD_RETURNS_NUMBER,
  3457. join: METHOD_RETURNS_STRING,
  3458. keys: METHOD_RETURNS_UNKNOWN,
  3459. lastIndexOf: METHOD_RETURNS_NUMBER,
  3460. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3461. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3462. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3463. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3464. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3465. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  3466. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3467. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3468. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3469. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  3470. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  3471. toLocaleString: METHOD_RETURNS_STRING,
  3472. toString: METHOD_RETURNS_STRING,
  3473. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3474. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  3475. }, OBJECT_PROTOTYPE, true);
  3476. class SpreadElement extends NodeBase {
  3477. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3478. if (path.length > 0) {
  3479. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  3480. }
  3481. }
  3482. hasEffects(context) {
  3483. if (!this.deoptimized)
  3484. this.applyDeoptimizations();
  3485. const { propertyReadSideEffects } = this.scope.context.options
  3486. .treeshake;
  3487. return (this.argument.hasEffects(context) ||
  3488. (propertyReadSideEffects &&
  3489. (propertyReadSideEffects === 'always' ||
  3490. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  3491. }
  3492. includeNode(context) {
  3493. this.included = true;
  3494. if (!this.deoptimized)
  3495. this.applyDeoptimizations();
  3496. this.argument.includePath(UNKNOWN_PATH, context);
  3497. }
  3498. applyDeoptimizations() {
  3499. this.deoptimized = true;
  3500. // Only properties of properties of the argument could become subject to reassignment
  3501. // This will also reassign the return values of iterators
  3502. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  3503. this.scope.context.requestTreeshakingPass();
  3504. }
  3505. }
  3506. class ArrayExpression extends NodeBase {
  3507. constructor() {
  3508. super(...arguments);
  3509. this.objectEntity = null;
  3510. }
  3511. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3512. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3513. }
  3514. deoptimizePath(path) {
  3515. this.getObjectEntity().deoptimizePath(path);
  3516. }
  3517. getLiteralValueAtPath(path, recursionTracker, origin) {
  3518. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  3519. }
  3520. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3521. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3522. }
  3523. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3524. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  3525. }
  3526. includeNode(context) {
  3527. this.included = true;
  3528. if (!this.deoptimized)
  3529. this.applyDeoptimizations();
  3530. for (const element of this.elements) {
  3531. if (element) {
  3532. element?.includePath(UNKNOWN_PATH, context);
  3533. }
  3534. }
  3535. }
  3536. applyDeoptimizations() {
  3537. this.deoptimized = true;
  3538. let hasSpread = false;
  3539. for (let index = 0; index < this.elements.length; index++) {
  3540. const element = this.elements[index];
  3541. if (element && (hasSpread || element instanceof SpreadElement)) {
  3542. hasSpread = true;
  3543. element.deoptimizePath(UNKNOWN_PATH);
  3544. }
  3545. }
  3546. this.scope.context.requestTreeshakingPass();
  3547. }
  3548. getObjectEntity() {
  3549. if (this.objectEntity !== null) {
  3550. return this.objectEntity;
  3551. }
  3552. const properties = [
  3553. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3554. ];
  3555. let hasSpread = false;
  3556. for (let index = 0; index < this.elements.length; index++) {
  3557. const element = this.elements[index];
  3558. if (hasSpread || element instanceof SpreadElement) {
  3559. if (element) {
  3560. hasSpread = true;
  3561. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  3562. }
  3563. }
  3564. else if (element) {
  3565. properties.push({ key: String(index), kind: 'init', property: element });
  3566. }
  3567. else {
  3568. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  3569. }
  3570. }
  3571. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  3572. }
  3573. }
  3574. /* eslint sort-keys: "off" */
  3575. const ValueProperties = Symbol('Value Properties');
  3576. const getUnknownValue = () => UnknownValue;
  3577. const returnFalse = () => false;
  3578. const returnTrue = () => true;
  3579. const PURE = {
  3580. deoptimizeArgumentsOnCall: doNothing,
  3581. getLiteralValue: getUnknownValue,
  3582. hasEffectsWhenCalled: returnFalse
  3583. };
  3584. const IMPURE = {
  3585. deoptimizeArgumentsOnCall: doNothing,
  3586. getLiteralValue: getUnknownValue,
  3587. hasEffectsWhenCalled: returnTrue
  3588. };
  3589. const PURE_WITH_ARRAY = {
  3590. deoptimizeArgumentsOnCall: doNothing,
  3591. getLiteralValue: getUnknownValue,
  3592. hasEffectsWhenCalled({ args }) {
  3593. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  3594. }
  3595. };
  3596. const GETTER_ACCESS = {
  3597. deoptimizeArgumentsOnCall: doNothing,
  3598. getLiteralValue: getUnknownValue,
  3599. hasEffectsWhenCalled({ args }, context) {
  3600. const [_thisArgument, firstArgument] = args;
  3601. return (!(firstArgument instanceof ExpressionEntity) ||
  3602. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  3603. }
  3604. };
  3605. // We use shortened variables to reduce file size here
  3606. /* OBJECT */
  3607. const O = {
  3608. __proto__: null,
  3609. [ValueProperties]: IMPURE
  3610. };
  3611. /* PURE FUNCTION */
  3612. const PF = {
  3613. __proto__: null,
  3614. [ValueProperties]: PURE
  3615. };
  3616. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  3617. const PF_NO_GETTER = {
  3618. __proto__: null,
  3619. [ValueProperties]: GETTER_ACCESS
  3620. };
  3621. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  3622. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  3623. __proto__: null,
  3624. [ValueProperties]: {
  3625. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  3626. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  3627. },
  3628. getLiteralValue: getUnknownValue,
  3629. hasEffectsWhenCalled({ args }, context) {
  3630. return (args.length <= 1 ||
  3631. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  3632. }
  3633. }
  3634. };
  3635. /* CONSTRUCTOR */
  3636. const C = {
  3637. __proto__: null,
  3638. [ValueProperties]: IMPURE,
  3639. prototype: O
  3640. };
  3641. /* PURE CONSTRUCTOR */
  3642. const PC = {
  3643. __proto__: null,
  3644. [ValueProperties]: PURE,
  3645. prototype: O
  3646. };
  3647. const PC_WITH_ARRAY = {
  3648. __proto__: null,
  3649. [ValueProperties]: PURE_WITH_ARRAY,
  3650. prototype: O
  3651. };
  3652. const ARRAY_TYPE = {
  3653. __proto__: null,
  3654. [ValueProperties]: PURE,
  3655. from: O,
  3656. of: PF,
  3657. prototype: O
  3658. };
  3659. const INTL_MEMBER = {
  3660. __proto__: null,
  3661. [ValueProperties]: PURE,
  3662. supportedLocalesOf: PC
  3663. };
  3664. const knownGlobals = {
  3665. // Placeholders for global objects to avoid shape mutations
  3666. global: O,
  3667. globalThis: O,
  3668. self: O,
  3669. window: O,
  3670. // Common globals
  3671. __proto__: null,
  3672. [ValueProperties]: IMPURE,
  3673. Array: {
  3674. __proto__: null,
  3675. [ValueProperties]: IMPURE,
  3676. from: O,
  3677. isArray: PF,
  3678. of: PF,
  3679. prototype: O
  3680. },
  3681. ArrayBuffer: {
  3682. __proto__: null,
  3683. [ValueProperties]: PURE,
  3684. isView: PF,
  3685. prototype: O
  3686. },
  3687. AggregateError: PC_WITH_ARRAY,
  3688. Atomics: O,
  3689. BigInt: C,
  3690. BigInt64Array: C,
  3691. BigUint64Array: C,
  3692. Boolean: PC,
  3693. constructor: C,
  3694. DataView: PC,
  3695. Date: {
  3696. __proto__: null,
  3697. [ValueProperties]: PURE,
  3698. now: PF,
  3699. parse: PF,
  3700. prototype: O,
  3701. UTC: PF
  3702. },
  3703. decodeURI: PF,
  3704. decodeURIComponent: PF,
  3705. encodeURI: PF,
  3706. encodeURIComponent: PF,
  3707. Error: PC,
  3708. escape: PF,
  3709. eval: O,
  3710. EvalError: PC,
  3711. FinalizationRegistry: C,
  3712. Float32Array: ARRAY_TYPE,
  3713. Float64Array: ARRAY_TYPE,
  3714. Function: C,
  3715. hasOwnProperty: O,
  3716. Infinity: O,
  3717. Int16Array: ARRAY_TYPE,
  3718. Int32Array: ARRAY_TYPE,
  3719. Int8Array: ARRAY_TYPE,
  3720. isFinite: PF,
  3721. isNaN: PF,
  3722. isPrototypeOf: O,
  3723. JSON: O,
  3724. Map: PC_WITH_ARRAY,
  3725. Math: {
  3726. __proto__: null,
  3727. [ValueProperties]: IMPURE,
  3728. abs: PF,
  3729. acos: PF,
  3730. acosh: PF,
  3731. asin: PF,
  3732. asinh: PF,
  3733. atan: PF,
  3734. atan2: PF,
  3735. atanh: PF,
  3736. cbrt: PF,
  3737. ceil: PF,
  3738. clz32: PF,
  3739. cos: PF,
  3740. cosh: PF,
  3741. exp: PF,
  3742. expm1: PF,
  3743. floor: PF,
  3744. fround: PF,
  3745. hypot: PF,
  3746. imul: PF,
  3747. log: PF,
  3748. log10: PF,
  3749. log1p: PF,
  3750. log2: PF,
  3751. max: PF,
  3752. min: PF,
  3753. pow: PF,
  3754. random: PF,
  3755. round: PF,
  3756. sign: PF,
  3757. sin: PF,
  3758. sinh: PF,
  3759. sqrt: PF,
  3760. tan: PF,
  3761. tanh: PF,
  3762. trunc: PF
  3763. },
  3764. NaN: O,
  3765. Number: {
  3766. __proto__: null,
  3767. [ValueProperties]: PURE,
  3768. isFinite: PF,
  3769. isInteger: PF,
  3770. isNaN: PF,
  3771. isSafeInteger: PF,
  3772. parseFloat: PF,
  3773. parseInt: PF,
  3774. prototype: O
  3775. },
  3776. Object: {
  3777. __proto__: null,
  3778. [ValueProperties]: PURE,
  3779. create: PF,
  3780. // Technically those can throw in certain situations, but we ignore this as
  3781. // code that relies on this will hopefully wrap this in a try-catch, which
  3782. // deoptimizes everything anyway
  3783. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  3784. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  3785. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  3786. getOwnPropertyDescriptor: PF,
  3787. getOwnPropertyDescriptors: PF,
  3788. getOwnPropertyNames: PF,
  3789. getOwnPropertySymbols: PF,
  3790. getPrototypeOf: PF,
  3791. hasOwn: PF,
  3792. is: PF,
  3793. isExtensible: PF,
  3794. isFrozen: PF,
  3795. isSealed: PF,
  3796. keys: PF,
  3797. fromEntries: O,
  3798. entries: PF_NO_GETTER,
  3799. values: PF_NO_GETTER,
  3800. prototype: O
  3801. },
  3802. parseFloat: PF,
  3803. parseInt: PF,
  3804. Promise: {
  3805. __proto__: null,
  3806. [ValueProperties]: IMPURE,
  3807. all: O,
  3808. allSettled: O,
  3809. any: O,
  3810. prototype: O,
  3811. race: O,
  3812. reject: O,
  3813. resolve: O
  3814. },
  3815. propertyIsEnumerable: O,
  3816. Proxy: {
  3817. __proto__: null,
  3818. [ValueProperties]: {
  3819. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  3820. if (isObjectExpressionNode(parameter)) {
  3821. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  3822. if (!hasSpreadElement) {
  3823. for (const property of parameter.properties) {
  3824. property.deoptimizeArgumentsOnInteractionAtPath({
  3825. args: [null, target],
  3826. type: INTERACTION_CALLED,
  3827. withNew: false
  3828. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  3829. }
  3830. return;
  3831. }
  3832. }
  3833. target.deoptimizePath(UNKNOWN_PATH);
  3834. },
  3835. getLiteralValue: getUnknownValue,
  3836. hasEffectsWhenCalled: returnTrue
  3837. }
  3838. },
  3839. RangeError: PC,
  3840. ReferenceError: PC,
  3841. Reflect: O,
  3842. RegExp: PC,
  3843. Set: PC_WITH_ARRAY,
  3844. SharedArrayBuffer: C,
  3845. String: {
  3846. __proto__: null,
  3847. [ValueProperties]: PURE,
  3848. fromCharCode: PF,
  3849. fromCodePoint: PF,
  3850. prototype: O,
  3851. raw: PF
  3852. },
  3853. Symbol: {
  3854. __proto__: null,
  3855. [ValueProperties]: PURE,
  3856. for: PF,
  3857. keyFor: PF,
  3858. prototype: O,
  3859. toStringTag: {
  3860. __proto__: null,
  3861. [ValueProperties]: {
  3862. deoptimizeArgumentsOnCall: doNothing,
  3863. getLiteralValue() {
  3864. return SymbolToStringTag;
  3865. },
  3866. hasEffectsWhenCalled: returnTrue
  3867. }
  3868. }
  3869. },
  3870. SyntaxError: PC,
  3871. toLocaleString: O,
  3872. toString: O,
  3873. TypeError: PC,
  3874. Uint16Array: ARRAY_TYPE,
  3875. Uint32Array: ARRAY_TYPE,
  3876. Uint8Array: ARRAY_TYPE,
  3877. Uint8ClampedArray: ARRAY_TYPE,
  3878. // Technically, this is a global, but it needs special handling
  3879. // undefined: ?,
  3880. unescape: PF,
  3881. URIError: PC,
  3882. valueOf: O,
  3883. WeakMap: PC_WITH_ARRAY,
  3884. WeakRef: C,
  3885. WeakSet: PC_WITH_ARRAY,
  3886. // Additional globals shared by Node and Browser that are not strictly part of the language
  3887. clearInterval: C,
  3888. clearTimeout: C,
  3889. console: {
  3890. __proto__: null,
  3891. [ValueProperties]: IMPURE,
  3892. assert: C,
  3893. clear: C,
  3894. count: C,
  3895. countReset: C,
  3896. debug: C,
  3897. dir: C,
  3898. dirxml: C,
  3899. error: C,
  3900. exception: C,
  3901. group: C,
  3902. groupCollapsed: C,
  3903. groupEnd: C,
  3904. info: C,
  3905. log: C,
  3906. table: C,
  3907. time: C,
  3908. timeEnd: C,
  3909. timeLog: C,
  3910. trace: C,
  3911. warn: C
  3912. },
  3913. Intl: {
  3914. __proto__: null,
  3915. [ValueProperties]: IMPURE,
  3916. Collator: INTL_MEMBER,
  3917. DateTimeFormat: INTL_MEMBER,
  3918. DisplayNames: INTL_MEMBER,
  3919. ListFormat: INTL_MEMBER,
  3920. Locale: INTL_MEMBER,
  3921. NumberFormat: INTL_MEMBER,
  3922. PluralRules: INTL_MEMBER,
  3923. RelativeTimeFormat: INTL_MEMBER,
  3924. Segmenter: INTL_MEMBER
  3925. },
  3926. setInterval: C,
  3927. setTimeout: C,
  3928. TextDecoder: C,
  3929. TextEncoder: C,
  3930. URL: {
  3931. __proto__: null,
  3932. [ValueProperties]: IMPURE,
  3933. prototype: O,
  3934. canParse: PF
  3935. },
  3936. URLSearchParams: C,
  3937. // Browser specific globals
  3938. AbortController: C,
  3939. AbortSignal: C,
  3940. addEventListener: O,
  3941. alert: O,
  3942. AnalyserNode: C,
  3943. Animation: C,
  3944. AnimationEvent: C,
  3945. applicationCache: O,
  3946. ApplicationCache: C,
  3947. ApplicationCacheErrorEvent: C,
  3948. atob: O,
  3949. Attr: C,
  3950. Audio: C,
  3951. AudioBuffer: C,
  3952. AudioBufferSourceNode: C,
  3953. AudioContext: C,
  3954. AudioDestinationNode: C,
  3955. AudioListener: C,
  3956. AudioNode: C,
  3957. AudioParam: C,
  3958. AudioProcessingEvent: C,
  3959. AudioScheduledSourceNode: C,
  3960. AudioWorkletNode: C,
  3961. BarProp: C,
  3962. BaseAudioContext: C,
  3963. BatteryManager: C,
  3964. BeforeUnloadEvent: C,
  3965. BiquadFilterNode: C,
  3966. Blob: C,
  3967. BlobEvent: C,
  3968. blur: O,
  3969. BroadcastChannel: C,
  3970. btoa: O,
  3971. ByteLengthQueuingStrategy: C,
  3972. Cache: C,
  3973. caches: O,
  3974. CacheStorage: C,
  3975. cancelAnimationFrame: O,
  3976. cancelIdleCallback: O,
  3977. CanvasCaptureMediaStreamTrack: C,
  3978. CanvasGradient: C,
  3979. CanvasPattern: C,
  3980. CanvasRenderingContext2D: C,
  3981. ChannelMergerNode: C,
  3982. ChannelSplitterNode: C,
  3983. CharacterData: C,
  3984. clientInformation: O,
  3985. ClipboardEvent: C,
  3986. close: O,
  3987. closed: O,
  3988. CloseEvent: C,
  3989. Comment: C,
  3990. CompositionEvent: C,
  3991. confirm: O,
  3992. ConstantSourceNode: C,
  3993. ConvolverNode: C,
  3994. CountQueuingStrategy: C,
  3995. createImageBitmap: O,
  3996. Credential: C,
  3997. CredentialsContainer: C,
  3998. crypto: O,
  3999. Crypto: C,
  4000. CryptoKey: C,
  4001. CSS: C,
  4002. CSSConditionRule: C,
  4003. CSSFontFaceRule: C,
  4004. CSSGroupingRule: C,
  4005. CSSImportRule: C,
  4006. CSSKeyframeRule: C,
  4007. CSSKeyframesRule: C,
  4008. CSSMediaRule: C,
  4009. CSSNamespaceRule: C,
  4010. CSSPageRule: C,
  4011. CSSRule: C,
  4012. CSSRuleList: C,
  4013. CSSStyleDeclaration: C,
  4014. CSSStyleRule: C,
  4015. CSSStyleSheet: C,
  4016. CSSSupportsRule: C,
  4017. CustomElementRegistry: C,
  4018. customElements: O,
  4019. CustomEvent: {
  4020. __proto__: null,
  4021. [ValueProperties]: {
  4022. deoptimizeArgumentsOnCall({ args }) {
  4023. args[2]?.deoptimizePath(['detail']);
  4024. },
  4025. getLiteralValue: getUnknownValue,
  4026. hasEffectsWhenCalled: returnFalse
  4027. },
  4028. prototype: O
  4029. },
  4030. DataTransfer: C,
  4031. DataTransferItem: C,
  4032. DataTransferItemList: C,
  4033. defaultstatus: O,
  4034. defaultStatus: O,
  4035. DelayNode: C,
  4036. DeviceMotionEvent: C,
  4037. DeviceOrientationEvent: C,
  4038. devicePixelRatio: O,
  4039. dispatchEvent: O,
  4040. document: O,
  4041. Document: C,
  4042. DocumentFragment: C,
  4043. DocumentType: C,
  4044. DOMError: C,
  4045. DOMException: C,
  4046. DOMImplementation: C,
  4047. DOMMatrix: C,
  4048. DOMMatrixReadOnly: C,
  4049. DOMParser: C,
  4050. DOMPoint: C,
  4051. DOMPointReadOnly: C,
  4052. DOMQuad: C,
  4053. DOMRect: C,
  4054. DOMRectReadOnly: C,
  4055. DOMStringList: C,
  4056. DOMStringMap: C,
  4057. DOMTokenList: C,
  4058. DragEvent: C,
  4059. DynamicsCompressorNode: C,
  4060. Element: C,
  4061. ErrorEvent: C,
  4062. Event: C,
  4063. EventSource: C,
  4064. EventTarget: C,
  4065. external: O,
  4066. fetch: O,
  4067. File: C,
  4068. FileList: C,
  4069. FileReader: C,
  4070. find: O,
  4071. focus: O,
  4072. FocusEvent: C,
  4073. FontFace: C,
  4074. FontFaceSetLoadEvent: C,
  4075. FormData: C,
  4076. frames: O,
  4077. GainNode: C,
  4078. Gamepad: C,
  4079. GamepadButton: C,
  4080. GamepadEvent: C,
  4081. getComputedStyle: O,
  4082. getSelection: O,
  4083. HashChangeEvent: C,
  4084. Headers: C,
  4085. history: O,
  4086. History: C,
  4087. HTMLAllCollection: C,
  4088. HTMLAnchorElement: C,
  4089. HTMLAreaElement: C,
  4090. HTMLAudioElement: C,
  4091. HTMLBaseElement: C,
  4092. HTMLBodyElement: C,
  4093. HTMLBRElement: C,
  4094. HTMLButtonElement: C,
  4095. HTMLCanvasElement: C,
  4096. HTMLCollection: C,
  4097. HTMLContentElement: C,
  4098. HTMLDataElement: C,
  4099. HTMLDataListElement: C,
  4100. HTMLDetailsElement: C,
  4101. HTMLDialogElement: C,
  4102. HTMLDirectoryElement: C,
  4103. HTMLDivElement: C,
  4104. HTMLDListElement: C,
  4105. HTMLDocument: C,
  4106. HTMLElement: C,
  4107. HTMLEmbedElement: C,
  4108. HTMLFieldSetElement: C,
  4109. HTMLFontElement: C,
  4110. HTMLFormControlsCollection: C,
  4111. HTMLFormElement: C,
  4112. HTMLFrameElement: C,
  4113. HTMLFrameSetElement: C,
  4114. HTMLHeadElement: C,
  4115. HTMLHeadingElement: C,
  4116. HTMLHRElement: C,
  4117. HTMLHtmlElement: C,
  4118. HTMLIFrameElement: C,
  4119. HTMLImageElement: C,
  4120. HTMLInputElement: C,
  4121. HTMLLabelElement: C,
  4122. HTMLLegendElement: C,
  4123. HTMLLIElement: C,
  4124. HTMLLinkElement: C,
  4125. HTMLMapElement: C,
  4126. HTMLMarqueeElement: C,
  4127. HTMLMediaElement: C,
  4128. HTMLMenuElement: C,
  4129. HTMLMetaElement: C,
  4130. HTMLMeterElement: C,
  4131. HTMLModElement: C,
  4132. HTMLObjectElement: C,
  4133. HTMLOListElement: C,
  4134. HTMLOptGroupElement: C,
  4135. HTMLOptionElement: C,
  4136. HTMLOptionsCollection: C,
  4137. HTMLOutputElement: C,
  4138. HTMLParagraphElement: C,
  4139. HTMLParamElement: C,
  4140. HTMLPictureElement: C,
  4141. HTMLPreElement: C,
  4142. HTMLProgressElement: C,
  4143. HTMLQuoteElement: C,
  4144. HTMLScriptElement: C,
  4145. HTMLSelectElement: C,
  4146. HTMLShadowElement: C,
  4147. HTMLSlotElement: C,
  4148. HTMLSourceElement: C,
  4149. HTMLSpanElement: C,
  4150. HTMLStyleElement: C,
  4151. HTMLTableCaptionElement: C,
  4152. HTMLTableCellElement: C,
  4153. HTMLTableColElement: C,
  4154. HTMLTableElement: C,
  4155. HTMLTableRowElement: C,
  4156. HTMLTableSectionElement: C,
  4157. HTMLTemplateElement: C,
  4158. HTMLTextAreaElement: C,
  4159. HTMLTimeElement: C,
  4160. HTMLTitleElement: C,
  4161. HTMLTrackElement: C,
  4162. HTMLUListElement: C,
  4163. HTMLUnknownElement: C,
  4164. HTMLVideoElement: C,
  4165. IDBCursor: C,
  4166. IDBCursorWithValue: C,
  4167. IDBDatabase: C,
  4168. IDBFactory: C,
  4169. IDBIndex: C,
  4170. IDBKeyRange: C,
  4171. IDBObjectStore: C,
  4172. IDBOpenDBRequest: C,
  4173. IDBRequest: C,
  4174. IDBTransaction: C,
  4175. IDBVersionChangeEvent: C,
  4176. IdleDeadline: C,
  4177. IIRFilterNode: C,
  4178. Image: C,
  4179. ImageBitmap: C,
  4180. ImageBitmapRenderingContext: C,
  4181. ImageCapture: C,
  4182. ImageData: C,
  4183. indexedDB: O,
  4184. innerHeight: O,
  4185. innerWidth: O,
  4186. InputEvent: C,
  4187. IntersectionObserver: C,
  4188. IntersectionObserverEntry: C,
  4189. isSecureContext: O,
  4190. KeyboardEvent: C,
  4191. KeyframeEffect: C,
  4192. length: O,
  4193. localStorage: O,
  4194. location: O,
  4195. Location: C,
  4196. locationbar: O,
  4197. matchMedia: O,
  4198. MediaDeviceInfo: C,
  4199. MediaDevices: C,
  4200. MediaElementAudioSourceNode: C,
  4201. MediaEncryptedEvent: C,
  4202. MediaError: C,
  4203. MediaKeyMessageEvent: C,
  4204. MediaKeySession: C,
  4205. MediaKeyStatusMap: C,
  4206. MediaKeySystemAccess: C,
  4207. MediaList: C,
  4208. MediaQueryList: C,
  4209. MediaQueryListEvent: C,
  4210. MediaRecorder: C,
  4211. MediaSettingsRange: C,
  4212. MediaSource: C,
  4213. MediaStream: C,
  4214. MediaStreamAudioDestinationNode: C,
  4215. MediaStreamAudioSourceNode: C,
  4216. MediaStreamEvent: C,
  4217. MediaStreamTrack: C,
  4218. MediaStreamTrackEvent: C,
  4219. menubar: O,
  4220. MessageChannel: C,
  4221. MessageEvent: C,
  4222. MessagePort: C,
  4223. MIDIAccess: C,
  4224. MIDIConnectionEvent: C,
  4225. MIDIInput: C,
  4226. MIDIInputMap: C,
  4227. MIDIMessageEvent: C,
  4228. MIDIOutput: C,
  4229. MIDIOutputMap: C,
  4230. MIDIPort: C,
  4231. MimeType: C,
  4232. MimeTypeArray: C,
  4233. MouseEvent: C,
  4234. moveBy: O,
  4235. moveTo: O,
  4236. MutationEvent: C,
  4237. MutationObserver: C,
  4238. MutationRecord: C,
  4239. name: O,
  4240. NamedNodeMap: C,
  4241. NavigationPreloadManager: C,
  4242. navigator: O,
  4243. Navigator: C,
  4244. NetworkInformation: C,
  4245. Node: C,
  4246. NodeFilter: O,
  4247. NodeIterator: C,
  4248. NodeList: C,
  4249. Notification: C,
  4250. OfflineAudioCompletionEvent: C,
  4251. OfflineAudioContext: C,
  4252. offscreenBuffering: O,
  4253. OffscreenCanvas: C,
  4254. open: O,
  4255. openDatabase: O,
  4256. Option: C,
  4257. origin: O,
  4258. OscillatorNode: C,
  4259. outerHeight: O,
  4260. outerWidth: O,
  4261. PageTransitionEvent: C,
  4262. pageXOffset: O,
  4263. pageYOffset: O,
  4264. PannerNode: C,
  4265. parent: O,
  4266. Path2D: C,
  4267. PaymentAddress: C,
  4268. PaymentRequest: C,
  4269. PaymentRequestUpdateEvent: C,
  4270. PaymentResponse: C,
  4271. performance: O,
  4272. Performance: C,
  4273. PerformanceEntry: C,
  4274. PerformanceLongTaskTiming: C,
  4275. PerformanceMark: C,
  4276. PerformanceMeasure: C,
  4277. PerformanceNavigation: C,
  4278. PerformanceNavigationTiming: C,
  4279. PerformanceObserver: C,
  4280. PerformanceObserverEntryList: C,
  4281. PerformancePaintTiming: C,
  4282. PerformanceResourceTiming: C,
  4283. PerformanceTiming: C,
  4284. PeriodicWave: C,
  4285. Permissions: C,
  4286. PermissionStatus: C,
  4287. personalbar: O,
  4288. PhotoCapabilities: C,
  4289. Plugin: C,
  4290. PluginArray: C,
  4291. PointerEvent: C,
  4292. PopStateEvent: C,
  4293. postMessage: O,
  4294. Presentation: C,
  4295. PresentationAvailability: C,
  4296. PresentationConnection: C,
  4297. PresentationConnectionAvailableEvent: C,
  4298. PresentationConnectionCloseEvent: C,
  4299. PresentationConnectionList: C,
  4300. PresentationReceiver: C,
  4301. PresentationRequest: C,
  4302. print: O,
  4303. ProcessingInstruction: C,
  4304. ProgressEvent: C,
  4305. PromiseRejectionEvent: C,
  4306. prompt: O,
  4307. PushManager: C,
  4308. PushSubscription: C,
  4309. PushSubscriptionOptions: C,
  4310. queueMicrotask: O,
  4311. RadioNodeList: C,
  4312. Range: C,
  4313. ReadableStream: C,
  4314. RemotePlayback: C,
  4315. removeEventListener: O,
  4316. Request: C,
  4317. requestAnimationFrame: O,
  4318. requestIdleCallback: O,
  4319. resizeBy: O,
  4320. ResizeObserver: C,
  4321. ResizeObserverEntry: C,
  4322. resizeTo: O,
  4323. Response: C,
  4324. RTCCertificate: C,
  4325. RTCDataChannel: C,
  4326. RTCDataChannelEvent: C,
  4327. RTCDtlsTransport: C,
  4328. RTCIceCandidate: C,
  4329. RTCIceTransport: C,
  4330. RTCPeerConnection: C,
  4331. RTCPeerConnectionIceEvent: C,
  4332. RTCRtpReceiver: C,
  4333. RTCRtpSender: C,
  4334. RTCSctpTransport: C,
  4335. RTCSessionDescription: C,
  4336. RTCStatsReport: C,
  4337. RTCTrackEvent: C,
  4338. screen: O,
  4339. Screen: C,
  4340. screenLeft: O,
  4341. ScreenOrientation: C,
  4342. screenTop: O,
  4343. screenX: O,
  4344. screenY: O,
  4345. ScriptProcessorNode: C,
  4346. scroll: O,
  4347. scrollbars: O,
  4348. scrollBy: O,
  4349. scrollTo: O,
  4350. scrollX: O,
  4351. scrollY: O,
  4352. SecurityPolicyViolationEvent: C,
  4353. Selection: C,
  4354. ServiceWorker: C,
  4355. ServiceWorkerContainer: C,
  4356. ServiceWorkerRegistration: C,
  4357. sessionStorage: O,
  4358. ShadowRoot: C,
  4359. SharedWorker: C,
  4360. SourceBuffer: C,
  4361. SourceBufferList: C,
  4362. speechSynthesis: O,
  4363. SpeechSynthesisEvent: C,
  4364. SpeechSynthesisUtterance: C,
  4365. StaticRange: C,
  4366. status: O,
  4367. statusbar: O,
  4368. StereoPannerNode: C,
  4369. stop: O,
  4370. Storage: C,
  4371. StorageEvent: C,
  4372. StorageManager: C,
  4373. styleMedia: O,
  4374. StyleSheet: C,
  4375. StyleSheetList: C,
  4376. SubtleCrypto: C,
  4377. SVGAElement: C,
  4378. SVGAngle: C,
  4379. SVGAnimatedAngle: C,
  4380. SVGAnimatedBoolean: C,
  4381. SVGAnimatedEnumeration: C,
  4382. SVGAnimatedInteger: C,
  4383. SVGAnimatedLength: C,
  4384. SVGAnimatedLengthList: C,
  4385. SVGAnimatedNumber: C,
  4386. SVGAnimatedNumberList: C,
  4387. SVGAnimatedPreserveAspectRatio: C,
  4388. SVGAnimatedRect: C,
  4389. SVGAnimatedString: C,
  4390. SVGAnimatedTransformList: C,
  4391. SVGAnimateElement: C,
  4392. SVGAnimateMotionElement: C,
  4393. SVGAnimateTransformElement: C,
  4394. SVGAnimationElement: C,
  4395. SVGCircleElement: C,
  4396. SVGClipPathElement: C,
  4397. SVGComponentTransferFunctionElement: C,
  4398. SVGDefsElement: C,
  4399. SVGDescElement: C,
  4400. SVGDiscardElement: C,
  4401. SVGElement: C,
  4402. SVGEllipseElement: C,
  4403. SVGFEBlendElement: C,
  4404. SVGFEColorMatrixElement: C,
  4405. SVGFEComponentTransferElement: C,
  4406. SVGFECompositeElement: C,
  4407. SVGFEConvolveMatrixElement: C,
  4408. SVGFEDiffuseLightingElement: C,
  4409. SVGFEDisplacementMapElement: C,
  4410. SVGFEDistantLightElement: C,
  4411. SVGFEDropShadowElement: C,
  4412. SVGFEFloodElement: C,
  4413. SVGFEFuncAElement: C,
  4414. SVGFEFuncBElement: C,
  4415. SVGFEFuncGElement: C,
  4416. SVGFEFuncRElement: C,
  4417. SVGFEGaussianBlurElement: C,
  4418. SVGFEImageElement: C,
  4419. SVGFEMergeElement: C,
  4420. SVGFEMergeNodeElement: C,
  4421. SVGFEMorphologyElement: C,
  4422. SVGFEOffsetElement: C,
  4423. SVGFEPointLightElement: C,
  4424. SVGFESpecularLightingElement: C,
  4425. SVGFESpotLightElement: C,
  4426. SVGFETileElement: C,
  4427. SVGFETurbulenceElement: C,
  4428. SVGFilterElement: C,
  4429. SVGForeignObjectElement: C,
  4430. SVGGElement: C,
  4431. SVGGeometryElement: C,
  4432. SVGGradientElement: C,
  4433. SVGGraphicsElement: C,
  4434. SVGImageElement: C,
  4435. SVGLength: C,
  4436. SVGLengthList: C,
  4437. SVGLinearGradientElement: C,
  4438. SVGLineElement: C,
  4439. SVGMarkerElement: C,
  4440. SVGMaskElement: C,
  4441. SVGMatrix: C,
  4442. SVGMetadataElement: C,
  4443. SVGMPathElement: C,
  4444. SVGNumber: C,
  4445. SVGNumberList: C,
  4446. SVGPathElement: C,
  4447. SVGPatternElement: C,
  4448. SVGPoint: C,
  4449. SVGPointList: C,
  4450. SVGPolygonElement: C,
  4451. SVGPolylineElement: C,
  4452. SVGPreserveAspectRatio: C,
  4453. SVGRadialGradientElement: C,
  4454. SVGRect: C,
  4455. SVGRectElement: C,
  4456. SVGScriptElement: C,
  4457. SVGSetElement: C,
  4458. SVGStopElement: C,
  4459. SVGStringList: C,
  4460. SVGStyleElement: C,
  4461. SVGSVGElement: C,
  4462. SVGSwitchElement: C,
  4463. SVGSymbolElement: C,
  4464. SVGTextContentElement: C,
  4465. SVGTextElement: C,
  4466. SVGTextPathElement: C,
  4467. SVGTextPositioningElement: C,
  4468. SVGTitleElement: C,
  4469. SVGTransform: C,
  4470. SVGTransformList: C,
  4471. SVGTSpanElement: C,
  4472. SVGUnitTypes: C,
  4473. SVGUseElement: C,
  4474. SVGViewElement: C,
  4475. TaskAttributionTiming: C,
  4476. Text: C,
  4477. TextEvent: C,
  4478. TextMetrics: C,
  4479. TextTrack: C,
  4480. TextTrackCue: C,
  4481. TextTrackCueList: C,
  4482. TextTrackList: C,
  4483. TimeRanges: C,
  4484. toolbar: O,
  4485. top: O,
  4486. Touch: C,
  4487. TouchEvent: C,
  4488. TouchList: C,
  4489. TrackEvent: C,
  4490. TransitionEvent: C,
  4491. TreeWalker: C,
  4492. UIEvent: C,
  4493. ValidityState: C,
  4494. visualViewport: O,
  4495. VisualViewport: C,
  4496. VTTCue: C,
  4497. WaveShaperNode: C,
  4498. WebAssembly: O,
  4499. WebGL2RenderingContext: C,
  4500. WebGLActiveInfo: C,
  4501. WebGLBuffer: C,
  4502. WebGLContextEvent: C,
  4503. WebGLFramebuffer: C,
  4504. WebGLProgram: C,
  4505. WebGLQuery: C,
  4506. WebGLRenderbuffer: C,
  4507. WebGLRenderingContext: C,
  4508. WebGLSampler: C,
  4509. WebGLShader: C,
  4510. WebGLShaderPrecisionFormat: C,
  4511. WebGLSync: C,
  4512. WebGLTexture: C,
  4513. WebGLTransformFeedback: C,
  4514. WebGLUniformLocation: C,
  4515. WebGLVertexArrayObject: C,
  4516. WebSocket: C,
  4517. WheelEvent: C,
  4518. Window: C,
  4519. Worker: C,
  4520. WritableStream: C,
  4521. XMLDocument: C,
  4522. XMLHttpRequest: C,
  4523. XMLHttpRequestEventTarget: C,
  4524. XMLHttpRequestUpload: C,
  4525. XMLSerializer: C,
  4526. XPathEvaluator: C,
  4527. XPathExpression: C,
  4528. XPathResult: C,
  4529. XSLTProcessor: C
  4530. };
  4531. for (const global of ['window', 'global', 'self', 'globalThis']) {
  4532. knownGlobals[global] = knownGlobals;
  4533. }
  4534. function getGlobalAtPath(path) {
  4535. let currentGlobal = knownGlobals;
  4536. for (const pathSegment of path) {
  4537. if (typeof pathSegment !== 'string') {
  4538. return null;
  4539. }
  4540. currentGlobal = currentGlobal[pathSegment];
  4541. if (!currentGlobal) {
  4542. return null;
  4543. }
  4544. }
  4545. return currentGlobal[ValueProperties];
  4546. }
  4547. class GlobalVariable extends Variable {
  4548. constructor(name) {
  4549. super(name);
  4550. // Ensure we use live-bindings for globals as we do not know if they have
  4551. // been reassigned
  4552. this.markReassigned();
  4553. }
  4554. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4555. switch (interaction.type) {
  4556. // While there is no point in testing these cases as at the moment, they
  4557. // are also covered via other means, we keep them for completeness
  4558. case INTERACTION_ACCESSED:
  4559. case INTERACTION_ASSIGNED: {
  4560. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  4561. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4562. }
  4563. return;
  4564. }
  4565. case INTERACTION_CALLED: {
  4566. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4567. if (globalAtPath) {
  4568. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  4569. }
  4570. else {
  4571. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4572. }
  4573. return;
  4574. }
  4575. }
  4576. }
  4577. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  4578. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4579. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  4580. }
  4581. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4582. switch (interaction.type) {
  4583. case INTERACTION_ACCESSED: {
  4584. if (path.length === 0) {
  4585. // Technically, "undefined" is a global variable of sorts
  4586. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  4587. }
  4588. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  4589. }
  4590. case INTERACTION_ASSIGNED: {
  4591. return true;
  4592. }
  4593. case INTERACTION_CALLED: {
  4594. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4595. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  4596. }
  4597. }
  4598. }
  4599. }
  4600. // To avoid infinite recursions
  4601. const MAX_PATH_DEPTH = 6;
  4602. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  4603. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  4604. const limitConcatenatedPathDepth = (path1, path2) => {
  4605. const { length: length1 } = path1;
  4606. const { length: length2 } = path2;
  4607. return length1 === 0
  4608. ? path2
  4609. : length2 === 0
  4610. ? path1
  4611. : length1 + length2 > MAX_PATH_DEPTH
  4612. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  4613. : [...path1, ...path2];
  4614. };
  4615. class LocalVariable extends Variable {
  4616. constructor(name, declarator, init,
  4617. /** if this is non-empty, the actual init is this path of this.init */
  4618. initPath, context, kind) {
  4619. super(name);
  4620. this.init = init;
  4621. this.initPath = initPath;
  4622. this.kind = kind;
  4623. this.calledFromTryStatement = false;
  4624. this.additionalInitializers = null;
  4625. this.includedPathTracker = new IncludedFullPathTracker();
  4626. this.expressionsToBeDeoptimized = [];
  4627. this.declarations = declarator ? [declarator] : [];
  4628. this.deoptimizationTracker = context.deoptimizationTracker;
  4629. this.module = context.module;
  4630. }
  4631. addDeclaration(identifier, init) {
  4632. this.declarations.push(identifier);
  4633. this.markInitializersForDeoptimization().push(init);
  4634. }
  4635. consolidateInitializers() {
  4636. if (this.additionalInitializers) {
  4637. for (const initializer of this.additionalInitializers) {
  4638. initializer.deoptimizePath(UNKNOWN_PATH);
  4639. }
  4640. }
  4641. }
  4642. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4643. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4644. deoptimizeInteraction(interaction);
  4645. return;
  4646. }
  4647. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4648. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  4649. }, undefined);
  4650. }
  4651. deoptimizePath(path) {
  4652. if (this.isReassigned ||
  4653. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  4654. return;
  4655. }
  4656. if (path.length === 0) {
  4657. this.markReassigned();
  4658. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  4659. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  4660. for (const expression of expressionsToBeDeoptimized) {
  4661. expression.deoptimizeCache();
  4662. }
  4663. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  4664. }
  4665. else {
  4666. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  4667. }
  4668. }
  4669. getLiteralValueAtPath(path, recursionTracker, origin) {
  4670. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4671. return UnknownValue;
  4672. }
  4673. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4674. this.expressionsToBeDeoptimized.push(origin);
  4675. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  4676. }, UnknownValue);
  4677. }
  4678. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4679. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4680. return UNKNOWN_RETURN_EXPRESSION;
  4681. }
  4682. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4683. this.expressionsToBeDeoptimized.push(origin);
  4684. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  4685. }, UNKNOWN_RETURN_EXPRESSION);
  4686. }
  4687. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4688. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4689. return true;
  4690. }
  4691. switch (interaction.type) {
  4692. case INTERACTION_ACCESSED: {
  4693. if (this.isReassigned)
  4694. return true;
  4695. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  4696. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4697. }
  4698. case INTERACTION_ASSIGNED: {
  4699. if (this.included)
  4700. return true;
  4701. if (path.length === 0)
  4702. return false;
  4703. if (this.isReassigned)
  4704. return true;
  4705. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  4706. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4707. }
  4708. case INTERACTION_CALLED: {
  4709. if (this.isReassigned)
  4710. return true;
  4711. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  4712. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4713. }
  4714. }
  4715. }
  4716. includePath(path, context) {
  4717. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  4718. this.module.scope.context.requestTreeshakingPass();
  4719. if (!this.included) {
  4720. // This will reduce the number of tree-shaking passes by eagerly
  4721. // including inits. By pushing this here instead of directly including
  4722. // we avoid deep call stacks.
  4723. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  4724. }
  4725. super.includePath(path, context);
  4726. for (const declaration of this.declarations) {
  4727. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  4728. if (!declaration.included)
  4729. declaration.include(context, false);
  4730. let node = declaration.parent;
  4731. while (!node.included) {
  4732. // We do not want to properly include parents in case they are part of a dead branch
  4733. // in which case .include() might pull in more dead code
  4734. node.includeNode(context);
  4735. if (node.type === Program$1)
  4736. break;
  4737. node = node.parent;
  4738. }
  4739. }
  4740. // We need to make sure we include the correct path of the init
  4741. if (path.length > 0) {
  4742. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  4743. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  4744. }
  4745. }
  4746. }
  4747. includeCallArguments(interaction, context) {
  4748. if (this.isReassigned ||
  4749. context.includedCallArguments.has(this.init) ||
  4750. // This can be removed again once we can include arguments when called at
  4751. // a specific path
  4752. this.initPath.length > 0) {
  4753. includeInteraction(interaction, context);
  4754. }
  4755. else {
  4756. context.includedCallArguments.add(this.init);
  4757. this.init.includeCallArguments(interaction, context);
  4758. context.includedCallArguments.delete(this.init);
  4759. }
  4760. }
  4761. markCalledFromTryStatement() {
  4762. this.calledFromTryStatement = true;
  4763. }
  4764. markInitializersForDeoptimization() {
  4765. if (this.additionalInitializers === null) {
  4766. this.additionalInitializers = [this.init];
  4767. this.init = UNKNOWN_EXPRESSION;
  4768. this.markReassigned();
  4769. }
  4770. return this.additionalInitializers;
  4771. }
  4772. }
  4773. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  4774. class IdentifierBase extends NodeBase {
  4775. constructor() {
  4776. super(...arguments);
  4777. this.variable = null;
  4778. this.isVariableReference = false;
  4779. }
  4780. get isTDZAccess() {
  4781. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  4782. return null;
  4783. }
  4784. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  4785. }
  4786. set isTDZAccess(value) {
  4787. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  4788. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  4789. }
  4790. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4791. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4792. }
  4793. deoptimizePath(path) {
  4794. if (path.length === 0 && !this.scope.contains(this.name)) {
  4795. this.disallowImportReassignment();
  4796. }
  4797. // We keep conditional chaining because an unknown Node could have an
  4798. // Identifier as property that might be deoptimized by default
  4799. this.variable?.deoptimizePath(path);
  4800. }
  4801. getLiteralValueAtPath(path, recursionTracker, origin) {
  4802. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  4803. }
  4804. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4805. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4806. return [expression, isPure || this.isPureFunction(path)];
  4807. }
  4808. hasEffects(context) {
  4809. if (!this.deoptimized)
  4810. this.applyDeoptimizations();
  4811. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  4812. return true;
  4813. }
  4814. return (this.scope.context.options.treeshake
  4815. .unknownGlobalSideEffects &&
  4816. this.variable instanceof GlobalVariable &&
  4817. !this.isPureFunction(EMPTY_PATH) &&
  4818. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  4819. }
  4820. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4821. switch (interaction.type) {
  4822. case INTERACTION_ACCESSED: {
  4823. return (this.variable !== null &&
  4824. !this.isPureFunction(path) &&
  4825. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4826. }
  4827. case INTERACTION_ASSIGNED: {
  4828. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  4829. }
  4830. case INTERACTION_CALLED: {
  4831. return (!this.isPureFunction(path) &&
  4832. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4833. }
  4834. }
  4835. }
  4836. include(context, includeChildrenRecursively) {
  4837. if (!this.included)
  4838. this.includeNode(context);
  4839. if (includeChildrenRecursively) {
  4840. this.variable?.includePath(UNKNOWN_PATH, context);
  4841. }
  4842. }
  4843. includeNode(context) {
  4844. this.included = true;
  4845. if (!this.deoptimized)
  4846. this.applyDeoptimizations();
  4847. if (this.variable !== null) {
  4848. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  4849. }
  4850. }
  4851. includePath(path, context) {
  4852. if (!this.included) {
  4853. this.included = true;
  4854. if (!this.deoptimized)
  4855. this.applyDeoptimizations();
  4856. if (this.variable !== null) {
  4857. this.scope.context.includeVariableInModule(this.variable, path, context);
  4858. }
  4859. }
  4860. else if (path.length > 0) {
  4861. this.variable?.includePath(path, context);
  4862. }
  4863. }
  4864. includeCallArguments(interaction, context) {
  4865. this.variable.includeCallArguments(interaction, context);
  4866. }
  4867. isPossibleTDZ() {
  4868. // return cached value to avoid issues with the next tree-shaking pass
  4869. const cachedTdzAccess = this.isTDZAccess;
  4870. if (cachedTdzAccess !== null)
  4871. return cachedTdzAccess;
  4872. if (!(this.variable instanceof LocalVariable &&
  4873. this.variable.kind &&
  4874. tdzVariableKinds.has(this.variable.kind) &&
  4875. // We ignore modules that did not receive a treeshaking pass yet as that
  4876. // causes many false positives due to circular dependencies or disabled
  4877. // moduleSideEffects.
  4878. this.variable.module.hasTreeShakingPassStarted)) {
  4879. return (this.isTDZAccess = false);
  4880. }
  4881. let decl_id;
  4882. if (this.variable.declarations &&
  4883. this.variable.declarations.length === 1 &&
  4884. (decl_id = this.variable.declarations[0]) &&
  4885. this.start < decl_id.start &&
  4886. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  4887. // a variable accessed before its declaration
  4888. // in the same function or at top level of module
  4889. return (this.isTDZAccess = true);
  4890. }
  4891. if (!this.variable.initReached) {
  4892. // Either a const/let TDZ violation or
  4893. // var use before declaration was encountered.
  4894. return (this.isTDZAccess = true);
  4895. }
  4896. return (this.isTDZAccess = false);
  4897. }
  4898. applyDeoptimizations() {
  4899. this.deoptimized = true;
  4900. if (this.variable instanceof LocalVariable) {
  4901. // When accessing a variable from a module without side effects, this
  4902. // means we use an export of that module and therefore need to potentially
  4903. // include it in the bundle.
  4904. if (!this.variable.module.isExecuted) {
  4905. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  4906. }
  4907. this.variable.consolidateInitializers();
  4908. this.scope.context.requestTreeshakingPass();
  4909. }
  4910. if (this.isVariableReference) {
  4911. this.variable.addUsedPlace(this);
  4912. this.scope.context.requestTreeshakingPass();
  4913. }
  4914. }
  4915. disallowImportReassignment() {
  4916. return this.scope.context.error(logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  4917. }
  4918. getVariableRespectingTDZ() {
  4919. if (this.isPossibleTDZ()) {
  4920. return UNKNOWN_EXPRESSION;
  4921. }
  4922. return this.variable;
  4923. }
  4924. isPureFunction(path) {
  4925. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  4926. for (const segment of path) {
  4927. if (currentPureFunction) {
  4928. if (currentPureFunction[PureFunctionKey]) {
  4929. return true;
  4930. }
  4931. currentPureFunction = currentPureFunction[segment];
  4932. }
  4933. else {
  4934. return false;
  4935. }
  4936. }
  4937. return currentPureFunction?.[PureFunctionKey];
  4938. }
  4939. }
  4940. function closestParentFunctionOrProgram(node) {
  4941. while (node && !/^Program|Function/.test(node.type)) {
  4942. node = node.parent;
  4943. }
  4944. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  4945. return node;
  4946. }
  4947. class ObjectMember extends ExpressionEntity {
  4948. constructor(object, path) {
  4949. super();
  4950. this.object = object;
  4951. this.path = path;
  4952. }
  4953. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4954. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  4955. }
  4956. deoptimizePath(path) {
  4957. this.object.deoptimizePath([...this.path, ...path]);
  4958. }
  4959. getLiteralValueAtPath(path, recursionTracker, origin) {
  4960. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  4961. }
  4962. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4963. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  4964. }
  4965. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4966. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  4967. }
  4968. }
  4969. class Identifier extends IdentifierBase {
  4970. constructor() {
  4971. super(...arguments);
  4972. this.variable = null;
  4973. }
  4974. get isDestructuringDeoptimized() {
  4975. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  4976. }
  4977. set isDestructuringDeoptimized(value) {
  4978. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  4979. }
  4980. addExportedVariables(variables, exportNamesByVariable) {
  4981. if (exportNamesByVariable.has(this.variable)) {
  4982. variables.push(this.variable);
  4983. }
  4984. }
  4985. bind() {
  4986. if (!this.variable && is_reference(this, this.parent)) {
  4987. this.variable = this.scope.findVariable(this.name);
  4988. this.variable.addReference(this);
  4989. this.isVariableReference = true;
  4990. }
  4991. }
  4992. declare(kind, destructuredInitPath, init) {
  4993. let variable;
  4994. const { treeshake } = this.scope.context.options;
  4995. if (kind === 'parameter') {
  4996. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  4997. }
  4998. else {
  4999. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  5000. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  5001. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  5002. variable.markInitializersForDeoptimization();
  5003. }
  5004. }
  5005. return [(this.variable = variable)];
  5006. }
  5007. deoptimizeAssignment(destructuredInitPath, init) {
  5008. this.deoptimizePath(EMPTY_PATH);
  5009. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  5010. }
  5011. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  5012. return (destructuredInitPath.length > 0 &&
  5013. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  5014. }
  5015. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  5016. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  5017. this.isDestructuringDeoptimized = true;
  5018. init.deoptimizeArgumentsOnInteractionAtPath({
  5019. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  5020. type: INTERACTION_ACCESSED
  5021. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  5022. }
  5023. const { propertyReadSideEffects } = this.scope.context.options
  5024. .treeshake;
  5025. if ((this.included ||=
  5026. destructuredInitPath.length > 0 &&
  5027. !context.brokenFlow &&
  5028. propertyReadSideEffects &&
  5029. (propertyReadSideEffects === 'always' ||
  5030. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  5031. if (this.variable && !this.variable.included) {
  5032. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  5033. }
  5034. init.includePath(destructuredInitPath, context);
  5035. return true;
  5036. }
  5037. return false;
  5038. }
  5039. markDeclarationReached() {
  5040. this.variable.initReached = true;
  5041. }
  5042. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  5043. if (this.variable) {
  5044. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  5045. if (name !== this.name) {
  5046. code.overwrite(this.start, this.end, name, {
  5047. contentOnly: true,
  5048. storeName: true
  5049. });
  5050. if (isShorthandProperty) {
  5051. code.prependRight(this.start, `${this.name}: `);
  5052. }
  5053. }
  5054. // In strict mode, any variable named "eval" must be the actual "eval" function
  5055. if (name === 'eval' &&
  5056. renderedParentType === CallExpression$1 &&
  5057. isCalleeOfRenderedParent) {
  5058. code.appendRight(this.start, '0, ');
  5059. }
  5060. }
  5061. }
  5062. }
  5063. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5064. const base = 64;
  5065. function toBase64(value) {
  5066. let outString = '';
  5067. do {
  5068. const currentDigit = value % base;
  5069. value = (value / base) | 0;
  5070. outString = chars[currentDigit] + outString;
  5071. } while (value !== 0);
  5072. return outString;
  5073. }
  5074. function getSafeName(baseName, usedNames, forbiddenNames) {
  5075. let safeName = baseName;
  5076. let count = 1;
  5077. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  5078. safeName = `${baseName}$${toBase64(count++)}`;
  5079. }
  5080. usedNames.add(safeName);
  5081. return safeName;
  5082. }
  5083. class Scope {
  5084. constructor() {
  5085. this.children = [];
  5086. this.variables = new Map();
  5087. }
  5088. /*
  5089. Redeclaration rules:
  5090. - var can redeclare var
  5091. - in function scopes, function and var can redeclare function and var
  5092. - var is hoisted across scopes, function remains in the scope it is declared
  5093. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  5094. - function cannot redeclare catch scope parameters
  5095. - var can redeclare catch scope parameters in a way
  5096. - if the parameter is an identifier and not a pattern
  5097. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  5098. - const, let, class, and function except in the cases above cannot redeclare anything
  5099. */
  5100. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5101. const name = identifier.name;
  5102. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5103. if (existingVariable) {
  5104. if (kind === 'var' && existingVariable.kind === 'var') {
  5105. existingVariable.addDeclaration(identifier, init);
  5106. return existingVariable;
  5107. }
  5108. context.error(logRedeclarationError(name), identifier.start);
  5109. }
  5110. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5111. this.variables.set(name, newVariable);
  5112. return newVariable;
  5113. }
  5114. addHoistedVariable(name, variable) {
  5115. (this.hoistedVariables ||= new Map()).set(name, variable);
  5116. }
  5117. contains(name) {
  5118. return this.variables.has(name);
  5119. }
  5120. findVariable(_name) {
  5121. /* istanbul ignore next */
  5122. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5123. }
  5124. }
  5125. class ChildScope extends Scope {
  5126. constructor(parent, context) {
  5127. super();
  5128. this.parent = parent;
  5129. this.context = context;
  5130. this.accessedOutsideVariables = new Map();
  5131. parent.children.push(this);
  5132. }
  5133. addAccessedDynamicImport(importExpression) {
  5134. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5135. if (this.parent instanceof ChildScope) {
  5136. this.parent.addAccessedDynamicImport(importExpression);
  5137. }
  5138. }
  5139. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5140. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5141. for (const name of globals) {
  5142. accessedGlobals.add(name);
  5143. }
  5144. accessedGlobalsByScope.set(this, accessedGlobals);
  5145. if (this.parent instanceof ChildScope) {
  5146. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5147. }
  5148. }
  5149. addNamespaceMemberAccess(name, variable) {
  5150. this.accessedOutsideVariables.set(name, variable);
  5151. this.parent.addNamespaceMemberAccess(name, variable);
  5152. }
  5153. addReturnExpression(expression) {
  5154. if (this.parent instanceof ChildScope) {
  5155. this.parent.addReturnExpression(expression);
  5156. }
  5157. }
  5158. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5159. for (const variable of this.accessedOutsideVariables.values()) {
  5160. if (variable.included) {
  5161. usedNames.add(variable.getBaseVariableName());
  5162. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5163. usedNames.add('exports');
  5164. }
  5165. }
  5166. }
  5167. const accessedGlobals = accessedGlobalsByScope.get(this);
  5168. if (accessedGlobals) {
  5169. for (const name of accessedGlobals) {
  5170. usedNames.add(name);
  5171. }
  5172. }
  5173. }
  5174. contains(name) {
  5175. return this.variables.has(name) || this.parent.contains(name);
  5176. }
  5177. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5178. const usedNames = new Set();
  5179. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5180. if (this.accessedDynamicImports) {
  5181. for (const importExpression of this.accessedDynamicImports) {
  5182. if (importExpression.inlineNamespace) {
  5183. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5184. }
  5185. }
  5186. }
  5187. for (const [name, variable] of this.variables) {
  5188. if (variable.included || variable.alwaysRendered) {
  5189. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  5190. }
  5191. }
  5192. for (const scope of this.children) {
  5193. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5194. }
  5195. }
  5196. findLexicalBoundary() {
  5197. return this.parent.findLexicalBoundary();
  5198. }
  5199. findGlobal(name) {
  5200. const variable = this.parent.findVariable(name);
  5201. this.accessedOutsideVariables.set(name, variable);
  5202. return variable;
  5203. }
  5204. findVariable(name) {
  5205. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5206. if (knownVariable) {
  5207. return knownVariable;
  5208. }
  5209. const variable = this.parent.findVariable(name);
  5210. this.accessedOutsideVariables.set(name, variable);
  5211. return variable;
  5212. }
  5213. }
  5214. function checkEffectForNodes(nodes, context) {
  5215. for (const node of nodes) {
  5216. if (node.hasEffects(context)) {
  5217. return true;
  5218. }
  5219. }
  5220. return false;
  5221. }
  5222. class MethodBase extends NodeBase {
  5223. constructor() {
  5224. super(...arguments);
  5225. this.accessedValue = null;
  5226. }
  5227. get computed() {
  5228. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  5229. }
  5230. set computed(value) {
  5231. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  5232. }
  5233. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5234. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  5235. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5236. args: interaction.args,
  5237. type: INTERACTION_CALLED,
  5238. withNew: false
  5239. }, EMPTY_PATH, recursionTracker);
  5240. }
  5241. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  5242. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5243. args: interaction.args,
  5244. type: INTERACTION_CALLED,
  5245. withNew: false
  5246. }, EMPTY_PATH, recursionTracker);
  5247. }
  5248. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5249. }
  5250. // As getter properties directly receive their values from fixed function
  5251. // expressions, there is no known situation where a getter is deoptimized.
  5252. deoptimizeCache() { }
  5253. deoptimizePath(path) {
  5254. this.getAccessedValue()[0].deoptimizePath(path);
  5255. }
  5256. getLiteralValueAtPath(path, recursionTracker, origin) {
  5257. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  5258. }
  5259. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5260. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5261. }
  5262. hasEffects(context) {
  5263. return this.key.hasEffects(context);
  5264. }
  5265. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5266. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  5267. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5268. args: interaction.args,
  5269. type: INTERACTION_CALLED,
  5270. withNew: false
  5271. }, context);
  5272. }
  5273. // setters are only called for empty paths
  5274. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  5275. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5276. args: interaction.args,
  5277. type: INTERACTION_CALLED,
  5278. withNew: false
  5279. }, context);
  5280. }
  5281. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  5282. }
  5283. getAccessedValue() {
  5284. if (this.accessedValue === null) {
  5285. if (this.kind === 'get') {
  5286. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  5287. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  5288. }
  5289. else {
  5290. return (this.accessedValue = [this.value, false]);
  5291. }
  5292. }
  5293. return this.accessedValue;
  5294. }
  5295. }
  5296. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5297. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  5298. class MethodDefinition extends MethodBase {
  5299. hasEffects(context) {
  5300. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5301. }
  5302. }
  5303. class BlockScope extends ChildScope {
  5304. constructor(parent) {
  5305. super(parent, parent.context);
  5306. }
  5307. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5308. if (kind === 'var') {
  5309. const name = identifier.name;
  5310. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5311. if (existingVariable) {
  5312. if (existingVariable.kind === 'var' ||
  5313. (kind === 'var' && existingVariable.kind === 'parameter')) {
  5314. existingVariable.addDeclaration(identifier, init);
  5315. return existingVariable;
  5316. }
  5317. return context.error(logRedeclarationError(name), identifier.start);
  5318. }
  5319. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5320. // Necessary to make sure the init is deoptimized for conditional declarations.
  5321. // We cannot call deoptimizePath here.
  5322. declaredVariable.markInitializersForDeoptimization();
  5323. // We add the variable to this and all parent scopes to reliably detect conflicts
  5324. this.addHoistedVariable(name, declaredVariable);
  5325. return declaredVariable;
  5326. }
  5327. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5328. }
  5329. }
  5330. class StaticBlock extends NodeBase {
  5331. createScope(parentScope) {
  5332. this.scope = new BlockScope(parentScope);
  5333. }
  5334. hasEffects(context) {
  5335. for (const node of this.body) {
  5336. if (node.hasEffects(context))
  5337. return true;
  5338. }
  5339. return false;
  5340. }
  5341. include(context, includeChildrenRecursively) {
  5342. this.included = true;
  5343. for (const node of this.body) {
  5344. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5345. node.include(context, includeChildrenRecursively);
  5346. }
  5347. }
  5348. render(code, options) {
  5349. if (this.body.length > 0) {
  5350. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  5351. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  5352. }
  5353. else {
  5354. super.render(code, options);
  5355. }
  5356. }
  5357. }
  5358. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5359. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  5360. function isStaticBlock(statement) {
  5361. return statement.type === StaticBlock$1;
  5362. }
  5363. class ClassNode extends NodeBase {
  5364. constructor() {
  5365. super(...arguments);
  5366. this.objectEntity = null;
  5367. }
  5368. createScope(parentScope) {
  5369. this.scope = new ChildScope(parentScope, parentScope.context);
  5370. }
  5371. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5372. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5373. }
  5374. deoptimizeCache() {
  5375. this.getObjectEntity().deoptimizeAllProperties();
  5376. }
  5377. deoptimizePath(path) {
  5378. this.getObjectEntity().deoptimizePath(path);
  5379. }
  5380. getLiteralValueAtPath(path, recursionTracker, origin) {
  5381. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5382. }
  5383. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5384. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5385. }
  5386. hasEffects(context) {
  5387. if (!this.deoptimized)
  5388. this.applyDeoptimizations();
  5389. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  5390. this.id?.markDeclarationReached();
  5391. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5392. }
  5393. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5394. return interaction.type === INTERACTION_CALLED && path.length === 0
  5395. ? !interaction.withNew ||
  5396. (this.classConstructor === null
  5397. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  5398. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  5399. false
  5400. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5401. }
  5402. include(context, includeChildrenRecursively) {
  5403. if (!this.included)
  5404. this.includeNode(context);
  5405. this.superClass?.include(context, includeChildrenRecursively);
  5406. this.body.include(context, includeChildrenRecursively);
  5407. for (const decorator of this.decorators)
  5408. decorator.include(context, includeChildrenRecursively);
  5409. if (this.id) {
  5410. this.id.markDeclarationReached();
  5411. this.id.include(context, includeChildrenRecursively);
  5412. }
  5413. }
  5414. initialise() {
  5415. super.initialise();
  5416. this.id?.declare('class', EMPTY_PATH, this);
  5417. for (const method of this.body.body) {
  5418. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  5419. this.classConstructor = method;
  5420. return;
  5421. }
  5422. }
  5423. this.classConstructor = null;
  5424. }
  5425. applyDeoptimizations() {
  5426. this.deoptimized = true;
  5427. for (const definition of this.body.body) {
  5428. if (!isStaticBlock(definition) &&
  5429. !(definition.static ||
  5430. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  5431. // Calls to methods are not tracked, ensure that the return value is deoptimized
  5432. definition.deoptimizePath(UNKNOWN_PATH);
  5433. }
  5434. }
  5435. this.scope.context.requestTreeshakingPass();
  5436. }
  5437. getObjectEntity() {
  5438. if (this.objectEntity !== null) {
  5439. return this.objectEntity;
  5440. }
  5441. const staticProperties = [];
  5442. const dynamicMethods = [];
  5443. for (const definition of this.body.body) {
  5444. if (isStaticBlock(definition))
  5445. continue;
  5446. const properties = definition.static ? staticProperties : dynamicMethods;
  5447. const definitionKind = definition.kind;
  5448. // Note that class fields do not end up on the prototype
  5449. if (properties === dynamicMethods && !definitionKind)
  5450. continue;
  5451. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  5452. let key;
  5453. if (definition.computed) {
  5454. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5455. if (typeof keyValue === 'symbol') {
  5456. properties.push({ key: UnknownKey, kind, property: definition });
  5457. continue;
  5458. }
  5459. else {
  5460. key = String(keyValue);
  5461. }
  5462. }
  5463. else {
  5464. key =
  5465. definition.key instanceof Identifier
  5466. ? definition.key.name
  5467. : String(definition.key.value);
  5468. }
  5469. properties.push({ key, kind, property: definition });
  5470. }
  5471. staticProperties.unshift({
  5472. key: 'prototype',
  5473. kind: 'init',
  5474. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  5475. });
  5476. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  5477. }
  5478. }
  5479. ClassNode.prototype.includeNode = onlyIncludeSelf;
  5480. class ClassDeclaration extends ClassNode {
  5481. initialise() {
  5482. super.initialise();
  5483. if (this.id !== null) {
  5484. this.id.variable.isId = true;
  5485. }
  5486. }
  5487. parseNode(esTreeNode) {
  5488. if (esTreeNode.id !== null) {
  5489. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  5490. }
  5491. return super.parseNode(esTreeNode);
  5492. }
  5493. render(code, options) {
  5494. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  5495. if (this.id) {
  5496. const { variable, name } = this.id;
  5497. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5498. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  5499. }
  5500. const renderedVariable = variable.getName(getPropertyAccess);
  5501. if (renderedVariable !== name) {
  5502. this.decorators.map(decorator => decorator.render(code, options));
  5503. this.superClass?.render(code, options);
  5504. this.body.render(code, {
  5505. ...options,
  5506. useOriginalName: (_variable) => _variable === variable
  5507. });
  5508. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  5509. code.prependLeft(this.end, ';');
  5510. return;
  5511. }
  5512. }
  5513. super.render(code, options);
  5514. }
  5515. applyDeoptimizations() {
  5516. super.applyDeoptimizations();
  5517. const { id, scope } = this;
  5518. if (id) {
  5519. const { name, variable } = id;
  5520. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  5521. if (accessedVariable !== variable) {
  5522. accessedVariable.forbidName(name);
  5523. }
  5524. }
  5525. }
  5526. }
  5527. }
  5528. class ArgumentsVariable extends LocalVariable {
  5529. constructor(context) {
  5530. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  5531. }
  5532. addArgumentToBeDeoptimized(_argument) { }
  5533. // Only If there is at least one reference, then we need to track all
  5534. // arguments in order to be able to deoptimize them.
  5535. addReference() {
  5536. this.deoptimizedArguments = [];
  5537. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  5538. }
  5539. hasEffectsOnInteractionAtPath(path, { type }) {
  5540. return type !== INTERACTION_ACCESSED || path.length > 1;
  5541. }
  5542. includePath(path, context) {
  5543. super.includePath(path, context);
  5544. for (const argument of this.deoptimizedArguments) {
  5545. argument.deoptimizePath(UNKNOWN_PATH);
  5546. }
  5547. this.deoptimizedArguments.length = 0;
  5548. }
  5549. }
  5550. function addArgumentToBeDeoptimized(argument) {
  5551. if (this.included) {
  5552. argument.deoptimizePath(UNKNOWN_PATH);
  5553. }
  5554. else {
  5555. this.deoptimizedArguments?.push(argument);
  5556. }
  5557. }
  5558. const MAX_TRACKED_INTERACTIONS = 20;
  5559. const NO_INTERACTIONS = EMPTY_ARRAY;
  5560. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  5561. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  5562. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  5563. class ParameterVariable extends LocalVariable {
  5564. constructor(name, declarator, argumentPath, context) {
  5565. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  5566. this.includedPathTracker = new IncludedTopLevelPathTracker();
  5567. this.argumentsToBeDeoptimized = new Set();
  5568. this.deoptimizationInteractions = [];
  5569. this.deoptimizations = new EntityPathTracker();
  5570. this.deoptimizedFields = new Set();
  5571. this.expressionsDependingOnKnownValue = [];
  5572. this.knownValue = null;
  5573. this.knownValueLiteral = UnknownValue;
  5574. }
  5575. addArgumentForDeoptimization(entity) {
  5576. this.updateKnownValue(entity);
  5577. if (entity === UNKNOWN_EXPRESSION) {
  5578. // As unknown expressions fully deoptimize all interactions, we can clear
  5579. // the interaction cache at this point provided we keep this optimization
  5580. // in mind when adding new interactions
  5581. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5582. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  5583. for (const { interaction } of this.deoptimizationInteractions) {
  5584. deoptimizeInteraction(interaction);
  5585. }
  5586. this.deoptimizationInteractions = NO_INTERACTIONS;
  5587. }
  5588. }
  5589. else if (this.deoptimizedFields.has(UnknownKey)) {
  5590. // This means that we already deoptimized all interactions and no longer
  5591. // track them
  5592. entity.deoptimizePath([...this.initPath, UnknownKey]);
  5593. }
  5594. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  5595. this.argumentsToBeDeoptimized.add(entity);
  5596. for (const field of this.deoptimizedFields) {
  5597. entity.deoptimizePath([...this.initPath, field]);
  5598. }
  5599. for (const { interaction, path } of this.deoptimizationInteractions) {
  5600. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5601. }
  5602. }
  5603. }
  5604. /** This says we should not make assumptions about the value of the parameter.
  5605. * This is different from deoptimization that will also cause argument values
  5606. * to be deoptimized. */
  5607. markReassigned() {
  5608. if (this.isReassigned) {
  5609. return;
  5610. }
  5611. super.markReassigned();
  5612. for (const expression of this.expressionsDependingOnKnownValue) {
  5613. expression.deoptimizeCache();
  5614. }
  5615. this.expressionsDependingOnKnownValue = EMPTY_ARRAY;
  5616. }
  5617. deoptimizeCache() {
  5618. this.markReassigned();
  5619. }
  5620. /**
  5621. * Update the known value of the parameter variable.
  5622. * Must be called for every function call, so it can track all the arguments,
  5623. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  5624. * @param argument The argument of the function call
  5625. */
  5626. updateKnownValue(argument) {
  5627. if (this.isReassigned) {
  5628. return;
  5629. }
  5630. if (this.knownValue === null) {
  5631. this.knownValue = argument;
  5632. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  5633. return;
  5634. }
  5635. // the same literal or identifier, do nothing
  5636. if (this.knownValue === argument ||
  5637. (this.knownValue instanceof Identifier &&
  5638. argument instanceof Identifier &&
  5639. this.knownValue.variable === argument.variable)) {
  5640. return;
  5641. }
  5642. const { knownValueLiteral } = this;
  5643. if (typeof knownValueLiteral === 'symbol' ||
  5644. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  5645. knownValueLiteral) {
  5646. this.markReassigned();
  5647. }
  5648. }
  5649. /**
  5650. * This function freezes the known value of the parameter variable,
  5651. * so the optimization starts with a certain ExpressionEntity.
  5652. * The optimization can be undone by calling `markReassigned`.
  5653. * @returns the frozen value
  5654. */
  5655. getKnownValue() {
  5656. return this.knownValue || UNKNOWN_EXPRESSION;
  5657. }
  5658. getLiteralValueAtPath(path, recursionTracker, origin) {
  5659. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5660. return UnknownValue;
  5661. }
  5662. const knownValue = this.getKnownValue();
  5663. this.expressionsDependingOnKnownValue.push(origin);
  5664. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  5665. }
  5666. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5667. const { type } = interaction;
  5668. if (this.isReassigned ||
  5669. type === INTERACTION_ASSIGNED ||
  5670. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5671. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  5672. }
  5673. return (!(type === INTERACTION_CALLED
  5674. ? (interaction.withNew
  5675. ? context.instantiated
  5676. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  5677. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  5678. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  5679. }
  5680. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  5681. // For performance reasons, we fully deoptimize all deeper interactions
  5682. if (path.length >= 2 ||
  5683. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  5684. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  5685. (path.length === 1 &&
  5686. (this.deoptimizedFields.has(UnknownKey) ||
  5687. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  5688. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  5689. deoptimizeInteraction(interaction);
  5690. return;
  5691. }
  5692. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  5693. for (const entity of this.argumentsToBeDeoptimized) {
  5694. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5695. }
  5696. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5697. this.deoptimizationInteractions.push({
  5698. interaction,
  5699. path
  5700. });
  5701. }
  5702. }
  5703. }
  5704. deoptimizePath(path) {
  5705. if (path.length === 0) {
  5706. this.markReassigned();
  5707. return;
  5708. }
  5709. if (this.deoptimizedFields.has(UnknownKey)) {
  5710. return;
  5711. }
  5712. const key = path[0];
  5713. if (this.deoptimizedFields.has(key)) {
  5714. return;
  5715. }
  5716. this.deoptimizedFields.add(key);
  5717. for (const entity of this.argumentsToBeDeoptimized) {
  5718. // We do not need a recursion tracker here as we already track whether
  5719. // this field is deoptimized
  5720. entity.deoptimizePath([...this.initPath, key]);
  5721. }
  5722. if (key === UnknownKey) {
  5723. // save some memory
  5724. this.deoptimizationInteractions = NO_INTERACTIONS;
  5725. this.deoptimizations = EMPTY_PATH_TRACKER;
  5726. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  5727. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  5728. }
  5729. }
  5730. getReturnExpressionWhenCalledAtPath(path) {
  5731. // We deoptimize everything that is called as that will trivially deoptimize
  5732. // the corresponding return expressions as well and avoid badly performing
  5733. // and complicated alternatives
  5734. if (path.length === 0) {
  5735. this.deoptimizePath(UNKNOWN_PATH);
  5736. }
  5737. else if (!this.deoptimizedFields.has(path[0])) {
  5738. this.deoptimizePath([path[0]]);
  5739. }
  5740. return UNKNOWN_RETURN_EXPRESSION;
  5741. }
  5742. includeArgumentPaths(entity, context) {
  5743. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  5744. }
  5745. }
  5746. class ThisVariable extends ParameterVariable {
  5747. constructor(context) {
  5748. super('this', null, EMPTY_PATH, context);
  5749. }
  5750. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5751. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  5752. }
  5753. }
  5754. class CatchBodyScope extends ChildScope {
  5755. constructor(parent) {
  5756. super(parent, parent.context);
  5757. this.parent = parent;
  5758. }
  5759. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5760. if (kind === 'var') {
  5761. const name = identifier.name;
  5762. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5763. if (existingVariable) {
  5764. const existingKind = existingVariable.kind;
  5765. if (existingKind === 'parameter' &&
  5766. // If this is a destructured parameter, it is forbidden to redeclare
  5767. existingVariable.declarations[0].parent.type === CatchClause$1) {
  5768. // If this is a var with the same name as the catch scope parameter,
  5769. // the assignment actually goes to the parameter and the var is
  5770. // hoisted without assignment. Locally, it is shadowed by the
  5771. // parameter
  5772. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  5773. // To avoid the need to rewrite the declaration, we link the variable
  5774. // names. If we ever implement a logic that splits initialization and
  5775. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  5776. // removed again.
  5777. // We do not need to check whether there already is a linked
  5778. // variable because then declaredVariable would be that linked
  5779. // variable.
  5780. existingVariable.renderLikeHoisted(declaredVariable);
  5781. this.addHoistedVariable(name, declaredVariable);
  5782. return declaredVariable;
  5783. }
  5784. if (existingKind === 'var') {
  5785. existingVariable.addDeclaration(identifier, init);
  5786. return existingVariable;
  5787. }
  5788. return context.error(logRedeclarationError(name), identifier.start);
  5789. }
  5790. // We only add parameters to parameter scopes
  5791. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5792. // Necessary to make sure the init is deoptimized for conditional declarations.
  5793. // We cannot call deoptimizePath here.
  5794. declaredVariable.markInitializersForDeoptimization();
  5795. // We add the variable to this and all parent scopes to reliably detect conflicts
  5796. this.addHoistedVariable(name, declaredVariable);
  5797. return declaredVariable;
  5798. }
  5799. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5800. }
  5801. }
  5802. class FunctionBodyScope extends ChildScope {
  5803. constructor(parent) {
  5804. super(parent, parent.context);
  5805. }
  5806. // There is stuff that is only allowed in function scopes, i.e. functions can
  5807. // be redeclared, functions and var can redeclare each other
  5808. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5809. const name = identifier.name;
  5810. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5811. if (existingVariable) {
  5812. const existingKind = existingVariable.kind;
  5813. if ((kind === 'var' || kind === 'function') &&
  5814. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  5815. existingVariable.addDeclaration(identifier, init);
  5816. return existingVariable;
  5817. }
  5818. context.error(logRedeclarationError(name), identifier.start);
  5819. }
  5820. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5821. this.variables.set(name, newVariable);
  5822. return newVariable;
  5823. }
  5824. }
  5825. class ParameterScope extends ChildScope {
  5826. constructor(parent, isCatchScope) {
  5827. super(parent, parent.context);
  5828. this.hasRest = false;
  5829. this.parameters = [];
  5830. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  5831. }
  5832. /**
  5833. * Adds a parameter to this scope. Parameters must be added in the correct
  5834. * order, i.e. from left to right.
  5835. */
  5836. addParameterDeclaration(identifier, argumentPath) {
  5837. const { name, start } = identifier;
  5838. const existingParameter = this.variables.get(name);
  5839. if (existingParameter) {
  5840. return this.context.error(logDuplicateArgumentNameError(name), start);
  5841. }
  5842. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  5843. this.variables.set(name, variable);
  5844. // We also add it to the body scope to detect name conflicts with local
  5845. // variables. We still need the intermediate scope, though, as parameter
  5846. // defaults are NOT taken from the body scope but from the parameters or
  5847. // outside scope.
  5848. this.bodyScope.addHoistedVariable(name, variable);
  5849. return variable;
  5850. }
  5851. addParameterVariables(parameters, hasRest) {
  5852. this.parameters = parameters;
  5853. for (const parameterList of parameters) {
  5854. for (const parameter of parameterList) {
  5855. parameter.alwaysRendered = true;
  5856. }
  5857. }
  5858. this.hasRest = hasRest;
  5859. }
  5860. includeCallArguments({ args }, context) {
  5861. let calledFromTryStatement = false;
  5862. let argumentIncluded = false;
  5863. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  5864. let lastExplicitlyIncludedIndex = args.length - 1;
  5865. // If there is a SpreadElement, we need to include all arguments after it
  5866. // because we no longer know which argument corresponds to which parameter.
  5867. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  5868. const argument = args[argumentIndex];
  5869. if (argument instanceof SpreadElement && !argumentIncluded) {
  5870. argumentIncluded = true;
  5871. lastExplicitlyIncludedIndex = argumentIndex - 1;
  5872. }
  5873. if (argumentIncluded) {
  5874. argument.includePath(UNKNOWN_PATH, context);
  5875. argument.include(context, false);
  5876. }
  5877. }
  5878. // Now we go backwards either starting from the last argument or before the
  5879. // first SpreadElement to ensure all arguments before are included as needed
  5880. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  5881. const parameterVariables = this.parameters[index - 1] || restParameter;
  5882. const argument = args[index];
  5883. if (parameterVariables) {
  5884. calledFromTryStatement = false;
  5885. if (parameterVariables.length === 0) {
  5886. // handle empty destructuring to avoid destructuring undefined
  5887. argumentIncluded = true;
  5888. }
  5889. else {
  5890. for (const parameterVariable of parameterVariables) {
  5891. if (parameterVariable.calledFromTryStatement) {
  5892. calledFromTryStatement = true;
  5893. }
  5894. if (parameterVariable.included) {
  5895. argumentIncluded = true;
  5896. if (calledFromTryStatement) {
  5897. argument.include(context, true);
  5898. }
  5899. else {
  5900. parameterVariable.includeArgumentPaths(argument, context);
  5901. argument.include(context, false);
  5902. }
  5903. }
  5904. }
  5905. }
  5906. }
  5907. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  5908. argumentIncluded = true;
  5909. argument.include(context, calledFromTryStatement);
  5910. }
  5911. }
  5912. }
  5913. }
  5914. class ReturnValueScope extends ParameterScope {
  5915. constructor() {
  5916. super(...arguments);
  5917. this.returnExpression = null;
  5918. this.returnExpressions = [];
  5919. }
  5920. addReturnExpression(expression) {
  5921. this.returnExpressions.push(expression);
  5922. }
  5923. deoptimizeArgumentsOnCall({ args }) {
  5924. const { parameters } = this;
  5925. let position = 0;
  5926. for (; position < args.length - 1; position++) {
  5927. // Only the "this" argument arg[0] can be null
  5928. const argument = args[position + 1];
  5929. if (argument instanceof SpreadElement) {
  5930. // This deoptimizes the current and remaining parameters and arguments
  5931. for (; position < parameters.length; position++) {
  5932. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  5933. for (const variable of parameters[position]) {
  5934. variable.markReassigned();
  5935. }
  5936. }
  5937. break;
  5938. }
  5939. if (this.hasRest && position >= parameters.length - 1) {
  5940. argument.deoptimizePath(UNKNOWN_PATH);
  5941. }
  5942. else {
  5943. const variables = parameters[position];
  5944. if (variables) {
  5945. for (const variable of variables) {
  5946. variable.addArgumentForDeoptimization(argument);
  5947. }
  5948. }
  5949. this.addArgumentToBeDeoptimized(argument);
  5950. }
  5951. }
  5952. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  5953. for (; position < nonRestParameterLength; position++) {
  5954. for (const variable of parameters[position]) {
  5955. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  5956. }
  5957. }
  5958. }
  5959. getReturnExpression() {
  5960. if (this.returnExpression === null)
  5961. this.updateReturnExpression();
  5962. return this.returnExpression;
  5963. }
  5964. deoptimizeAllParameters() {
  5965. for (const parameter of this.parameters) {
  5966. for (const variable of parameter) {
  5967. variable.deoptimizePath(UNKNOWN_PATH);
  5968. variable.markReassigned();
  5969. }
  5970. }
  5971. }
  5972. reassignAllParameters() {
  5973. for (const parameter of this.parameters) {
  5974. for (const variable of parameter) {
  5975. variable.markReassigned();
  5976. }
  5977. }
  5978. }
  5979. addArgumentToBeDeoptimized(_argument) { }
  5980. updateReturnExpression() {
  5981. if (this.returnExpressions.length === 1) {
  5982. this.returnExpression = this.returnExpressions[0];
  5983. }
  5984. else {
  5985. this.returnExpression = UNKNOWN_EXPRESSION;
  5986. for (const expression of this.returnExpressions) {
  5987. expression.deoptimizePath(UNKNOWN_PATH);
  5988. }
  5989. }
  5990. }
  5991. }
  5992. class FunctionScope extends ReturnValueScope {
  5993. constructor(parent, functionNode) {
  5994. super(parent, false);
  5995. this.functionNode = functionNode;
  5996. const { context } = parent;
  5997. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  5998. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  5999. }
  6000. findLexicalBoundary() {
  6001. return this;
  6002. }
  6003. includeCallArguments(interaction, context) {
  6004. super.includeCallArguments(interaction, context);
  6005. if (this.argumentsVariable.included) {
  6006. const { args } = interaction;
  6007. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  6008. const argument = args[argumentIndex];
  6009. if (argument) {
  6010. argument.includePath(UNKNOWN_PATH, context);
  6011. argument.include(context, false);
  6012. }
  6013. }
  6014. }
  6015. }
  6016. addArgumentToBeDeoptimized(argument) {
  6017. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  6018. }
  6019. }
  6020. class ExpressionStatement extends NodeBase {
  6021. initialise() {
  6022. super.initialise();
  6023. if (this.directive &&
  6024. this.directive !== 'use strict' &&
  6025. this.parent.type === Program$1) {
  6026. this.scope.context.log(LOGLEVEL_WARN,
  6027. // This is necessary, because either way (deleting or not) can lead to errors.
  6028. logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  6029. }
  6030. }
  6031. removeAnnotations(code) {
  6032. this.expression.removeAnnotations(code);
  6033. }
  6034. render(code, options) {
  6035. super.render(code, options);
  6036. if (code.original[this.end - 1] !== ';') {
  6037. code.appendLeft(this.end, ';');
  6038. }
  6039. }
  6040. shouldBeIncluded(context) {
  6041. if (this.directive && this.directive !== 'use strict')
  6042. return this.parent.type !== Program$1;
  6043. return super.shouldBeIncluded(context);
  6044. }
  6045. }
  6046. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6047. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6048. class BlockStatement extends NodeBase {
  6049. get deoptimizeBody() {
  6050. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  6051. }
  6052. set deoptimizeBody(value) {
  6053. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  6054. }
  6055. get directlyIncluded() {
  6056. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  6057. }
  6058. set directlyIncluded(value) {
  6059. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  6060. }
  6061. addImplicitReturnExpressionToScope() {
  6062. const lastStatement = this.body[this.body.length - 1];
  6063. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  6064. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  6065. }
  6066. }
  6067. createScope(parentScope) {
  6068. this.scope = this.parent.preventChildBlockScope
  6069. ? parentScope
  6070. : new BlockScope(parentScope);
  6071. }
  6072. hasEffects(context) {
  6073. if (this.deoptimizeBody)
  6074. return true;
  6075. for (const node of this.body) {
  6076. if (context.brokenFlow)
  6077. break;
  6078. if (node.hasEffects(context))
  6079. return true;
  6080. }
  6081. return false;
  6082. }
  6083. include(context, includeChildrenRecursively) {
  6084. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  6085. this.included = true;
  6086. this.directlyIncluded = true;
  6087. if (this.deoptimizeBody)
  6088. includeChildrenRecursively = true;
  6089. for (const node of this.body) {
  6090. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6091. node.include(context, includeChildrenRecursively);
  6092. }
  6093. }
  6094. }
  6095. initialise() {
  6096. super.initialise();
  6097. const firstBodyStatement = this.body[0];
  6098. this.deoptimizeBody =
  6099. firstBodyStatement instanceof ExpressionStatement &&
  6100. firstBodyStatement.directive === 'use asm';
  6101. }
  6102. render(code, options) {
  6103. if (this.body.length > 0) {
  6104. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  6105. }
  6106. else {
  6107. super.render(code, options);
  6108. }
  6109. }
  6110. }
  6111. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6112. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6113. class RestElement extends NodeBase {
  6114. constructor() {
  6115. super(...arguments);
  6116. this.declarationInit = null;
  6117. }
  6118. addExportedVariables(variables, exportNamesByVariable) {
  6119. this.argument.addExportedVariables(variables, exportNamesByVariable);
  6120. }
  6121. declare(kind, destructuredInitPath, init) {
  6122. this.declarationInit = init;
  6123. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  6124. }
  6125. deoptimizeAssignment(destructuredInitPath, init) {
  6126. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  6127. }
  6128. deoptimizePath(path) {
  6129. if (path.length === 0) {
  6130. this.argument.deoptimizePath(EMPTY_PATH);
  6131. }
  6132. }
  6133. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6134. return (path.length > 0 ||
  6135. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  6136. }
  6137. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  6138. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  6139. }
  6140. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  6141. return (this.included =
  6142. this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init) || this.included);
  6143. }
  6144. include(context, includeChildrenRecursively) {
  6145. if (!this.included)
  6146. this.includeNode(context);
  6147. // This should just include the identifier, its properties should be
  6148. // included where the variable is used.
  6149. this.argument.include(context, includeChildrenRecursively);
  6150. }
  6151. markDeclarationReached() {
  6152. this.argument.markDeclarationReached();
  6153. }
  6154. applyDeoptimizations() {
  6155. this.deoptimized = true;
  6156. if (this.declarationInit !== null) {
  6157. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  6158. this.scope.context.requestTreeshakingPass();
  6159. }
  6160. }
  6161. }
  6162. RestElement.prototype.includeNode = onlyIncludeSelf;
  6163. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  6164. ? destructuredInitPath
  6165. : [...destructuredInitPath, UnknownKey];
  6166. class FunctionBase extends NodeBase {
  6167. constructor() {
  6168. super(...arguments);
  6169. this.parameterVariableValuesDeoptimized = false;
  6170. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  6171. }
  6172. get async() {
  6173. return isFlagSet(this.flags, 256 /* Flag.async */);
  6174. }
  6175. set async(value) {
  6176. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  6177. }
  6178. get deoptimizedReturn() {
  6179. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  6180. }
  6181. set deoptimizedReturn(value) {
  6182. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  6183. }
  6184. get generator() {
  6185. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  6186. }
  6187. set generator(value) {
  6188. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  6189. }
  6190. get hasCachedEffects() {
  6191. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  6192. }
  6193. set hasCachedEffects(value) {
  6194. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  6195. }
  6196. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6197. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  6198. this.scope.deoptimizeArgumentsOnCall(interaction);
  6199. }
  6200. else {
  6201. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6202. }
  6203. }
  6204. deoptimizePath(path) {
  6205. this.getObjectEntity().deoptimizePath(path);
  6206. if (path.length === 1 && path[0] === UnknownKey) {
  6207. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  6208. // which means the return expression and parameters need to be reassigned
  6209. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6210. this.scope.deoptimizeAllParameters();
  6211. }
  6212. }
  6213. getLiteralValueAtPath(path, recursionTracker, origin) {
  6214. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6215. }
  6216. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6217. if (path.length > 0) {
  6218. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6219. }
  6220. if (this.async) {
  6221. if (!this.deoptimizedReturn) {
  6222. this.deoptimizedReturn = true;
  6223. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6224. this.scope.context.requestTreeshakingPass();
  6225. }
  6226. return UNKNOWN_RETURN_EXPRESSION;
  6227. }
  6228. return [this.scope.getReturnExpression(), false];
  6229. }
  6230. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6231. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  6232. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6233. }
  6234. if (this.hasCachedEffects) {
  6235. return true;
  6236. }
  6237. if (this.async) {
  6238. const { propertyReadSideEffects } = this.scope.context.options
  6239. .treeshake;
  6240. const returnExpression = this.scope.getReturnExpression();
  6241. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  6242. (propertyReadSideEffects &&
  6243. (propertyReadSideEffects === 'always' ||
  6244. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  6245. this.hasCachedEffects = true;
  6246. return true;
  6247. }
  6248. }
  6249. const { propertyReadSideEffects } = this.scope.context.options
  6250. .treeshake;
  6251. for (let index = 0; index < this.params.length; index++) {
  6252. const parameter = this.params[index];
  6253. if (parameter.hasEffects(context) ||
  6254. (propertyReadSideEffects &&
  6255. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  6256. this.hasCachedEffects = true;
  6257. return true;
  6258. }
  6259. }
  6260. return false;
  6261. }
  6262. /**
  6263. * If the function (expression or declaration) is only used as function calls
  6264. */
  6265. onlyFunctionCallUsed() {
  6266. let variable = null;
  6267. if (this.parent.type === VariableDeclarator$1) {
  6268. variable = this.parent.id.variable ?? null;
  6269. }
  6270. if (this.parent.type === ExportDefaultDeclaration$1) {
  6271. variable = this.parent.variable;
  6272. }
  6273. return variable?.getOnlyFunctionCallUsed() ?? false;
  6274. }
  6275. include(context, includeChildrenRecursively) {
  6276. if (!this.included)
  6277. this.includeNode(context);
  6278. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  6279. this.parameterVariableValuesDeoptimized = true;
  6280. this.scope.reassignAllParameters();
  6281. }
  6282. const { brokenFlow } = context;
  6283. context.brokenFlow = false;
  6284. this.body.include(context, includeChildrenRecursively);
  6285. context.brokenFlow = brokenFlow;
  6286. }
  6287. initialise() {
  6288. super.initialise();
  6289. if (this.body instanceof BlockStatement) {
  6290. this.body.addImplicitReturnExpressionToScope();
  6291. }
  6292. else {
  6293. this.scope.addReturnExpression(this.body);
  6294. }
  6295. if (this.annotations &&
  6296. this.scope.context.options.treeshake.annotations) {
  6297. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  6298. }
  6299. }
  6300. parseNode(esTreeNode) {
  6301. const { body, params } = esTreeNode;
  6302. const { scope } = this;
  6303. const { bodyScope, context } = scope;
  6304. // We need to ensure that parameters are declared before the body is parsed
  6305. // so that the scope already knows all parameters and can detect conflicts
  6306. // when parsing the body.
  6307. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  6308. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  6309. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  6310. return super.parseNode(esTreeNode);
  6311. }
  6312. }
  6313. FunctionBase.prototype.preventChildBlockScope = true;
  6314. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6315. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  6316. class FunctionNode extends FunctionBase {
  6317. constructor() {
  6318. super(...arguments);
  6319. this.objectEntity = null;
  6320. }
  6321. createScope(parentScope) {
  6322. this.scope = new FunctionScope(parentScope, this);
  6323. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  6324. // This makes sure that all deoptimizations of "this" are applied to the
  6325. // constructed entity.
  6326. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  6327. }
  6328. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6329. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6330. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  6331. // args[0] is the "this" argument
  6332. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  6333. }
  6334. }
  6335. hasEffects(context) {
  6336. if (this.annotationNoSideEffects) {
  6337. return false;
  6338. }
  6339. return !!this.id?.hasEffects(context);
  6340. }
  6341. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6342. if (this.annotationNoSideEffects &&
  6343. path.length === 0 &&
  6344. interaction.type === INTERACTION_CALLED) {
  6345. return false;
  6346. }
  6347. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  6348. return true;
  6349. }
  6350. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  6351. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  6352. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  6353. const { brokenFlow, ignore, replacedVariableInits } = context;
  6354. context.ignore = {
  6355. breaks: false,
  6356. continues: false,
  6357. labels: new Set(),
  6358. returnYield: true,
  6359. this: interaction.withNew
  6360. };
  6361. if (this.body.hasEffects(context)) {
  6362. this.hasCachedEffects = true;
  6363. return true;
  6364. }
  6365. context.brokenFlow = brokenFlow;
  6366. if (thisInit) {
  6367. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  6368. }
  6369. else {
  6370. replacedVariableInits.delete(this.scope.thisVariable);
  6371. }
  6372. context.ignore = ignore;
  6373. }
  6374. return false;
  6375. }
  6376. include(context, includeChildrenRecursively) {
  6377. super.include(context, includeChildrenRecursively);
  6378. this.id?.include(context, includeChildrenRecursively);
  6379. const hasArguments = this.scope.argumentsVariable.included;
  6380. for (const parameter of this.params) {
  6381. if (!(parameter instanceof Identifier) || hasArguments) {
  6382. parameter.include(context, includeChildrenRecursively);
  6383. }
  6384. }
  6385. }
  6386. includeNode(context) {
  6387. this.included = true;
  6388. const hasArguments = this.scope.argumentsVariable.included;
  6389. for (const parameter of this.params) {
  6390. if (!(parameter instanceof Identifier) || hasArguments) {
  6391. parameter.includePath(UNKNOWN_PATH, context);
  6392. }
  6393. }
  6394. }
  6395. initialise() {
  6396. super.initialise();
  6397. this.id?.declare('function', EMPTY_PATH, this);
  6398. }
  6399. getObjectEntity() {
  6400. if (this.objectEntity !== null) {
  6401. return this.objectEntity;
  6402. }
  6403. return (this.objectEntity = new ObjectEntity([
  6404. {
  6405. key: 'prototype',
  6406. kind: 'init',
  6407. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  6408. }
  6409. ], OBJECT_PROTOTYPE));
  6410. }
  6411. }
  6412. class FunctionDeclaration extends FunctionNode {
  6413. initialise() {
  6414. super.initialise();
  6415. if (this.id !== null) {
  6416. this.id.variable.isId = true;
  6417. }
  6418. }
  6419. onlyFunctionCallUsed() {
  6420. // call super.onlyFunctionCallUsed for export default anonymous function
  6421. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  6422. }
  6423. parseNode(esTreeNode) {
  6424. if (esTreeNode.id !== null) {
  6425. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  6426. }
  6427. return super.parseNode(esTreeNode);
  6428. }
  6429. }
  6430. // The header ends at the first non-white-space after "default"
  6431. function getDeclarationStart(code, start) {
  6432. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  6433. }
  6434. function getFunctionIdInsertPosition(code, start) {
  6435. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  6436. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  6437. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  6438. if (generatorStarPos === -1) {
  6439. return declarationEnd;
  6440. }
  6441. return declarationEnd + generatorStarPos + 1;
  6442. }
  6443. class ExportDefaultDeclaration extends NodeBase {
  6444. include(context, includeChildrenRecursively) {
  6445. this.included = true;
  6446. this.declaration.include(context, includeChildrenRecursively);
  6447. if (includeChildrenRecursively) {
  6448. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  6449. }
  6450. }
  6451. includePath(path, context) {
  6452. this.included = true;
  6453. this.declaration.includePath(path, context);
  6454. }
  6455. initialise() {
  6456. super.initialise();
  6457. const declaration = this.declaration;
  6458. this.declarationName =
  6459. (declaration.id && declaration.id.name) || this.declaration.name;
  6460. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  6461. this.scope.context.addExport(this);
  6462. }
  6463. removeAnnotations(code) {
  6464. this.declaration.removeAnnotations(code);
  6465. }
  6466. render(code, options, nodeRenderOptions) {
  6467. const { start, end } = nodeRenderOptions;
  6468. const declarationStart = getDeclarationStart(code.original, this.start);
  6469. if (this.declaration instanceof FunctionDeclaration) {
  6470. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6471. ? getFunctionIdInsertPosition(code.original, declarationStart)
  6472. : null, options);
  6473. }
  6474. else if (this.declaration instanceof ClassDeclaration) {
  6475. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6476. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  6477. : null, options);
  6478. }
  6479. else if (this.variable.getOriginalVariable() !== this.variable) {
  6480. // Remove altogether to prevent re-declaring the same variable
  6481. treeshakeNode(this, code, start, end);
  6482. return;
  6483. }
  6484. else if (this.variable.included) {
  6485. this.renderVariableDeclaration(code, declarationStart, options);
  6486. }
  6487. else {
  6488. code.remove(this.start, declarationStart);
  6489. this.declaration.render(code, options, {
  6490. renderedSurroundingElement: ExpressionStatement$1
  6491. });
  6492. if (code.original[this.end - 1] !== ';') {
  6493. code.appendLeft(this.end, ';');
  6494. }
  6495. return;
  6496. }
  6497. this.declaration.render(code, options);
  6498. }
  6499. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  6500. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  6501. const name = this.variable.getName(getPropertyAccess);
  6502. // Remove `export default`
  6503. code.remove(this.start, declarationStart);
  6504. if (idInsertPosition !== null) {
  6505. code.appendLeft(idInsertPosition, ` ${name}`);
  6506. }
  6507. if (format === 'system' &&
  6508. this.declaration instanceof ClassDeclaration &&
  6509. exportNamesByVariable.has(this.variable)) {
  6510. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  6511. }
  6512. }
  6513. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  6514. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  6515. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  6516. if (systemExportNames) {
  6517. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  6518. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  6519. }
  6520. else {
  6521. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  6522. if (!hasTrailingSemicolon) {
  6523. code.appendLeft(this.end, ';');
  6524. }
  6525. }
  6526. }
  6527. }
  6528. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  6529. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6530. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  6531. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  6532. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  6533. const backSlashRegEx = /\\/g;
  6534. function escapeId(id) {
  6535. if (!needsEscapeRegEx.test(id))
  6536. return id;
  6537. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  6538. }
  6539. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  6540. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  6541. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  6542. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  6543. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  6544. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  6545. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  6546. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  6547. const defaultInteropHelpersByInteropType = {
  6548. auto: INTEROP_DEFAULT_VARIABLE,
  6549. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  6550. default: null,
  6551. defaultOnly: null,
  6552. esModule: null
  6553. };
  6554. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  6555. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  6556. const namespaceInteropHelpersByInteropType = {
  6557. auto: INTEROP_NAMESPACE_VARIABLE,
  6558. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  6559. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  6560. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  6561. esModule: null
  6562. };
  6563. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  6564. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  6565. const usedHelpers = new Set(additionalHelpers);
  6566. for (const variable of HELPER_NAMES) {
  6567. if (accessedGlobals.has(variable)) {
  6568. usedHelpers.add(variable);
  6569. }
  6570. }
  6571. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  6572. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  6573. : '').join('');
  6574. };
  6575. const HELPER_GENERATORS = {
  6576. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  6577. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  6578. },
  6579. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  6580. const { _, getDirectReturnFunction, n } = snippets;
  6581. const [left, right] = getDirectReturnFunction(['e'], {
  6582. functionReturn: true,
  6583. lineBreakIndent: null,
  6584. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  6585. });
  6586. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  6587. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6588. },
  6589. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  6590. const { _, getDirectReturnFunction, n } = snippets;
  6591. const [left, right] = getDirectReturnFunction(['e'], {
  6592. functionReturn: true,
  6593. lineBreakIndent: null,
  6594. name: INTEROP_DEFAULT_VARIABLE
  6595. });
  6596. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  6597. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6598. },
  6599. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6600. const { _, getDirectReturnFunction, n } = snippets;
  6601. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6602. const [left, right] = getDirectReturnFunction(['e'], {
  6603. functionReturn: true,
  6604. lineBreakIndent: null,
  6605. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  6606. });
  6607. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6608. }
  6609. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  6610. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  6611. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6612. `}${n}${n}`);
  6613. },
  6614. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  6615. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  6616. const [left, right] = getDirectReturnFunction(['e'], {
  6617. functionReturn: true,
  6618. lineBreakIndent: null,
  6619. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  6620. });
  6621. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  6622. [null, `__proto__:${_}null`],
  6623. ['default', 'e']
  6624. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  6625. },
  6626. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6627. const { _, n } = snippets;
  6628. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  6629. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6630. `}${n}${n}`);
  6631. },
  6632. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6633. const { _, getDirectReturnFunction, n } = snippets;
  6634. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6635. const [left, right] = getDirectReturnFunction(['e'], {
  6636. functionReturn: true,
  6637. lineBreakIndent: null,
  6638. name: INTEROP_NAMESPACE_VARIABLE
  6639. });
  6640. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6641. }
  6642. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  6643. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  6644. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6645. `}${n}${n}`);
  6646. },
  6647. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6648. const { _, cnst, n } = snippets;
  6649. const useForEach = cnst === 'var' && liveBindings;
  6650. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  6651. `${t}${loopOverNamespaces(`{${n}` +
  6652. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  6653. (liveBindings
  6654. ? useForEach
  6655. ? copyOwnPropertyLiveBinding
  6656. : copyPropertyLiveBinding
  6657. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  6658. `${t}${t}${t}}${n}` +
  6659. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  6660. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  6661. `}${n}${n}`);
  6662. }
  6663. };
  6664. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  6665. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  6666. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  6667. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  6668. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  6669. const copyProperty = `{${n}` +
  6670. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  6671. `${index}${t}}`;
  6672. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  6673. `${index}if${_}(e)${_}{${n}` +
  6674. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  6675. `${index}}${n}` +
  6676. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  6677. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  6678. };
  6679. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  6680. ? `for${_}(${cnst} k in e)${_}${body}`
  6681. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6682. isAsync: false,
  6683. name: null
  6684. })}${body})${s}`;
  6685. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  6686. if (useForEach) {
  6687. const [left, right] = getDirectReturnFunction(['e'], {
  6688. functionReturn: false,
  6689. lineBreakIndent: { base: t, t },
  6690. name: null
  6691. });
  6692. return (`m.forEach(${left}` +
  6693. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6694. isAsync: false,
  6695. name: null
  6696. })}${body})${right});`);
  6697. }
  6698. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  6699. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  6700. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  6701. };
  6702. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  6703. const { _, n } = snippets;
  6704. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  6705. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  6706. `${index}}${n}`);
  6707. };
  6708. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6709. const [left, right] = getDirectReturnFunction([], {
  6710. functionReturn: true,
  6711. lineBreakIndent: null,
  6712. name: null
  6713. });
  6714. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6715. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6716. `${index}${t}enumerable:${_}true,${n}` +
  6717. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  6718. `${index}});${n}`);
  6719. };
  6720. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6721. const [left, right] = getDirectReturnFunction([], {
  6722. functionReturn: true,
  6723. lineBreakIndent: null,
  6724. name: null
  6725. });
  6726. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6727. `${index}if${_}(d)${_}{${n}` +
  6728. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6729. `${index}${t}${t}enumerable:${_}true,${n}` +
  6730. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  6731. `${index}${t}});${n}` +
  6732. `${index}}${n}`);
  6733. };
  6734. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  6735. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  6736. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  6737. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  6738. : fragment;
  6739. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  6740. function getToStringTagValue(getObject) {
  6741. return getObject([['value', "'Module'"]], {
  6742. lineBreakIndent: null
  6743. });
  6744. }
  6745. class Literal extends NodeBase {
  6746. deoptimizeArgumentsOnInteractionAtPath() { }
  6747. getLiteralValueAtPath(path) {
  6748. if (path.length > 0 ||
  6749. // unknown literals can also be null but do not start with an "n"
  6750. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  6751. typeof this.value === 'bigint' ||
  6752. // to support shims for regular expressions
  6753. this.scope.context.code.charCodeAt(this.start) === 47) {
  6754. return UnknownValue;
  6755. }
  6756. return this.value;
  6757. }
  6758. getReturnExpressionWhenCalledAtPath(path) {
  6759. if (path.length !== 1)
  6760. return UNKNOWN_RETURN_EXPRESSION;
  6761. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  6762. }
  6763. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6764. switch (interaction.type) {
  6765. case INTERACTION_ACCESSED: {
  6766. return path.length > (this.value === null ? 0 : 1);
  6767. }
  6768. case INTERACTION_ASSIGNED: {
  6769. return true;
  6770. }
  6771. case INTERACTION_CALLED: {
  6772. if (this.included &&
  6773. this.value instanceof RegExp &&
  6774. (this.value.global || this.value.sticky)) {
  6775. return true;
  6776. }
  6777. return (path.length !== 1 ||
  6778. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  6779. }
  6780. }
  6781. }
  6782. initialise() {
  6783. super.initialise();
  6784. this.members = getLiteralMembersForValue(this.value);
  6785. }
  6786. parseNode(esTreeNode) {
  6787. this.value = esTreeNode.value;
  6788. this.regex = esTreeNode.regex;
  6789. return super.parseNode(esTreeNode);
  6790. }
  6791. render(code) {
  6792. if (typeof this.value === 'string') {
  6793. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6794. }
  6795. }
  6796. }
  6797. Literal.prototype.includeNode = onlyIncludeSelf;
  6798. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  6799. if ('getLiteralValueAtPathAsChainElement' in object) {
  6800. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  6801. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  6802. return IS_SKIPPED_CHAIN;
  6803. }
  6804. }
  6805. else if (element.optional &&
  6806. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  6807. return IS_SKIPPED_CHAIN;
  6808. }
  6809. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  6810. }
  6811. function getResolvablePropertyKey(memberExpression) {
  6812. return memberExpression.computed
  6813. ? getResolvableComputedPropertyKey(memberExpression.property)
  6814. : memberExpression.property.name;
  6815. }
  6816. function getResolvableComputedPropertyKey(propertyKey) {
  6817. if (propertyKey instanceof Literal) {
  6818. return String(propertyKey.value);
  6819. }
  6820. return null;
  6821. }
  6822. function getPathIfNotComputed(memberExpression) {
  6823. const nextPathKey = memberExpression.propertyKey;
  6824. const object = memberExpression.object;
  6825. if (typeof nextPathKey === 'string') {
  6826. if (object instanceof Identifier) {
  6827. return [
  6828. { key: object.name, pos: object.start },
  6829. { key: nextPathKey, pos: memberExpression.property.start }
  6830. ];
  6831. }
  6832. if (object instanceof MemberExpression) {
  6833. const parentPath = getPathIfNotComputed(object);
  6834. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6835. }
  6836. }
  6837. return null;
  6838. }
  6839. function getStringFromPath(path) {
  6840. let pathString = path[0].key;
  6841. for (let index = 1; index < path.length; index++) {
  6842. pathString += '.' + path[index].key;
  6843. }
  6844. return pathString;
  6845. }
  6846. class MemberExpression extends NodeBase {
  6847. constructor() {
  6848. super(...arguments);
  6849. this.variable = null;
  6850. this.expressionsToBeDeoptimized = [];
  6851. }
  6852. get computed() {
  6853. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  6854. }
  6855. set computed(value) {
  6856. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  6857. }
  6858. get optional() {
  6859. return isFlagSet(this.flags, 128 /* Flag.optional */);
  6860. }
  6861. set optional(value) {
  6862. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  6863. }
  6864. get assignmentDeoptimized() {
  6865. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  6866. }
  6867. set assignmentDeoptimized(value) {
  6868. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  6869. }
  6870. get bound() {
  6871. return isFlagSet(this.flags, 32 /* Flag.bound */);
  6872. }
  6873. set bound(value) {
  6874. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  6875. }
  6876. get isUndefined() {
  6877. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  6878. }
  6879. set isUndefined(value) {
  6880. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  6881. }
  6882. bind() {
  6883. this.bound = true;
  6884. const path = getPathIfNotComputed(this);
  6885. const baseVariable = path && this.scope.findVariable(path[0].key);
  6886. if (baseVariable?.isNamespace) {
  6887. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  6888. if (!resolvedVariable) {
  6889. super.bind();
  6890. }
  6891. else if (resolvedVariable === 'undefined') {
  6892. this.isUndefined = true;
  6893. }
  6894. else {
  6895. this.variable = resolvedVariable;
  6896. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6897. }
  6898. }
  6899. else {
  6900. super.bind();
  6901. }
  6902. }
  6903. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6904. if (this.variable) {
  6905. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6906. }
  6907. else if (!this.isUndefined) {
  6908. if (path.length < MAX_PATH_DEPTH) {
  6909. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  6910. }
  6911. else {
  6912. deoptimizeInteraction(interaction);
  6913. }
  6914. }
  6915. }
  6916. deoptimizeAssignment(destructuredInitPath, init) {
  6917. this.deoptimizePath(EMPTY_PATH);
  6918. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  6919. }
  6920. deoptimizeCache() {
  6921. if (this.propertyKey === this.dynamicPropertyKey)
  6922. return;
  6923. const { expressionsToBeDeoptimized, object } = this;
  6924. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  6925. this.dynamicPropertyKey = this.propertyKey;
  6926. object.deoptimizePath(UNKNOWN_PATH);
  6927. if (this.included) {
  6928. object.includePath(UNKNOWN_PATH, createInclusionContext());
  6929. }
  6930. for (const expression of expressionsToBeDeoptimized) {
  6931. expression.deoptimizeCache();
  6932. }
  6933. }
  6934. deoptimizePath(path) {
  6935. if (path.length === 0)
  6936. this.disallowNamespaceReassignment();
  6937. if (this.variable) {
  6938. this.variable.deoptimizePath(path);
  6939. }
  6940. else if (!this.isUndefined) {
  6941. const { propertyKey } = this;
  6942. this.object.deoptimizePath([
  6943. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  6944. ...(path.length < MAX_PATH_DEPTH
  6945. ? path
  6946. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  6947. ]);
  6948. }
  6949. }
  6950. getLiteralValueAtPath(path, recursionTracker, origin) {
  6951. if (this.variable) {
  6952. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6953. }
  6954. if (this.isUndefined) {
  6955. return undefined;
  6956. }
  6957. const propertyKey = this.getDynamicPropertyKey();
  6958. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  6959. if (propertyKey !== this.propertyKey)
  6960. this.expressionsToBeDeoptimized.push(origin);
  6961. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  6962. }
  6963. return UnknownValue;
  6964. }
  6965. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  6966. if (this.variable) {
  6967. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6968. }
  6969. if (this.isUndefined) {
  6970. return undefined;
  6971. }
  6972. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  6973. }
  6974. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6975. if (this.variable) {
  6976. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6977. }
  6978. if (this.isUndefined) {
  6979. return [UNDEFINED_EXPRESSION, false];
  6980. }
  6981. const propertyKey = this.getDynamicPropertyKey();
  6982. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  6983. if (propertyKey !== this.propertyKey)
  6984. this.expressionsToBeDeoptimized.push(origin);
  6985. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  6986. }
  6987. return UNKNOWN_RETURN_EXPRESSION;
  6988. }
  6989. hasEffects(context) {
  6990. if (!this.deoptimized)
  6991. this.applyDeoptimizations();
  6992. return (this.property.hasEffects(context) ||
  6993. this.object.hasEffects(context) ||
  6994. this.hasAccessEffect(context));
  6995. }
  6996. hasEffectsAsChainElement(context) {
  6997. if (this.variable || this.isUndefined)
  6998. return this.hasEffects(context);
  6999. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  7000. ? this.object.hasEffectsAsChainElement(context)
  7001. : this.object.hasEffects(context);
  7002. if (objectHasEffects === IS_SKIPPED_CHAIN)
  7003. return IS_SKIPPED_CHAIN;
  7004. if (this.optional &&
  7005. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  7006. return objectHasEffects || IS_SKIPPED_CHAIN;
  7007. }
  7008. // We only apply deoptimizations lazily once we know we are not skipping
  7009. if (!this.deoptimized)
  7010. this.applyDeoptimizations();
  7011. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  7012. }
  7013. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7014. if (checkAccess && !this.deoptimized)
  7015. this.applyDeoptimizations();
  7016. if (!this.assignmentDeoptimized)
  7017. this.applyAssignmentDeoptimization();
  7018. return (this.property.hasEffects(context) ||
  7019. this.object.hasEffects(context) ||
  7020. (checkAccess && this.hasAccessEffect(context)) ||
  7021. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7022. }
  7023. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7024. if (this.variable) {
  7025. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7026. }
  7027. if (this.isUndefined) {
  7028. return true;
  7029. }
  7030. if (path.length < MAX_PATH_DEPTH) {
  7031. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  7032. }
  7033. return true;
  7034. }
  7035. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  7036. return (destructuredInitPath.length > 0 &&
  7037. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7038. }
  7039. include(context, includeChildrenRecursively) {
  7040. if (!this.included)
  7041. this.includeNode(context);
  7042. this.object.include(context, includeChildrenRecursively);
  7043. this.property.include(context, includeChildrenRecursively);
  7044. }
  7045. includeNode(context) {
  7046. this.included = true;
  7047. if (!this.deoptimized)
  7048. this.applyDeoptimizations();
  7049. if (this.variable) {
  7050. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7051. }
  7052. else if (!this.isUndefined) {
  7053. this.object.includePath([this.propertyKey], context);
  7054. }
  7055. }
  7056. includeNodeAsAssignmentTarget(context) {
  7057. this.included = true;
  7058. if (!this.assignmentDeoptimized)
  7059. this.applyAssignmentDeoptimization();
  7060. if (this.variable) {
  7061. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7062. }
  7063. else if (!this.isUndefined) {
  7064. this.object.includePath([this.propertyKey], context);
  7065. }
  7066. }
  7067. includePath(path, context) {
  7068. if (!this.included)
  7069. this.includeNode(context);
  7070. if (this.variable) {
  7071. this.variable?.includePath(path, context);
  7072. }
  7073. else if (!this.isUndefined) {
  7074. this.object.includePath([
  7075. this.propertyKey,
  7076. ...(path.length < MAX_PATH_DEPTH
  7077. ? path
  7078. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  7079. ], context);
  7080. }
  7081. }
  7082. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7083. if (!this.included)
  7084. this.includeNodeAsAssignmentTarget(context);
  7085. if (deoptimizeAccess && !this.deoptimized)
  7086. this.applyDeoptimizations();
  7087. this.object.include(context, includeChildrenRecursively);
  7088. this.property.include(context, includeChildrenRecursively);
  7089. }
  7090. includeCallArguments(interaction, context) {
  7091. if (this.variable) {
  7092. this.variable.includeCallArguments(interaction, context);
  7093. }
  7094. else {
  7095. includeInteraction(interaction, context);
  7096. }
  7097. }
  7098. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  7099. if ((this.included ||=
  7100. destructuredInitPath.length > 0 &&
  7101. !context.brokenFlow &&
  7102. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext()))) {
  7103. init.include(context, false);
  7104. return true;
  7105. }
  7106. return false;
  7107. }
  7108. initialise() {
  7109. super.initialise();
  7110. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  7111. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  7112. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  7113. }
  7114. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  7115. if (this.variable || this.isUndefined) {
  7116. const { snippets: { getPropertyAccess } } = options;
  7117. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  7118. if (renderedParentType && isCalleeOfRenderedParent)
  7119. replacement = '0, ' + replacement;
  7120. code.overwrite(this.start, this.end, replacement, {
  7121. contentOnly: true,
  7122. storeName: true
  7123. });
  7124. }
  7125. else {
  7126. if (renderedParentType && isCalleeOfRenderedParent) {
  7127. code.appendRight(this.start, '0, ');
  7128. }
  7129. this.object.render(code, options, { renderedSurroundingElement });
  7130. this.property.render(code, options);
  7131. }
  7132. }
  7133. setAssignedValue(value) {
  7134. this.assignmentInteraction = {
  7135. args: [this.object, value],
  7136. type: INTERACTION_ASSIGNED
  7137. };
  7138. }
  7139. applyDeoptimizations() {
  7140. this.deoptimized = true;
  7141. const { propertyReadSideEffects } = this.scope.context.options
  7142. .treeshake;
  7143. if (
  7144. // Namespaces are not bound and should not be deoptimized
  7145. this.bound &&
  7146. propertyReadSideEffects &&
  7147. !(this.variable || this.isUndefined)) {
  7148. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7149. this.scope.context.requestTreeshakingPass();
  7150. }
  7151. if (this.variable) {
  7152. this.variable.addUsedPlace(this);
  7153. this.scope.context.requestTreeshakingPass();
  7154. }
  7155. }
  7156. applyAssignmentDeoptimization() {
  7157. this.assignmentDeoptimized = true;
  7158. const { propertyReadSideEffects } = this.scope.context.options
  7159. .treeshake;
  7160. if (
  7161. // Namespaces are not bound and should not be deoptimized
  7162. this.bound &&
  7163. propertyReadSideEffects &&
  7164. !(this.variable || this.isUndefined)) {
  7165. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7166. this.scope.context.requestTreeshakingPass();
  7167. }
  7168. }
  7169. disallowNamespaceReassignment() {
  7170. if (this.object instanceof Identifier) {
  7171. const variable = this.scope.findVariable(this.object.name);
  7172. if (variable.isNamespace) {
  7173. if (this.variable) {
  7174. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  7175. }
  7176. this.scope.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  7177. }
  7178. }
  7179. }
  7180. getDynamicPropertyKey() {
  7181. if (this.dynamicPropertyKey === null) {
  7182. this.dynamicPropertyKey = this.propertyKey;
  7183. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7184. return (this.dynamicPropertyKey =
  7185. value === SymbolToStringTag
  7186. ? value
  7187. : typeof value === 'symbol'
  7188. ? UnknownKey
  7189. : String(value));
  7190. }
  7191. return this.dynamicPropertyKey;
  7192. }
  7193. hasAccessEffect(context) {
  7194. const { propertyReadSideEffects } = this.scope.context.options
  7195. .treeshake;
  7196. return (!(this.variable || this.isUndefined) &&
  7197. propertyReadSideEffects &&
  7198. (propertyReadSideEffects === 'always' ||
  7199. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  7200. }
  7201. }
  7202. function resolveNamespaceVariables(baseVariable, path, astContext) {
  7203. if (path.length === 0)
  7204. return baseVariable;
  7205. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  7206. return null;
  7207. const exportName = path[0].key;
  7208. const variable = baseVariable.context.traceExport(exportName);
  7209. if (!variable) {
  7210. if (path.length === 1) {
  7211. const fileName = baseVariable.context.fileName;
  7212. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  7213. return 'undefined';
  7214. }
  7215. return null;
  7216. }
  7217. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  7218. }
  7219. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7220. const IMPORT = 'import';
  7221. class MetaProperty extends NodeBase {
  7222. constructor() {
  7223. super(...arguments);
  7224. this.metaProperty = null;
  7225. this.preliminaryChunkId = null;
  7226. this.referenceId = null;
  7227. }
  7228. getReferencedFileName(outputPluginDriver) {
  7229. const { meta: { name }, metaProperty } = this;
  7230. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  7231. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  7232. }
  7233. return null;
  7234. }
  7235. hasEffects() {
  7236. return false;
  7237. }
  7238. hasEffectsOnInteractionAtPath(path, { type }) {
  7239. return path.length > 1 || type !== INTERACTION_ACCESSED;
  7240. }
  7241. include() {
  7242. if (!this.included)
  7243. this.includeNode();
  7244. }
  7245. includeNode() {
  7246. this.included = true;
  7247. if (this.meta.name === IMPORT) {
  7248. this.scope.context.addImportMeta(this);
  7249. const parent = this.parent;
  7250. const metaProperty = (this.metaProperty =
  7251. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7252. ? parent.propertyKey
  7253. : null);
  7254. if (metaProperty?.startsWith(FILE_PREFIX)) {
  7255. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  7256. }
  7257. }
  7258. }
  7259. render(code, renderOptions) {
  7260. const { format, pluginDriver, snippets } = renderOptions;
  7261. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  7262. const { id: moduleId } = module;
  7263. if (name !== IMPORT)
  7264. return;
  7265. const chunkId = preliminaryChunkId;
  7266. if (referenceId) {
  7267. const fileName = pluginDriver.getFileName(referenceId);
  7268. const relativePath = normalize(relative(dirname(chunkId), fileName));
  7269. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  7270. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  7271. ]) || relativeUrlMechanisms[format](relativePath);
  7272. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7273. return;
  7274. }
  7275. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  7276. metaProperty,
  7277. { chunkId, format, moduleId }
  7278. ]);
  7279. if (!replacement) {
  7280. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  7281. renderOptions.accessedDocumentCurrentScript ||=
  7282. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  7283. }
  7284. if (typeof replacement === 'string') {
  7285. if (parent instanceof MemberExpression) {
  7286. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7287. }
  7288. else {
  7289. code.overwrite(start, end, replacement, { contentOnly: true });
  7290. }
  7291. }
  7292. }
  7293. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  7294. this.preliminaryChunkId = preliminaryChunkId;
  7295. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  7296. if (accessedGlobals.length > 0) {
  7297. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7298. }
  7299. }
  7300. }
  7301. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  7302. const accessedMetaUrlGlobals = {
  7303. amd: ['document', 'module', 'URL'],
  7304. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7305. es: [],
  7306. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7307. system: ['module'],
  7308. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  7309. };
  7310. const accessedFileUrlGlobals = {
  7311. amd: ['document', 'require', 'URL'],
  7312. cjs: ['document', 'require', 'URL'],
  7313. es: [],
  7314. iife: ['document', 'URL'],
  7315. system: ['module', 'URL'],
  7316. umd: ['document', 'require', 'URL']
  7317. };
  7318. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  7319. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
  7320. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  7321. const urlMechanism = getUrl(chunkId);
  7322. return property === null
  7323. ? `({ url: ${urlMechanism} })`
  7324. : property === 'url'
  7325. ? urlMechanism
  7326. : 'undefined';
  7327. };
  7328. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  7329. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  7330. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(${DOCUMENT_CURRENT_SCRIPT} && ${DOCUMENT_CURRENT_SCRIPT}.tagName.toUpperCase() === 'SCRIPT' && ${DOCUMENT_CURRENT_SCRIPT}.src || new URL('${escapeId(chunkId)}', document.baseURI).href)`;
  7331. const relativeUrlMechanisms = {
  7332. amd: relativePath => {
  7333. if (relativePath[0] !== '.')
  7334. relativePath = './' + relativePath;
  7335. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
  7336. },
  7337. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  7338. es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
  7339. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  7340. system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
  7341. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  7342. };
  7343. const importMetaMechanisms = {
  7344. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  7345. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  7346. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7347. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  7348. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  7349. };
  7350. class UndefinedVariable extends Variable {
  7351. constructor() {
  7352. super('undefined');
  7353. }
  7354. getLiteralValueAtPath() {
  7355. return undefined;
  7356. }
  7357. }
  7358. class ExportDefaultVariable extends LocalVariable {
  7359. constructor(name, exportDefaultDeclaration, context) {
  7360. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  7361. this.hasId = false;
  7362. this.originalId = null;
  7363. this.originalVariable = null;
  7364. const declaration = exportDefaultDeclaration.declaration;
  7365. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  7366. declaration.id) {
  7367. this.hasId = true;
  7368. this.originalId = declaration.id;
  7369. }
  7370. else if (declaration instanceof Identifier) {
  7371. this.originalId = declaration;
  7372. }
  7373. }
  7374. addReference(identifier) {
  7375. if (!this.hasId) {
  7376. this.name = identifier.name;
  7377. }
  7378. }
  7379. addUsedPlace(usedPlace) {
  7380. const original = this.getOriginalVariable();
  7381. if (original === this) {
  7382. super.addUsedPlace(usedPlace);
  7383. }
  7384. else {
  7385. original.addUsedPlace(usedPlace);
  7386. }
  7387. }
  7388. forbidName(name) {
  7389. const original = this.getOriginalVariable();
  7390. if (original === this) {
  7391. super.forbidName(name);
  7392. }
  7393. else {
  7394. original.forbidName(name);
  7395. }
  7396. }
  7397. getAssignedVariableName() {
  7398. return (this.originalId && this.originalId.name) || null;
  7399. }
  7400. getBaseVariableName() {
  7401. const original = this.getOriginalVariable();
  7402. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  7403. }
  7404. getDirectOriginalVariable() {
  7405. return this.originalId &&
  7406. (this.hasId ||
  7407. !(this.originalId.isPossibleTDZ() ||
  7408. this.originalId.variable.isReassigned ||
  7409. this.originalId.variable instanceof UndefinedVariable ||
  7410. // this avoids a circular dependency
  7411. 'syntheticNamespace' in this.originalId.variable))
  7412. ? this.originalId.variable
  7413. : null;
  7414. }
  7415. getName(getPropertyAccess) {
  7416. const original = this.getOriginalVariable();
  7417. return original === this
  7418. ? super.getName(getPropertyAccess)
  7419. : original.getName(getPropertyAccess);
  7420. }
  7421. getOriginalVariable() {
  7422. if (this.originalVariable)
  7423. return this.originalVariable;
  7424. // eslint-disable-next-line @typescript-eslint/no-this-alias
  7425. let original = this;
  7426. let currentVariable;
  7427. const checkedVariables = new Set();
  7428. do {
  7429. checkedVariables.add(original);
  7430. currentVariable = original;
  7431. original = currentVariable.getDirectOriginalVariable();
  7432. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  7433. return (this.originalVariable = original || currentVariable);
  7434. }
  7435. }
  7436. class NamespaceVariable extends Variable {
  7437. constructor(context) {
  7438. super(context.getModuleName());
  7439. this.memberVariables = null;
  7440. this.mergedNamespaces = [];
  7441. this.referencedEarly = false;
  7442. this.references = [];
  7443. this.context = context;
  7444. this.module = context.module;
  7445. }
  7446. addReference(identifier) {
  7447. this.references.push(identifier);
  7448. this.name = identifier.name;
  7449. }
  7450. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7451. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  7452. const key = path[0];
  7453. if (typeof key === 'string') {
  7454. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  7455. }
  7456. else {
  7457. deoptimizeInteraction(interaction);
  7458. }
  7459. }
  7460. }
  7461. deoptimizePath(path) {
  7462. if (path.length > 1) {
  7463. const key = path[0];
  7464. if (typeof key === 'string') {
  7465. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  7466. }
  7467. }
  7468. }
  7469. getLiteralValueAtPath(path) {
  7470. if (path[0] === SymbolToStringTag) {
  7471. return 'Module';
  7472. }
  7473. return UnknownValue;
  7474. }
  7475. getMemberVariables() {
  7476. if (this.memberVariables) {
  7477. return this.memberVariables;
  7478. }
  7479. const memberVariables = Object.create(null);
  7480. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  7481. for (const name of sortedExports) {
  7482. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  7483. const exportedVariable = this.context.traceExport(name);
  7484. if (exportedVariable) {
  7485. memberVariables[name] = exportedVariable;
  7486. }
  7487. }
  7488. }
  7489. return (this.memberVariables = memberVariables);
  7490. }
  7491. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7492. const { type } = interaction;
  7493. if (path.length === 0) {
  7494. // This can only be a call anyway
  7495. return true;
  7496. }
  7497. if (path.length === 1 && type !== INTERACTION_CALLED) {
  7498. return type === INTERACTION_ASSIGNED;
  7499. }
  7500. const key = path[0];
  7501. if (typeof key !== 'string') {
  7502. return true;
  7503. }
  7504. const memberVariable = this.getMemberVariables()[key];
  7505. return (!memberVariable ||
  7506. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  7507. }
  7508. includePath(path, context) {
  7509. super.includePath(path, context);
  7510. this.context.includeAllExports();
  7511. }
  7512. prepare(accessedGlobalsByScope) {
  7513. if (this.mergedNamespaces.length > 0) {
  7514. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  7515. }
  7516. }
  7517. renderBlock(options) {
  7518. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  7519. const memberVariables = this.getMemberVariables();
  7520. const members = Object.entries(memberVariables)
  7521. .filter(([_, variable]) => variable.included)
  7522. .map(([name, variable]) => {
  7523. if (this.referencedEarly || variable.isReassigned || variable === this) {
  7524. return [
  7525. null,
  7526. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  7527. ];
  7528. }
  7529. return [name, variable.getName(getPropertyAccess)];
  7530. });
  7531. members.unshift([null, `__proto__:${_}null`]);
  7532. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  7533. if (this.mergedNamespaces.length > 0) {
  7534. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  7535. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  7536. }
  7537. else {
  7538. // The helper to merge namespaces will also take care of freezing and toStringTag
  7539. if (symbols) {
  7540. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  7541. }
  7542. if (freeze) {
  7543. output = `/*#__PURE__*/Object.freeze(${output})`;
  7544. }
  7545. }
  7546. const name = this.getName(getPropertyAccess);
  7547. output = `${cnst} ${name}${_}=${_}${output};`;
  7548. if (format === 'system' && exportNamesByVariable.has(this)) {
  7549. output += `${n}${getSystemExportStatement([this], options)};`;
  7550. }
  7551. return output;
  7552. }
  7553. renderFirst() {
  7554. return this.referencedEarly;
  7555. }
  7556. setMergedNamespaces(mergedNamespaces) {
  7557. this.mergedNamespaces = mergedNamespaces;
  7558. const moduleExecIndex = this.context.getModuleExecIndex();
  7559. for (const identifier of this.references) {
  7560. const { context } = identifier.scope;
  7561. if (context.getModuleExecIndex() <= moduleExecIndex) {
  7562. this.referencedEarly = true;
  7563. break;
  7564. }
  7565. }
  7566. }
  7567. }
  7568. NamespaceVariable.prototype.isNamespace = true;
  7569. class SyntheticNamedExportVariable extends Variable {
  7570. constructor(context, name, syntheticNamespace) {
  7571. super(name);
  7572. this.baseVariable = null;
  7573. this.context = context;
  7574. this.module = context.module;
  7575. this.syntheticNamespace = syntheticNamespace;
  7576. }
  7577. getBaseVariable() {
  7578. if (this.baseVariable)
  7579. return this.baseVariable;
  7580. let baseVariable = this.syntheticNamespace;
  7581. while (baseVariable instanceof ExportDefaultVariable ||
  7582. baseVariable instanceof SyntheticNamedExportVariable) {
  7583. if (baseVariable instanceof ExportDefaultVariable) {
  7584. const original = baseVariable.getOriginalVariable();
  7585. if (original === baseVariable)
  7586. break;
  7587. baseVariable = original;
  7588. }
  7589. if (baseVariable instanceof SyntheticNamedExportVariable) {
  7590. baseVariable = baseVariable.syntheticNamespace;
  7591. }
  7592. }
  7593. return (this.baseVariable = baseVariable);
  7594. }
  7595. getBaseVariableName() {
  7596. return this.syntheticNamespace.getBaseVariableName();
  7597. }
  7598. getName(getPropertyAccess) {
  7599. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  7600. }
  7601. includePath(path, context) {
  7602. super.includePath(path, context);
  7603. this.context.includeVariableInModule(this.syntheticNamespace, path, context);
  7604. }
  7605. setRenderNames(baseName, name) {
  7606. super.setRenderNames(baseName, name);
  7607. }
  7608. }
  7609. class ExternalChunk {
  7610. constructor(module, options, inputBase) {
  7611. this.options = options;
  7612. this.inputBase = inputBase;
  7613. this.defaultVariableName = '';
  7614. this.namespaceVariableName = '';
  7615. this.variableName = '';
  7616. this.fileName = null;
  7617. this.importAttributes = null;
  7618. this.id = module.id;
  7619. this.moduleInfo = module.info;
  7620. this.renormalizeRenderPath = module.renormalizeRenderPath;
  7621. this.suggestedVariableName = module.suggestedVariableName;
  7622. }
  7623. getFileName() {
  7624. if (this.fileName) {
  7625. return this.fileName;
  7626. }
  7627. const { paths } = this.options;
  7628. return (this.fileName =
  7629. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  7630. (this.renormalizeRenderPath ? normalize(relative(this.inputBase, this.id)) : this.id));
  7631. }
  7632. getImportAttributes(snippets) {
  7633. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  7634. this.options.externalImportAttributes &&
  7635. this.moduleInfo.attributes, snippets));
  7636. }
  7637. getImportPath(importer) {
  7638. return escapeId(this.renormalizeRenderPath
  7639. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  7640. : this.getFileName());
  7641. }
  7642. }
  7643. function formatAttributes(attributes, { getObject }) {
  7644. if (!attributes) {
  7645. return null;
  7646. }
  7647. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  7648. if (assertionEntries.length > 0) {
  7649. return getObject(assertionEntries, { lineBreakIndent: null });
  7650. }
  7651. return null;
  7652. }
  7653. function removeJsExtension(name) {
  7654. return name.endsWith('.js') ? name.slice(0, -3) : name;
  7655. }
  7656. function getCompleteAmdId(options, chunkId) {
  7657. if (options.autoId) {
  7658. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  7659. }
  7660. return options.id ?? '';
  7661. }
  7662. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  7663. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  7664. if (!namedExportsMode) {
  7665. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  7666. }
  7667. let exportBlock = '';
  7668. if (namedExportsMode) {
  7669. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7670. if (!reexports) {
  7671. continue;
  7672. }
  7673. for (const specifier of reexports) {
  7674. if (specifier.reexported !== '*') {
  7675. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7676. if (exportBlock)
  7677. exportBlock += n;
  7678. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  7679. const [left, right] = getDirectReturnFunction([], {
  7680. functionReturn: true,
  7681. lineBreakIndent: null,
  7682. name: null
  7683. });
  7684. exportBlock +=
  7685. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  7686. `${t}enumerable:${_}true,${n}` +
  7687. `${t}get:${_}${left}${importName}${right}${n}});`;
  7688. }
  7689. else if (specifier.reexported === '__proto__') {
  7690. exportBlock +=
  7691. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7692. `${t}enumerable:${_}true,${n}` +
  7693. `${t}value:${_}${importName}${n}});`;
  7694. }
  7695. else {
  7696. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  7697. }
  7698. }
  7699. }
  7700. }
  7701. }
  7702. for (const { exported, local } of exports) {
  7703. const lhs = `exports${getPropertyAccess(exported)}`;
  7704. const rhs = local;
  7705. if (lhs !== rhs) {
  7706. if (exportBlock)
  7707. exportBlock += n;
  7708. exportBlock +=
  7709. exported === '__proto__'
  7710. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7711. `${t}enumerable:${_}true,${n}` +
  7712. `${t}value:${_}${rhs}${n}});`
  7713. : `${lhs}${_}=${_}${rhs};`;
  7714. }
  7715. }
  7716. if (namedExportsMode) {
  7717. for (const { name, reexports } of dependencies) {
  7718. if (!reexports) {
  7719. continue;
  7720. }
  7721. for (const specifier of reexports) {
  7722. if (specifier.reexported === '*') {
  7723. if (exportBlock)
  7724. exportBlock += n;
  7725. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  7726. const protoString = "'__proto__'";
  7727. exportBlock +=
  7728. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  7729. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  7730. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  7731. `${t}${t}enumerable:${_}true,${n}` +
  7732. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  7733. `${t}});${n}${n}`;
  7734. }
  7735. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  7736. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  7737. isAsync: false,
  7738. name: null
  7739. })}${copyPropertyIfNecessary});`;
  7740. }
  7741. }
  7742. }
  7743. }
  7744. if (exportBlock) {
  7745. return `${n}${n}${exportBlock}`;
  7746. }
  7747. return '';
  7748. }
  7749. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  7750. if (exports.length > 0) {
  7751. return exports[0].local;
  7752. }
  7753. else {
  7754. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7755. if (reexports) {
  7756. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7757. }
  7758. }
  7759. }
  7760. }
  7761. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  7762. if (imported === 'default') {
  7763. if (!isChunk) {
  7764. const moduleInterop = interop(moduleId);
  7765. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  7766. ? defaultVariableName
  7767. : moduleVariableName;
  7768. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  7769. ? `${variableName}${getPropertyAccess('default')}`
  7770. : variableName;
  7771. }
  7772. return depNamedExportsMode
  7773. ? `${moduleVariableName}${getPropertyAccess('default')}`
  7774. : moduleVariableName;
  7775. }
  7776. if (imported === '*') {
  7777. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  7778. ? namespaceVariableName
  7779. : moduleVariableName;
  7780. }
  7781. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  7782. }
  7783. function getEsModuleValue(getObject) {
  7784. return getObject([['value', 'true']], {
  7785. lineBreakIndent: null
  7786. });
  7787. }
  7788. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  7789. if (hasNamedExports) {
  7790. if (addEsModule) {
  7791. if (addNamespaceToStringTag) {
  7792. return `Object.defineProperties(exports,${_}${getObject([
  7793. ['__esModule', getEsModuleValue(getObject)],
  7794. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  7795. ], {
  7796. lineBreakIndent: null
  7797. })});`;
  7798. }
  7799. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  7800. }
  7801. if (addNamespaceToStringTag) {
  7802. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  7803. }
  7804. }
  7805. return '';
  7806. }
  7807. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  7808. if (needsLiveBinding) {
  7809. const [left, right] = getDirectReturnFunction([], {
  7810. functionReturn: true,
  7811. lineBreakIndent: null,
  7812. name: null
  7813. });
  7814. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  7815. `${t}${t}enumerable:${_}true,${n}` +
  7816. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  7817. }
  7818. return `exports[k]${_}=${_}${name}[k]`;
  7819. };
  7820. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  7821. const { _, cnst, n } = snippets;
  7822. const neededInteropHelpers = new Set();
  7823. const interopStatements = [];
  7824. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  7825. neededInteropHelpers.add(helper);
  7826. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  7827. };
  7828. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7829. if (isChunk) {
  7830. for (const { imported, reexported } of [
  7831. ...(imports || []),
  7832. ...(reexports || [])
  7833. ]) {
  7834. if (imported === '*' && reexported !== '*') {
  7835. if (!namedExportsMode) {
  7836. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  7837. }
  7838. break;
  7839. }
  7840. }
  7841. }
  7842. else {
  7843. const moduleInterop = interop(importPath);
  7844. let hasDefault = false;
  7845. let hasNamespace = false;
  7846. for (const { imported, reexported } of [
  7847. ...(imports || []),
  7848. ...(reexports || [])
  7849. ]) {
  7850. let helper;
  7851. let variableName;
  7852. if (imported === 'default') {
  7853. if (!hasDefault) {
  7854. hasDefault = true;
  7855. if (defaultVariableName !== namespaceVariableName) {
  7856. variableName = defaultVariableName;
  7857. helper = defaultInteropHelpersByInteropType[moduleInterop];
  7858. }
  7859. }
  7860. }
  7861. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  7862. hasNamespace = true;
  7863. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  7864. variableName = namespaceVariableName;
  7865. }
  7866. if (helper) {
  7867. addInteropStatement(variableName, helper, name);
  7868. }
  7869. }
  7870. }
  7871. }
  7872. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  7873. }
  7874. function addJsExtension(name) {
  7875. return name.endsWith('.js') ? name : name + '.js';
  7876. }
  7877. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  7878. // The assumption is that this makes sense for all relative ids:
  7879. // https://requirejs.org/docs/api.html#jsfiles
  7880. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  7881. if (id[0] !== '.') {
  7882. return id;
  7883. }
  7884. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  7885. }
  7886. const builtinModules = [
  7887. "node:assert",
  7888. "assert",
  7889. "node:assert/strict",
  7890. "assert/strict",
  7891. "node:async_hooks",
  7892. "async_hooks",
  7893. "node:buffer",
  7894. "buffer",
  7895. "node:child_process",
  7896. "child_process",
  7897. "node:cluster",
  7898. "cluster",
  7899. "node:console",
  7900. "console",
  7901. "node:constants",
  7902. "constants",
  7903. "node:crypto",
  7904. "crypto",
  7905. "node:dgram",
  7906. "dgram",
  7907. "node:diagnostics_channel",
  7908. "diagnostics_channel",
  7909. "node:dns",
  7910. "dns",
  7911. "node:dns/promises",
  7912. "dns/promises",
  7913. "node:domain",
  7914. "domain",
  7915. "node:events",
  7916. "events",
  7917. "node:fs",
  7918. "fs",
  7919. "node:fs/promises",
  7920. "fs/promises",
  7921. "node:http",
  7922. "http",
  7923. "node:http2",
  7924. "http2",
  7925. "node:https",
  7926. "https",
  7927. "node:inspector",
  7928. "inspector",
  7929. "node:inspector/promises",
  7930. "inspector/promises",
  7931. "node:module",
  7932. "module",
  7933. "node:net",
  7934. "net",
  7935. "node:os",
  7936. "os",
  7937. "node:path",
  7938. "path",
  7939. "node:path/posix",
  7940. "path/posix",
  7941. "node:path/win32",
  7942. "path/win32",
  7943. "node:perf_hooks",
  7944. "perf_hooks",
  7945. "node:process",
  7946. "process",
  7947. "node:querystring",
  7948. "querystring",
  7949. "node:quic",
  7950. "node:readline",
  7951. "readline",
  7952. "node:readline/promises",
  7953. "readline/promises",
  7954. "node:repl",
  7955. "repl",
  7956. "node:sea",
  7957. "node:sqlite",
  7958. "node:stream",
  7959. "stream",
  7960. "node:stream/consumers",
  7961. "stream/consumers",
  7962. "node:stream/promises",
  7963. "stream/promises",
  7964. "node:stream/web",
  7965. "stream/web",
  7966. "node:string_decoder",
  7967. "string_decoder",
  7968. "node:test",
  7969. "node:test/reporters",
  7970. "node:timers",
  7971. "timers",
  7972. "node:timers/promises",
  7973. "timers/promises",
  7974. "node:tls",
  7975. "tls",
  7976. "node:trace_events",
  7977. "trace_events",
  7978. "node:tty",
  7979. "tty",
  7980. "node:url",
  7981. "url",
  7982. "node:util",
  7983. "util",
  7984. "node:util/types",
  7985. "util/types",
  7986. "node:v8",
  7987. "v8",
  7988. "node:vm",
  7989. "vm",
  7990. "node:wasi",
  7991. "wasi",
  7992. "node:worker_threads",
  7993. "worker_threads",
  7994. "node:zlib",
  7995. "zlib"
  7996. ];
  7997. const nodeBuiltins = new Set(builtinModules);
  7998. function warnOnBuiltins(log, dependencies) {
  7999. const externalBuiltins = dependencies
  8000. .map(({ importPath }) => importPath)
  8001. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  8002. if (externalBuiltins.length === 0)
  8003. return;
  8004. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  8005. }
  8006. function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, generatedCode: { symbols }, interop, reexportProtoFromExternal, strict }) {
  8007. warnOnBuiltins(log, dependencies);
  8008. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8009. const parameters = dependencies.map(m => m.name);
  8010. const { n, getNonArrowFunctionIntro, _ } = snippets;
  8011. if (namedExportsMode && hasExports) {
  8012. parameters.unshift(`exports`);
  8013. deps.unshift(`'exports'`);
  8014. }
  8015. if (accessedGlobals.has('require')) {
  8016. parameters.unshift('require');
  8017. deps.unshift(`'require'`);
  8018. }
  8019. if (accessedGlobals.has('module')) {
  8020. parameters.unshift('module');
  8021. deps.unshift(`'module'`);
  8022. }
  8023. const completeAmdId = getCompleteAmdId(amd, id);
  8024. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8025. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  8026. const useStrict = strict ? `${_}'use strict';` : '';
  8027. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8028. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8029. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8030. if (namespaceMarkers) {
  8031. namespaceMarkers = n + n + namespaceMarkers;
  8032. }
  8033. magicString
  8034. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8035. .indent(t)
  8036. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8037. // cf. https://v8.dev/blog/preparser#pife
  8038. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  8039. isAsync: false,
  8040. name: null
  8041. })}{${useStrict}${n}${n}`)
  8042. .append(`${n}${n}}));`);
  8043. }
  8044. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, generatedCode: { symbols }, reexportProtoFromExternal, strict }) {
  8045. const { _, n } = snippets;
  8046. const useStrict = strict ? `'use strict';${n}${n}` : '';
  8047. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8048. if (namespaceMarkers) {
  8049. namespaceMarkers += n + n;
  8050. }
  8051. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  8052. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8053. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  8054. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  8055. magicString.append(`${exportBlock}${outro}`);
  8056. }
  8057. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  8058. let importBlock = '';
  8059. let definingVariable = false;
  8060. for (const { importPath, name, reexports, imports } of dependencies) {
  8061. if (!reexports && !imports) {
  8062. if (importBlock) {
  8063. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  8064. }
  8065. definingVariable = false;
  8066. importBlock += `require('${importPath}')`;
  8067. }
  8068. else {
  8069. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  8070. definingVariable = true;
  8071. importBlock += `${name}${_}=${_}require('${importPath}')`;
  8072. }
  8073. }
  8074. if (importBlock) {
  8075. return `${importBlock};${n}${n}`;
  8076. }
  8077. return '';
  8078. }
  8079. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  8080. const { n } = snippets;
  8081. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  8082. if (importBlock.length > 0)
  8083. intro += importBlock.join(n) + n + n;
  8084. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  8085. if (intro)
  8086. magicString.prepend(intro);
  8087. const exportBlock = getExportBlock(exports, snippets);
  8088. if (exportBlock.length > 0)
  8089. magicString.append(n + n + exportBlock.join(n).trim());
  8090. if (outro)
  8091. magicString.append(outro);
  8092. magicString.trim();
  8093. }
  8094. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  8095. const importBlock = [];
  8096. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  8097. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  8098. const pathWithAssertion = `'${importPath}'${assertion};`;
  8099. if (!reexports && !imports) {
  8100. importBlock.push(`import${_}${pathWithAssertion}`);
  8101. continue;
  8102. }
  8103. if (imports) {
  8104. let defaultImport = null;
  8105. let starImport = null;
  8106. const importedNames = [];
  8107. for (const specifier of imports) {
  8108. if (specifier.imported === 'default') {
  8109. defaultImport = specifier;
  8110. }
  8111. else if (specifier.imported === '*') {
  8112. starImport = specifier;
  8113. }
  8114. else {
  8115. importedNames.push(specifier);
  8116. }
  8117. }
  8118. if (starImport) {
  8119. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  8120. }
  8121. if (defaultImport && importedNames.length === 0) {
  8122. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  8123. }
  8124. else if (importedNames.length > 0) {
  8125. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  8126. .map(specifier => specifier.imported === specifier.local
  8127. ? specifier.imported
  8128. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  8129. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8130. }
  8131. }
  8132. if (reexports) {
  8133. let starExport = null;
  8134. const namespaceReexports = [];
  8135. const namedReexports = [];
  8136. for (const specifier of reexports) {
  8137. if (specifier.reexported === '*') {
  8138. starExport = specifier;
  8139. }
  8140. else if (specifier.imported === '*') {
  8141. namespaceReexports.push(specifier);
  8142. }
  8143. else {
  8144. namedReexports.push(specifier);
  8145. }
  8146. }
  8147. if (starExport) {
  8148. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  8149. }
  8150. if (namespaceReexports.length > 0) {
  8151. if (!imports ||
  8152. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  8153. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  8154. }
  8155. for (const specifier of namespaceReexports) {
  8156. importBlock.push(`export${_}{${_}${name === specifier.reexported
  8157. ? name
  8158. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  8159. }
  8160. }
  8161. if (namedReexports.length > 0) {
  8162. importBlock.push(`export${_}{${_}${namedReexports
  8163. .map(specifier => specifier.imported === specifier.reexported
  8164. ? stringifyIdentifierIfNeeded(specifier.imported)
  8165. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  8166. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8167. }
  8168. }
  8169. }
  8170. return importBlock;
  8171. }
  8172. function getExportBlock(exports, { _, cnst }) {
  8173. const exportBlock = [];
  8174. const exportDeclaration = new Array(exports.length);
  8175. let index = 0;
  8176. for (const specifier of exports) {
  8177. if (specifier.expression) {
  8178. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  8179. }
  8180. exportDeclaration[index++] =
  8181. specifier.exported === specifier.local
  8182. ? specifier.local
  8183. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  8184. }
  8185. if (exportDeclaration.length > 0) {
  8186. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  8187. }
  8188. return exportBlock;
  8189. }
  8190. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  8191. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  8192. const parts = name.split('.');
  8193. // Check if the key exists in the object's prototype.
  8194. const isReserved = parts[0] in Object.prototype;
  8195. if (log && isReserved) {
  8196. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8197. }
  8198. parts[0] =
  8199. (typeof globals === 'function'
  8200. ? globals(parts[0])
  8201. : isReserved
  8202. ? parts[0]
  8203. : globals[parts[0]]) || parts[0];
  8204. parts.pop();
  8205. let propertyPath = root;
  8206. return (parts
  8207. .map(part => {
  8208. propertyPath += getPropertyAccess(part);
  8209. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  8210. })
  8211. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  8212. }
  8213. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  8214. const parts = deepName.split('.');
  8215. // Check if the key exists in the object's prototype.
  8216. const isReserved = parts[0] in Object.prototype;
  8217. if (log && isReserved) {
  8218. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8219. }
  8220. parts[0] =
  8221. (typeof globals === 'function'
  8222. ? globals(parts[0])
  8223. : isReserved
  8224. ? parts[0]
  8225. : globals[parts[0]]) || parts[0];
  8226. const last = parts.pop();
  8227. let propertyPath = root;
  8228. let deepAssignment = [
  8229. ...parts.map(part => {
  8230. propertyPath += getPropertyAccess(part);
  8231. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  8232. }),
  8233. `${propertyPath}${getPropertyAccess(last)}`
  8234. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  8235. if (parts.length > 0) {
  8236. deepAssignment = `(${deepAssignment})`;
  8237. }
  8238. return deepAssignment;
  8239. }
  8240. function trimEmptyImports(dependencies) {
  8241. let index = dependencies.length;
  8242. while (index--) {
  8243. const { imports, reexports } = dependencies[index];
  8244. if (imports || reexports) {
  8245. return dependencies.slice(0, index + 1);
  8246. }
  8247. }
  8248. return [];
  8249. }
  8250. function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, reexportProtoFromExternal, globals, interop, name, generatedCode: { symbols }, strict }) {
  8251. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  8252. const isNamespaced = name && name.includes('.');
  8253. const useVariableAssignment = !extend && !isNamespaced;
  8254. if (name && useVariableAssignment && !isLegal(name)) {
  8255. return error(logIllegalIdentifierAsName(name));
  8256. }
  8257. warnOnBuiltins(log, dependencies);
  8258. const external = trimEmptyImports(dependencies);
  8259. const deps = external.map(dep => dep.globalName || 'null');
  8260. const parameters = external.map(m => m.name);
  8261. if (hasExports && !name) {
  8262. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  8263. }
  8264. if (namedExportsMode && hasExports) {
  8265. if (extend) {
  8266. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  8267. parameters.unshift('exports');
  8268. }
  8269. else {
  8270. deps.unshift('{}');
  8271. parameters.unshift('exports');
  8272. }
  8273. }
  8274. const useStrict = strict ? `${t}'use strict';${n}` : '';
  8275. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8276. magicString.prepend(`${intro}${interopBlock}`);
  8277. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  8278. isAsync: false,
  8279. name: null
  8280. })}{${n}${useStrict}${n}`;
  8281. if (hasExports) {
  8282. if (name && !(extend && namedExportsMode)) {
  8283. wrapperIntro =
  8284. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  8285. `${_}=${_}${wrapperIntro}`;
  8286. }
  8287. if (isNamespaced) {
  8288. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  8289. }
  8290. }
  8291. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  8292. if (hasExports && !extend && namedExportsMode) {
  8293. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  8294. }
  8295. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8296. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8297. if (namespaceMarkers) {
  8298. namespaceMarkers = n + n + namespaceMarkers;
  8299. }
  8300. magicString
  8301. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8302. .indent(t)
  8303. .prepend(wrapperIntro)
  8304. .append(wrapperOutro);
  8305. }
  8306. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  8307. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  8308. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  8309. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  8310. const registeredName = name ? `'${name}',${_}` : '';
  8311. const wrapperParameters = accessedGlobals.has('module')
  8312. ? ['exports', 'module']
  8313. : hasExports
  8314. ? ['exports']
  8315. : [];
  8316. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8317. // cf. https://v8.dev/blog/preparser#pife
  8318. let wrapperStart = `System.register(${registeredName}[` +
  8319. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  8320. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  8321. isAsync: false,
  8322. name: null
  8323. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  8324. getStarExcludesBlock(starExcludes, t, snippets) +
  8325. getImportBindingsBlock(importBindings, t, snippets) +
  8326. `${n}${t}return${_}{${setters.length > 0
  8327. ? `${n}${t}${t}setters:${_}[${setters
  8328. .map(setter => setter
  8329. ? `${getFunctionIntro(['module'], {
  8330. isAsync: false,
  8331. name: null
  8332. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  8333. : systemNullSetters
  8334. ? `null`
  8335. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  8336. .join(`,${_}`)}],`
  8337. : ''}${n}`;
  8338. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  8339. isAsync: usesTopLevelAwait,
  8340. name: null
  8341. })}{${n}${n}`;
  8342. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  8343. magicString
  8344. .prepend(intro +
  8345. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  8346. getHoistedExportsBlock(exports, t, snippets))
  8347. .append(`${outro}${n}${n}` +
  8348. getSyntheticExportsBlock(exports, t, snippets) +
  8349. getMissingExportsBlock(exports, t, snippets))
  8350. .indent(`${t}${t}${t}`)
  8351. .append(wrapperEnd)
  8352. .prepend(wrapperStart);
  8353. }
  8354. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  8355. const importBindings = [];
  8356. const setters = [];
  8357. let starExcludes = null;
  8358. for (const { imports, reexports } of dependencies) {
  8359. const setter = [];
  8360. if (imports) {
  8361. for (const specifier of imports) {
  8362. importBindings.push(specifier.local);
  8363. if (specifier.imported === '*') {
  8364. setter.push(`${specifier.local}${_}=${_}module;`);
  8365. }
  8366. else {
  8367. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  8368. }
  8369. }
  8370. }
  8371. if (reexports) {
  8372. const reexportedNames = [];
  8373. let hasStarReexport = false;
  8374. for (const { imported, reexported } of reexports) {
  8375. if (reexported === '*') {
  8376. hasStarReexport = true;
  8377. }
  8378. else {
  8379. reexportedNames.push([
  8380. reexported,
  8381. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  8382. ]);
  8383. }
  8384. }
  8385. if (reexportedNames.length > 1 || hasStarReexport) {
  8386. if (hasStarReexport) {
  8387. if (!starExcludes) {
  8388. starExcludes = getStarExcludes({ dependencies, exports });
  8389. }
  8390. reexportedNames.unshift([null, `__proto__:${_}null`]);
  8391. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8392. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  8393. }
  8394. else {
  8395. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8396. setter.push(`exports(${exportMapping});`);
  8397. }
  8398. }
  8399. else {
  8400. const [key, value] = reexportedNames[0];
  8401. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  8402. }
  8403. }
  8404. setters.push(setter.join(`${n}${t}${t}${t}`));
  8405. }
  8406. return { importBindings, setters, starExcludes };
  8407. }
  8408. const getStarExcludes = ({ dependencies, exports }) => {
  8409. const starExcludes = new Set(exports.map(expt => expt.exported));
  8410. starExcludes.add('default');
  8411. for (const { reexports } of dependencies) {
  8412. if (reexports) {
  8413. for (const reexport of reexports) {
  8414. if (reexport.reexported !== '*')
  8415. starExcludes.add(reexport.reexported);
  8416. }
  8417. }
  8418. }
  8419. return starExcludes;
  8420. };
  8421. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  8422. if (starExcludes) {
  8423. const fields = [...starExcludes].map(property => [
  8424. property,
  8425. '1'
  8426. ]);
  8427. fields.unshift([null, `__proto__:${_}null`]);
  8428. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  8429. lineBreakIndent: { base: t, t }
  8430. })};`;
  8431. }
  8432. return '';
  8433. };
  8434. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  8435. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8436. function getExportsBlock(exports, t, { _, n }) {
  8437. if (exports.length === 0) {
  8438. return '';
  8439. }
  8440. if (exports.length === 1) {
  8441. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  8442. }
  8443. return (`exports({${n}` +
  8444. exports
  8445. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  8446. .join(`,${n}`) +
  8447. `${n}});${n}${n}`);
  8448. }
  8449. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  8450. .filter(expt => expt.expression)
  8451. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8452. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  8453. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  8454. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  8455. function globalProperty(name, globalVariable, getPropertyAccess) {
  8456. if (!name)
  8457. return 'null';
  8458. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  8459. }
  8460. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  8461. let propertyPath = globalVariable;
  8462. return name
  8463. .split('.')
  8464. .map(part => (propertyPath += getPropertyAccess(part)))
  8465. .join(`${_}&&${_}`);
  8466. }
  8467. function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, generatedCode: { symbols }, globals, noConflict, reexportProtoFromExternal, strict }) {
  8468. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  8469. const factoryVariable = compact ? 'f' : 'factory';
  8470. const globalVariable = compact ? 'g' : 'global';
  8471. if (hasExports && !name) {
  8472. return error(logMissingNameOptionForUmdExport());
  8473. }
  8474. warnOnBuiltins(log, dependencies);
  8475. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8476. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  8477. const trimmedImports = trimEmptyImports(dependencies);
  8478. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  8479. const factoryParameters = trimmedImports.map(m => m.name);
  8480. if (namedExportsMode && (hasExports || noConflict)) {
  8481. amdDeps.unshift(`'exports'`);
  8482. cjsDeps.unshift(`exports`);
  8483. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  8484. factoryParameters.unshift('exports');
  8485. }
  8486. const completeAmdId = getCompleteAmdId(amd, id);
  8487. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8488. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  8489. const define = amd.define;
  8490. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  8491. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  8492. let iifeExport;
  8493. if (noConflict) {
  8494. const noConflictExportsVariable = compact ? 'e' : 'exports';
  8495. let factory;
  8496. if (!namedExportsMode && hasExports) {
  8497. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  8498. }
  8499. else {
  8500. const module = globalDeps.shift();
  8501. factory =
  8502. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  8503. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  8504. }
  8505. iifeExport =
  8506. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  8507. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  8508. `${t}${t}${factory}${n}` +
  8509. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  8510. isAsync: false,
  8511. name: null
  8512. })}{${_}` +
  8513. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  8514. `${t}})()`;
  8515. }
  8516. else {
  8517. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  8518. if (!namedExportsMode && hasExports) {
  8519. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  8520. }
  8521. }
  8522. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  8523. const wrapperParameters = [factoryVariable];
  8524. if (iifeNeedsGlobal) {
  8525. wrapperParameters.unshift(globalVariable);
  8526. }
  8527. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  8528. const iifeStart = iifeNeedsGlobal
  8529. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  8530. : '';
  8531. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  8532. const cjsIntro = iifeNeedsGlobal
  8533. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  8534. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  8535. : '';
  8536. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  8537. cjsIntro +
  8538. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  8539. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  8540. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8541. // cf. https://v8.dev/blog/preparser#pife
  8542. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  8543. isAsync: false,
  8544. name: null
  8545. })}{${useStrict}${n}`;
  8546. const wrapperOutro = n + n + '}));';
  8547. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8548. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8549. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8550. if (namespaceMarkers) {
  8551. namespaceMarkers = n + n + namespaceMarkers;
  8552. }
  8553. magicString
  8554. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8555. .trim()
  8556. .indent(t)
  8557. .append(wrapperOutro)
  8558. .prepend(wrapperIntro);
  8559. }
  8560. const finalisers = { amd, cjs, es, iife, system, umd };
  8561. function getDefaultExportFromCjs (x) {
  8562. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  8563. }
  8564. function getAugmentedNamespace(n) {
  8565. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  8566. var f = n.default;
  8567. if (typeof f == "function") {
  8568. var a = function a () {
  8569. if (this instanceof a) {
  8570. return Reflect.construct(f, arguments, this.constructor);
  8571. }
  8572. return f.apply(this, arguments);
  8573. };
  8574. a.prototype = f.prototype;
  8575. } else a = {};
  8576. Object.defineProperty(a, '__esModule', {value: true});
  8577. Object.keys(n).forEach(function (k) {
  8578. var d = Object.getOwnPropertyDescriptor(n, k);
  8579. Object.defineProperty(a, k, d.get ? d : {
  8580. enumerable: true,
  8581. get: function () {
  8582. return n[k];
  8583. }
  8584. });
  8585. });
  8586. return a;
  8587. }
  8588. var utils = {};
  8589. var constants;
  8590. var hasRequiredConstants;
  8591. function requireConstants () {
  8592. if (hasRequiredConstants) return constants;
  8593. hasRequiredConstants = 1;
  8594. const WIN_SLASH = '\\\\/';
  8595. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  8596. /**
  8597. * Posix glob regex
  8598. */
  8599. const DOT_LITERAL = '\\.';
  8600. const PLUS_LITERAL = '\\+';
  8601. const QMARK_LITERAL = '\\?';
  8602. const SLASH_LITERAL = '\\/';
  8603. const ONE_CHAR = '(?=.)';
  8604. const QMARK = '[^/]';
  8605. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  8606. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  8607. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  8608. const NO_DOT = `(?!${DOT_LITERAL})`;
  8609. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  8610. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  8611. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  8612. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  8613. const STAR = `${QMARK}*?`;
  8614. const SEP = '/';
  8615. const POSIX_CHARS = {
  8616. DOT_LITERAL,
  8617. PLUS_LITERAL,
  8618. QMARK_LITERAL,
  8619. SLASH_LITERAL,
  8620. ONE_CHAR,
  8621. QMARK,
  8622. END_ANCHOR,
  8623. DOTS_SLASH,
  8624. NO_DOT,
  8625. NO_DOTS,
  8626. NO_DOT_SLASH,
  8627. NO_DOTS_SLASH,
  8628. QMARK_NO_DOT,
  8629. STAR,
  8630. START_ANCHOR,
  8631. SEP
  8632. };
  8633. /**
  8634. * Windows glob regex
  8635. */
  8636. const WINDOWS_CHARS = {
  8637. ...POSIX_CHARS,
  8638. SLASH_LITERAL: `[${WIN_SLASH}]`,
  8639. QMARK: WIN_NO_SLASH,
  8640. STAR: `${WIN_NO_SLASH}*?`,
  8641. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  8642. NO_DOT: `(?!${DOT_LITERAL})`,
  8643. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8644. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  8645. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8646. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  8647. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  8648. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  8649. SEP: '\\'
  8650. };
  8651. /**
  8652. * POSIX Bracket Regex
  8653. */
  8654. const POSIX_REGEX_SOURCE = {
  8655. alnum: 'a-zA-Z0-9',
  8656. alpha: 'a-zA-Z',
  8657. ascii: '\\x00-\\x7F',
  8658. blank: ' \\t',
  8659. cntrl: '\\x00-\\x1F\\x7F',
  8660. digit: '0-9',
  8661. graph: '\\x21-\\x7E',
  8662. lower: 'a-z',
  8663. print: '\\x20-\\x7E ',
  8664. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  8665. space: ' \\t\\r\\n\\v\\f',
  8666. upper: 'A-Z',
  8667. word: 'A-Za-z0-9_',
  8668. xdigit: 'A-Fa-f0-9'
  8669. };
  8670. constants = {
  8671. MAX_LENGTH: 1024 * 64,
  8672. POSIX_REGEX_SOURCE,
  8673. // regular expressions
  8674. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  8675. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  8676. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  8677. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  8678. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  8679. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  8680. // Replace globs with equivalent patterns to reduce parsing time.
  8681. REPLACEMENTS: {
  8682. '***': '*',
  8683. '**/**': '**',
  8684. '**/**/**': '**'
  8685. },
  8686. // Digits
  8687. CHAR_0: 48, /* 0 */
  8688. CHAR_9: 57, /* 9 */
  8689. // Alphabet chars.
  8690. CHAR_UPPERCASE_A: 65, /* A */
  8691. CHAR_LOWERCASE_A: 97, /* a */
  8692. CHAR_UPPERCASE_Z: 90, /* Z */
  8693. CHAR_LOWERCASE_Z: 122, /* z */
  8694. CHAR_LEFT_PARENTHESES: 40, /* ( */
  8695. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  8696. CHAR_ASTERISK: 42, /* * */
  8697. // Non-alphabetic chars.
  8698. CHAR_AMPERSAND: 38, /* & */
  8699. CHAR_AT: 64, /* @ */
  8700. CHAR_BACKWARD_SLASH: 92, /* \ */
  8701. CHAR_CARRIAGE_RETURN: 13, /* \r */
  8702. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  8703. CHAR_COLON: 58, /* : */
  8704. CHAR_COMMA: 44, /* , */
  8705. CHAR_DOT: 46, /* . */
  8706. CHAR_DOUBLE_QUOTE: 34, /* " */
  8707. CHAR_EQUAL: 61, /* = */
  8708. CHAR_EXCLAMATION_MARK: 33, /* ! */
  8709. CHAR_FORM_FEED: 12, /* \f */
  8710. CHAR_FORWARD_SLASH: 47, /* / */
  8711. CHAR_GRAVE_ACCENT: 96, /* ` */
  8712. CHAR_HASH: 35, /* # */
  8713. CHAR_HYPHEN_MINUS: 45, /* - */
  8714. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  8715. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  8716. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  8717. CHAR_LINE_FEED: 10, /* \n */
  8718. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  8719. CHAR_PERCENT: 37, /* % */
  8720. CHAR_PLUS: 43, /* + */
  8721. CHAR_QUESTION_MARK: 63, /* ? */
  8722. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  8723. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  8724. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  8725. CHAR_SEMICOLON: 59, /* ; */
  8726. CHAR_SINGLE_QUOTE: 39, /* ' */
  8727. CHAR_SPACE: 32, /* */
  8728. CHAR_TAB: 9, /* \t */
  8729. CHAR_UNDERSCORE: 95, /* _ */
  8730. CHAR_VERTICAL_LINE: 124, /* | */
  8731. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  8732. /**
  8733. * Create EXTGLOB_CHARS
  8734. */
  8735. extglobChars(chars) {
  8736. return {
  8737. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  8738. '?': { type: 'qmark', open: '(?:', close: ')?' },
  8739. '+': { type: 'plus', open: '(?:', close: ')+' },
  8740. '*': { type: 'star', open: '(?:', close: ')*' },
  8741. '@': { type: 'at', open: '(?:', close: ')' }
  8742. };
  8743. },
  8744. /**
  8745. * Create GLOB_CHARS
  8746. */
  8747. globChars(win32) {
  8748. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  8749. }
  8750. };
  8751. return constants;
  8752. }
  8753. /*global navigator*/
  8754. var hasRequiredUtils;
  8755. function requireUtils () {
  8756. if (hasRequiredUtils) return utils;
  8757. hasRequiredUtils = 1;
  8758. (function (exports) {
  8759. const {
  8760. REGEX_BACKSLASH,
  8761. REGEX_REMOVE_BACKSLASH,
  8762. REGEX_SPECIAL_CHARS,
  8763. REGEX_SPECIAL_CHARS_GLOBAL
  8764. } = /*@__PURE__*/ requireConstants();
  8765. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  8766. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  8767. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  8768. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  8769. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  8770. exports.isWindows = () => {
  8771. if (typeof navigator !== 'undefined' && navigator.platform) {
  8772. const platform = navigator.platform.toLowerCase();
  8773. return platform === 'win32' || platform === 'windows';
  8774. }
  8775. if (typeof process !== 'undefined' && process.platform) {
  8776. return process.platform === 'win32';
  8777. }
  8778. return false;
  8779. };
  8780. exports.removeBackslashes = str => {
  8781. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  8782. return match === '\\' ? '' : match;
  8783. });
  8784. };
  8785. exports.escapeLast = (input, char, lastIdx) => {
  8786. const idx = input.lastIndexOf(char, lastIdx);
  8787. if (idx === -1) return input;
  8788. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  8789. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  8790. };
  8791. exports.removePrefix = (input, state = {}) => {
  8792. let output = input;
  8793. if (output.startsWith('./')) {
  8794. output = output.slice(2);
  8795. state.prefix = './';
  8796. }
  8797. return output;
  8798. };
  8799. exports.wrapOutput = (input, state = {}, options = {}) => {
  8800. const prepend = options.contains ? '' : '^';
  8801. const append = options.contains ? '' : '$';
  8802. let output = `${prepend}(?:${input})${append}`;
  8803. if (state.negated === true) {
  8804. output = `(?:^(?!${output}).*$)`;
  8805. }
  8806. return output;
  8807. };
  8808. exports.basename = (path, { windows } = {}) => {
  8809. const segs = path.split(windows ? /[\\/]/ : '/');
  8810. const last = segs[segs.length - 1];
  8811. if (last === '') {
  8812. return segs[segs.length - 2];
  8813. }
  8814. return last;
  8815. };
  8816. } (utils));
  8817. return utils;
  8818. }
  8819. var scan_1;
  8820. var hasRequiredScan;
  8821. function requireScan () {
  8822. if (hasRequiredScan) return scan_1;
  8823. hasRequiredScan = 1;
  8824. const utils = /*@__PURE__*/ requireUtils();
  8825. const {
  8826. CHAR_ASTERISK, /* * */
  8827. CHAR_AT, /* @ */
  8828. CHAR_BACKWARD_SLASH, /* \ */
  8829. CHAR_COMMA, /* , */
  8830. CHAR_DOT, /* . */
  8831. CHAR_EXCLAMATION_MARK, /* ! */
  8832. CHAR_FORWARD_SLASH, /* / */
  8833. CHAR_LEFT_CURLY_BRACE, /* { */
  8834. CHAR_LEFT_PARENTHESES, /* ( */
  8835. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  8836. CHAR_PLUS, /* + */
  8837. CHAR_QUESTION_MARK, /* ? */
  8838. CHAR_RIGHT_CURLY_BRACE, /* } */
  8839. CHAR_RIGHT_PARENTHESES, /* ) */
  8840. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  8841. } = /*@__PURE__*/ requireConstants();
  8842. const isPathSeparator = code => {
  8843. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  8844. };
  8845. const depth = token => {
  8846. if (token.isPrefix !== true) {
  8847. token.depth = token.isGlobstar ? Infinity : 1;
  8848. }
  8849. };
  8850. /**
  8851. * Quickly scans a glob pattern and returns an object with a handful of
  8852. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  8853. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  8854. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  8855. *
  8856. * ```js
  8857. * const pm = require('picomatch');
  8858. * console.log(pm.scan('foo/bar/*.js'));
  8859. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  8860. * ```
  8861. * @param {String} `str`
  8862. * @param {Object} `options`
  8863. * @return {Object} Returns an object with tokens and regex source string.
  8864. * @api public
  8865. */
  8866. const scan = (input, options) => {
  8867. const opts = options || {};
  8868. const length = input.length - 1;
  8869. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  8870. const slashes = [];
  8871. const tokens = [];
  8872. const parts = [];
  8873. let str = input;
  8874. let index = -1;
  8875. let start = 0;
  8876. let lastIndex = 0;
  8877. let isBrace = false;
  8878. let isBracket = false;
  8879. let isGlob = false;
  8880. let isExtglob = false;
  8881. let isGlobstar = false;
  8882. let braceEscaped = false;
  8883. let backslashes = false;
  8884. let negated = false;
  8885. let negatedExtglob = false;
  8886. let finished = false;
  8887. let braces = 0;
  8888. let prev;
  8889. let code;
  8890. let token = { value: '', depth: 0, isGlob: false };
  8891. const eos = () => index >= length;
  8892. const peek = () => str.charCodeAt(index + 1);
  8893. const advance = () => {
  8894. prev = code;
  8895. return str.charCodeAt(++index);
  8896. };
  8897. while (index < length) {
  8898. code = advance();
  8899. let next;
  8900. if (code === CHAR_BACKWARD_SLASH) {
  8901. backslashes = token.backslashes = true;
  8902. code = advance();
  8903. if (code === CHAR_LEFT_CURLY_BRACE) {
  8904. braceEscaped = true;
  8905. }
  8906. continue;
  8907. }
  8908. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  8909. braces++;
  8910. while (eos() !== true && (code = advance())) {
  8911. if (code === CHAR_BACKWARD_SLASH) {
  8912. backslashes = token.backslashes = true;
  8913. advance();
  8914. continue;
  8915. }
  8916. if (code === CHAR_LEFT_CURLY_BRACE) {
  8917. braces++;
  8918. continue;
  8919. }
  8920. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  8921. isBrace = token.isBrace = true;
  8922. isGlob = token.isGlob = true;
  8923. finished = true;
  8924. if (scanToEnd === true) {
  8925. continue;
  8926. }
  8927. break;
  8928. }
  8929. if (braceEscaped !== true && code === CHAR_COMMA) {
  8930. isBrace = token.isBrace = true;
  8931. isGlob = token.isGlob = true;
  8932. finished = true;
  8933. if (scanToEnd === true) {
  8934. continue;
  8935. }
  8936. break;
  8937. }
  8938. if (code === CHAR_RIGHT_CURLY_BRACE) {
  8939. braces--;
  8940. if (braces === 0) {
  8941. braceEscaped = false;
  8942. isBrace = token.isBrace = true;
  8943. finished = true;
  8944. break;
  8945. }
  8946. }
  8947. }
  8948. if (scanToEnd === true) {
  8949. continue;
  8950. }
  8951. break;
  8952. }
  8953. if (code === CHAR_FORWARD_SLASH) {
  8954. slashes.push(index);
  8955. tokens.push(token);
  8956. token = { value: '', depth: 0, isGlob: false };
  8957. if (finished === true) continue;
  8958. if (prev === CHAR_DOT && index === (start + 1)) {
  8959. start += 2;
  8960. continue;
  8961. }
  8962. lastIndex = index + 1;
  8963. continue;
  8964. }
  8965. if (opts.noext !== true) {
  8966. const isExtglobChar = code === CHAR_PLUS
  8967. || code === CHAR_AT
  8968. || code === CHAR_ASTERISK
  8969. || code === CHAR_QUESTION_MARK
  8970. || code === CHAR_EXCLAMATION_MARK;
  8971. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  8972. isGlob = token.isGlob = true;
  8973. isExtglob = token.isExtglob = true;
  8974. finished = true;
  8975. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  8976. negatedExtglob = true;
  8977. }
  8978. if (scanToEnd === true) {
  8979. while (eos() !== true && (code = advance())) {
  8980. if (code === CHAR_BACKWARD_SLASH) {
  8981. backslashes = token.backslashes = true;
  8982. code = advance();
  8983. continue;
  8984. }
  8985. if (code === CHAR_RIGHT_PARENTHESES) {
  8986. isGlob = token.isGlob = true;
  8987. finished = true;
  8988. break;
  8989. }
  8990. }
  8991. continue;
  8992. }
  8993. break;
  8994. }
  8995. }
  8996. if (code === CHAR_ASTERISK) {
  8997. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  8998. isGlob = token.isGlob = true;
  8999. finished = true;
  9000. if (scanToEnd === true) {
  9001. continue;
  9002. }
  9003. break;
  9004. }
  9005. if (code === CHAR_QUESTION_MARK) {
  9006. isGlob = token.isGlob = true;
  9007. finished = true;
  9008. if (scanToEnd === true) {
  9009. continue;
  9010. }
  9011. break;
  9012. }
  9013. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  9014. while (eos() !== true && (next = advance())) {
  9015. if (next === CHAR_BACKWARD_SLASH) {
  9016. backslashes = token.backslashes = true;
  9017. advance();
  9018. continue;
  9019. }
  9020. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  9021. isBracket = token.isBracket = true;
  9022. isGlob = token.isGlob = true;
  9023. finished = true;
  9024. break;
  9025. }
  9026. }
  9027. if (scanToEnd === true) {
  9028. continue;
  9029. }
  9030. break;
  9031. }
  9032. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  9033. negated = token.negated = true;
  9034. start++;
  9035. continue;
  9036. }
  9037. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  9038. isGlob = token.isGlob = true;
  9039. if (scanToEnd === true) {
  9040. while (eos() !== true && (code = advance())) {
  9041. if (code === CHAR_LEFT_PARENTHESES) {
  9042. backslashes = token.backslashes = true;
  9043. code = advance();
  9044. continue;
  9045. }
  9046. if (code === CHAR_RIGHT_PARENTHESES) {
  9047. finished = true;
  9048. break;
  9049. }
  9050. }
  9051. continue;
  9052. }
  9053. break;
  9054. }
  9055. if (isGlob === true) {
  9056. finished = true;
  9057. if (scanToEnd === true) {
  9058. continue;
  9059. }
  9060. break;
  9061. }
  9062. }
  9063. if (opts.noext === true) {
  9064. isExtglob = false;
  9065. isGlob = false;
  9066. }
  9067. let base = str;
  9068. let prefix = '';
  9069. let glob = '';
  9070. if (start > 0) {
  9071. prefix = str.slice(0, start);
  9072. str = str.slice(start);
  9073. lastIndex -= start;
  9074. }
  9075. if (base && isGlob === true && lastIndex > 0) {
  9076. base = str.slice(0, lastIndex);
  9077. glob = str.slice(lastIndex);
  9078. } else if (isGlob === true) {
  9079. base = '';
  9080. glob = str;
  9081. } else {
  9082. base = str;
  9083. }
  9084. if (base && base !== '' && base !== '/' && base !== str) {
  9085. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  9086. base = base.slice(0, -1);
  9087. }
  9088. }
  9089. if (opts.unescape === true) {
  9090. if (glob) glob = utils.removeBackslashes(glob);
  9091. if (base && backslashes === true) {
  9092. base = utils.removeBackslashes(base);
  9093. }
  9094. }
  9095. const state = {
  9096. prefix,
  9097. input,
  9098. start,
  9099. base,
  9100. glob,
  9101. isBrace,
  9102. isBracket,
  9103. isGlob,
  9104. isExtglob,
  9105. isGlobstar,
  9106. negated,
  9107. negatedExtglob
  9108. };
  9109. if (opts.tokens === true) {
  9110. state.maxDepth = 0;
  9111. if (!isPathSeparator(code)) {
  9112. tokens.push(token);
  9113. }
  9114. state.tokens = tokens;
  9115. }
  9116. if (opts.parts === true || opts.tokens === true) {
  9117. let prevIndex;
  9118. for (let idx = 0; idx < slashes.length; idx++) {
  9119. const n = prevIndex ? prevIndex + 1 : start;
  9120. const i = slashes[idx];
  9121. const value = input.slice(n, i);
  9122. if (opts.tokens) {
  9123. if (idx === 0 && start !== 0) {
  9124. tokens[idx].isPrefix = true;
  9125. tokens[idx].value = prefix;
  9126. } else {
  9127. tokens[idx].value = value;
  9128. }
  9129. depth(tokens[idx]);
  9130. state.maxDepth += tokens[idx].depth;
  9131. }
  9132. if (idx !== 0 || value !== '') {
  9133. parts.push(value);
  9134. }
  9135. prevIndex = i;
  9136. }
  9137. if (prevIndex && prevIndex + 1 < input.length) {
  9138. const value = input.slice(prevIndex + 1);
  9139. parts.push(value);
  9140. if (opts.tokens) {
  9141. tokens[tokens.length - 1].value = value;
  9142. depth(tokens[tokens.length - 1]);
  9143. state.maxDepth += tokens[tokens.length - 1].depth;
  9144. }
  9145. }
  9146. state.slashes = slashes;
  9147. state.parts = parts;
  9148. }
  9149. return state;
  9150. };
  9151. scan_1 = scan;
  9152. return scan_1;
  9153. }
  9154. var parse_1;
  9155. var hasRequiredParse;
  9156. function requireParse () {
  9157. if (hasRequiredParse) return parse_1;
  9158. hasRequiredParse = 1;
  9159. const constants = /*@__PURE__*/ requireConstants();
  9160. const utils = /*@__PURE__*/ requireUtils();
  9161. /**
  9162. * Constants
  9163. */
  9164. const {
  9165. MAX_LENGTH,
  9166. POSIX_REGEX_SOURCE,
  9167. REGEX_NON_SPECIAL_CHARS,
  9168. REGEX_SPECIAL_CHARS_BACKREF,
  9169. REPLACEMENTS
  9170. } = constants;
  9171. /**
  9172. * Helpers
  9173. */
  9174. const expandRange = (args, options) => {
  9175. if (typeof options.expandRange === 'function') {
  9176. return options.expandRange(...args, options);
  9177. }
  9178. args.sort();
  9179. const value = `[${args.join('-')}]`;
  9180. return value;
  9181. };
  9182. /**
  9183. * Create the message for a syntax error
  9184. */
  9185. const syntaxError = (type, char) => {
  9186. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  9187. };
  9188. /**
  9189. * Parse the given input string.
  9190. * @param {String} input
  9191. * @param {Object} options
  9192. * @return {Object}
  9193. */
  9194. const parse = (input, options) => {
  9195. if (typeof input !== 'string') {
  9196. throw new TypeError('Expected a string');
  9197. }
  9198. input = REPLACEMENTS[input] || input;
  9199. const opts = { ...options };
  9200. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  9201. let len = input.length;
  9202. if (len > max) {
  9203. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  9204. }
  9205. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  9206. const tokens = [bos];
  9207. const capture = opts.capture ? '' : '?:';
  9208. // create constants based on platform, for windows or posix
  9209. const PLATFORM_CHARS = constants.globChars(opts.windows);
  9210. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  9211. const {
  9212. DOT_LITERAL,
  9213. PLUS_LITERAL,
  9214. SLASH_LITERAL,
  9215. ONE_CHAR,
  9216. DOTS_SLASH,
  9217. NO_DOT,
  9218. NO_DOT_SLASH,
  9219. NO_DOTS_SLASH,
  9220. QMARK,
  9221. QMARK_NO_DOT,
  9222. STAR,
  9223. START_ANCHOR
  9224. } = PLATFORM_CHARS;
  9225. const globstar = opts => {
  9226. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  9227. };
  9228. const nodot = opts.dot ? '' : NO_DOT;
  9229. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  9230. let star = opts.bash === true ? globstar(opts) : STAR;
  9231. if (opts.capture) {
  9232. star = `(${star})`;
  9233. }
  9234. // minimatch options support
  9235. if (typeof opts.noext === 'boolean') {
  9236. opts.noextglob = opts.noext;
  9237. }
  9238. const state = {
  9239. input,
  9240. index: -1,
  9241. start: 0,
  9242. dot: opts.dot === true,
  9243. consumed: '',
  9244. output: '',
  9245. prefix: '',
  9246. backtrack: false,
  9247. negated: false,
  9248. brackets: 0,
  9249. braces: 0,
  9250. parens: 0,
  9251. quotes: 0,
  9252. globstar: false,
  9253. tokens
  9254. };
  9255. input = utils.removePrefix(input, state);
  9256. len = input.length;
  9257. const extglobs = [];
  9258. const braces = [];
  9259. const stack = [];
  9260. let prev = bos;
  9261. let value;
  9262. /**
  9263. * Tokenizing helpers
  9264. */
  9265. const eos = () => state.index === len - 1;
  9266. const peek = state.peek = (n = 1) => input[state.index + n];
  9267. const advance = state.advance = () => input[++state.index] || '';
  9268. const remaining = () => input.slice(state.index + 1);
  9269. const consume = (value = '', num = 0) => {
  9270. state.consumed += value;
  9271. state.index += num;
  9272. };
  9273. const append = token => {
  9274. state.output += token.output != null ? token.output : token.value;
  9275. consume(token.value);
  9276. };
  9277. const negate = () => {
  9278. let count = 1;
  9279. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  9280. advance();
  9281. state.start++;
  9282. count++;
  9283. }
  9284. if (count % 2 === 0) {
  9285. return false;
  9286. }
  9287. state.negated = true;
  9288. state.start++;
  9289. return true;
  9290. };
  9291. const increment = type => {
  9292. state[type]++;
  9293. stack.push(type);
  9294. };
  9295. const decrement = type => {
  9296. state[type]--;
  9297. stack.pop();
  9298. };
  9299. /**
  9300. * Push tokens onto the tokens array. This helper speeds up
  9301. * tokenizing by 1) helping us avoid backtracking as much as possible,
  9302. * and 2) helping us avoid creating extra tokens when consecutive
  9303. * characters are plain text. This improves performance and simplifies
  9304. * lookbehinds.
  9305. */
  9306. const push = tok => {
  9307. if (prev.type === 'globstar') {
  9308. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  9309. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  9310. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  9311. state.output = state.output.slice(0, -prev.output.length);
  9312. prev.type = 'star';
  9313. prev.value = '*';
  9314. prev.output = star;
  9315. state.output += prev.output;
  9316. }
  9317. }
  9318. if (extglobs.length && tok.type !== 'paren') {
  9319. extglobs[extglobs.length - 1].inner += tok.value;
  9320. }
  9321. if (tok.value || tok.output) append(tok);
  9322. if (prev && prev.type === 'text' && tok.type === 'text') {
  9323. prev.output = (prev.output || prev.value) + tok.value;
  9324. prev.value += tok.value;
  9325. return;
  9326. }
  9327. tok.prev = prev;
  9328. tokens.push(tok);
  9329. prev = tok;
  9330. };
  9331. const extglobOpen = (type, value) => {
  9332. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  9333. token.prev = prev;
  9334. token.parens = state.parens;
  9335. token.output = state.output;
  9336. const output = (opts.capture ? '(' : '') + token.open;
  9337. increment('parens');
  9338. push({ type, value, output: state.output ? '' : ONE_CHAR });
  9339. push({ type: 'paren', extglob: true, value: advance(), output });
  9340. extglobs.push(token);
  9341. };
  9342. const extglobClose = token => {
  9343. let output = token.close + (opts.capture ? ')' : '');
  9344. let rest;
  9345. if (token.type === 'negate') {
  9346. let extglobStar = star;
  9347. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  9348. extglobStar = globstar(opts);
  9349. }
  9350. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  9351. output = token.close = `)$))${extglobStar}`;
  9352. }
  9353. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  9354. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  9355. // In this case, we need to parse the string and use it in the output of the original pattern.
  9356. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  9357. //
  9358. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  9359. const expression = parse(rest, { ...options, fastpaths: false }).output;
  9360. output = token.close = `)${expression})${extglobStar})`;
  9361. }
  9362. if (token.prev.type === 'bos') {
  9363. state.negatedExtglob = true;
  9364. }
  9365. }
  9366. push({ type: 'paren', extglob: true, value, output });
  9367. decrement('parens');
  9368. };
  9369. /**
  9370. * Fast paths
  9371. */
  9372. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  9373. let backslashes = false;
  9374. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  9375. if (first === '\\') {
  9376. backslashes = true;
  9377. return m;
  9378. }
  9379. if (first === '?') {
  9380. if (esc) {
  9381. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  9382. }
  9383. if (index === 0) {
  9384. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  9385. }
  9386. return QMARK.repeat(chars.length);
  9387. }
  9388. if (first === '.') {
  9389. return DOT_LITERAL.repeat(chars.length);
  9390. }
  9391. if (first === '*') {
  9392. if (esc) {
  9393. return esc + first + (rest ? star : '');
  9394. }
  9395. return star;
  9396. }
  9397. return esc ? m : `\\${m}`;
  9398. });
  9399. if (backslashes === true) {
  9400. if (opts.unescape === true) {
  9401. output = output.replace(/\\/g, '');
  9402. } else {
  9403. output = output.replace(/\\+/g, m => {
  9404. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  9405. });
  9406. }
  9407. }
  9408. if (output === input && opts.contains === true) {
  9409. state.output = input;
  9410. return state;
  9411. }
  9412. state.output = utils.wrapOutput(output, state, options);
  9413. return state;
  9414. }
  9415. /**
  9416. * Tokenize input until we reach end-of-string
  9417. */
  9418. while (!eos()) {
  9419. value = advance();
  9420. if (value === '\u0000') {
  9421. continue;
  9422. }
  9423. /**
  9424. * Escaped characters
  9425. */
  9426. if (value === '\\') {
  9427. const next = peek();
  9428. if (next === '/' && opts.bash !== true) {
  9429. continue;
  9430. }
  9431. if (next === '.' || next === ';') {
  9432. continue;
  9433. }
  9434. if (!next) {
  9435. value += '\\';
  9436. push({ type: 'text', value });
  9437. continue;
  9438. }
  9439. // collapse slashes to reduce potential for exploits
  9440. const match = /^\\+/.exec(remaining());
  9441. let slashes = 0;
  9442. if (match && match[0].length > 2) {
  9443. slashes = match[0].length;
  9444. state.index += slashes;
  9445. if (slashes % 2 !== 0) {
  9446. value += '\\';
  9447. }
  9448. }
  9449. if (opts.unescape === true) {
  9450. value = advance();
  9451. } else {
  9452. value += advance();
  9453. }
  9454. if (state.brackets === 0) {
  9455. push({ type: 'text', value });
  9456. continue;
  9457. }
  9458. }
  9459. /**
  9460. * If we're inside a regex character class, continue
  9461. * until we reach the closing bracket.
  9462. */
  9463. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  9464. if (opts.posix !== false && value === ':') {
  9465. const inner = prev.value.slice(1);
  9466. if (inner.includes('[')) {
  9467. prev.posix = true;
  9468. if (inner.includes(':')) {
  9469. const idx = prev.value.lastIndexOf('[');
  9470. const pre = prev.value.slice(0, idx);
  9471. const rest = prev.value.slice(idx + 2);
  9472. const posix = POSIX_REGEX_SOURCE[rest];
  9473. if (posix) {
  9474. prev.value = pre + posix;
  9475. state.backtrack = true;
  9476. advance();
  9477. if (!bos.output && tokens.indexOf(prev) === 1) {
  9478. bos.output = ONE_CHAR;
  9479. }
  9480. continue;
  9481. }
  9482. }
  9483. }
  9484. }
  9485. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  9486. value = `\\${value}`;
  9487. }
  9488. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  9489. value = `\\${value}`;
  9490. }
  9491. if (opts.posix === true && value === '!' && prev.value === '[') {
  9492. value = '^';
  9493. }
  9494. prev.value += value;
  9495. append({ value });
  9496. continue;
  9497. }
  9498. /**
  9499. * If we're inside a quoted string, continue
  9500. * until we reach the closing double quote.
  9501. */
  9502. if (state.quotes === 1 && value !== '"') {
  9503. value = utils.escapeRegex(value);
  9504. prev.value += value;
  9505. append({ value });
  9506. continue;
  9507. }
  9508. /**
  9509. * Double quotes
  9510. */
  9511. if (value === '"') {
  9512. state.quotes = state.quotes === 1 ? 0 : 1;
  9513. if (opts.keepQuotes === true) {
  9514. push({ type: 'text', value });
  9515. }
  9516. continue;
  9517. }
  9518. /**
  9519. * Parentheses
  9520. */
  9521. if (value === '(') {
  9522. increment('parens');
  9523. push({ type: 'paren', value });
  9524. continue;
  9525. }
  9526. if (value === ')') {
  9527. if (state.parens === 0 && opts.strictBrackets === true) {
  9528. throw new SyntaxError(syntaxError('opening', '('));
  9529. }
  9530. const extglob = extglobs[extglobs.length - 1];
  9531. if (extglob && state.parens === extglob.parens + 1) {
  9532. extglobClose(extglobs.pop());
  9533. continue;
  9534. }
  9535. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  9536. decrement('parens');
  9537. continue;
  9538. }
  9539. /**
  9540. * Square brackets
  9541. */
  9542. if (value === '[') {
  9543. if (opts.nobracket === true || !remaining().includes(']')) {
  9544. if (opts.nobracket !== true && opts.strictBrackets === true) {
  9545. throw new SyntaxError(syntaxError('closing', ']'));
  9546. }
  9547. value = `\\${value}`;
  9548. } else {
  9549. increment('brackets');
  9550. }
  9551. push({ type: 'bracket', value });
  9552. continue;
  9553. }
  9554. if (value === ']') {
  9555. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  9556. push({ type: 'text', value, output: `\\${value}` });
  9557. continue;
  9558. }
  9559. if (state.brackets === 0) {
  9560. if (opts.strictBrackets === true) {
  9561. throw new SyntaxError(syntaxError('opening', '['));
  9562. }
  9563. push({ type: 'text', value, output: `\\${value}` });
  9564. continue;
  9565. }
  9566. decrement('brackets');
  9567. const prevValue = prev.value.slice(1);
  9568. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  9569. value = `/${value}`;
  9570. }
  9571. prev.value += value;
  9572. append({ value });
  9573. // when literal brackets are explicitly disabled
  9574. // assume we should match with a regex character class
  9575. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  9576. continue;
  9577. }
  9578. const escaped = utils.escapeRegex(prev.value);
  9579. state.output = state.output.slice(0, -prev.value.length);
  9580. // when literal brackets are explicitly enabled
  9581. // assume we should escape the brackets to match literal characters
  9582. if (opts.literalBrackets === true) {
  9583. state.output += escaped;
  9584. prev.value = escaped;
  9585. continue;
  9586. }
  9587. // when the user specifies nothing, try to match both
  9588. prev.value = `(${capture}${escaped}|${prev.value})`;
  9589. state.output += prev.value;
  9590. continue;
  9591. }
  9592. /**
  9593. * Braces
  9594. */
  9595. if (value === '{' && opts.nobrace !== true) {
  9596. increment('braces');
  9597. const open = {
  9598. type: 'brace',
  9599. value,
  9600. output: '(',
  9601. outputIndex: state.output.length,
  9602. tokensIndex: state.tokens.length
  9603. };
  9604. braces.push(open);
  9605. push(open);
  9606. continue;
  9607. }
  9608. if (value === '}') {
  9609. const brace = braces[braces.length - 1];
  9610. if (opts.nobrace === true || !brace) {
  9611. push({ type: 'text', value, output: value });
  9612. continue;
  9613. }
  9614. let output = ')';
  9615. if (brace.dots === true) {
  9616. const arr = tokens.slice();
  9617. const range = [];
  9618. for (let i = arr.length - 1; i >= 0; i--) {
  9619. tokens.pop();
  9620. if (arr[i].type === 'brace') {
  9621. break;
  9622. }
  9623. if (arr[i].type !== 'dots') {
  9624. range.unshift(arr[i].value);
  9625. }
  9626. }
  9627. output = expandRange(range, opts);
  9628. state.backtrack = true;
  9629. }
  9630. if (brace.comma !== true && brace.dots !== true) {
  9631. const out = state.output.slice(0, brace.outputIndex);
  9632. const toks = state.tokens.slice(brace.tokensIndex);
  9633. brace.value = brace.output = '\\{';
  9634. value = output = '\\}';
  9635. state.output = out;
  9636. for (const t of toks) {
  9637. state.output += (t.output || t.value);
  9638. }
  9639. }
  9640. push({ type: 'brace', value, output });
  9641. decrement('braces');
  9642. braces.pop();
  9643. continue;
  9644. }
  9645. /**
  9646. * Pipes
  9647. */
  9648. if (value === '|') {
  9649. if (extglobs.length > 0) {
  9650. extglobs[extglobs.length - 1].conditions++;
  9651. }
  9652. push({ type: 'text', value });
  9653. continue;
  9654. }
  9655. /**
  9656. * Commas
  9657. */
  9658. if (value === ',') {
  9659. let output = value;
  9660. const brace = braces[braces.length - 1];
  9661. if (brace && stack[stack.length - 1] === 'braces') {
  9662. brace.comma = true;
  9663. output = '|';
  9664. }
  9665. push({ type: 'comma', value, output });
  9666. continue;
  9667. }
  9668. /**
  9669. * Slashes
  9670. */
  9671. if (value === '/') {
  9672. // if the beginning of the glob is "./", advance the start
  9673. // to the current index, and don't add the "./" characters
  9674. // to the state. This greatly simplifies lookbehinds when
  9675. // checking for BOS characters like "!" and "." (not "./")
  9676. if (prev.type === 'dot' && state.index === state.start + 1) {
  9677. state.start = state.index + 1;
  9678. state.consumed = '';
  9679. state.output = '';
  9680. tokens.pop();
  9681. prev = bos; // reset "prev" to the first token
  9682. continue;
  9683. }
  9684. push({ type: 'slash', value, output: SLASH_LITERAL });
  9685. continue;
  9686. }
  9687. /**
  9688. * Dots
  9689. */
  9690. if (value === '.') {
  9691. if (state.braces > 0 && prev.type === 'dot') {
  9692. if (prev.value === '.') prev.output = DOT_LITERAL;
  9693. const brace = braces[braces.length - 1];
  9694. prev.type = 'dots';
  9695. prev.output += value;
  9696. prev.value += value;
  9697. brace.dots = true;
  9698. continue;
  9699. }
  9700. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  9701. push({ type: 'text', value, output: DOT_LITERAL });
  9702. continue;
  9703. }
  9704. push({ type: 'dot', value, output: DOT_LITERAL });
  9705. continue;
  9706. }
  9707. /**
  9708. * Question marks
  9709. */
  9710. if (value === '?') {
  9711. const isGroup = prev && prev.value === '(';
  9712. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9713. extglobOpen('qmark', value);
  9714. continue;
  9715. }
  9716. if (prev && prev.type === 'paren') {
  9717. const next = peek();
  9718. let output = value;
  9719. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  9720. output = `\\${value}`;
  9721. }
  9722. push({ type: 'text', value, output });
  9723. continue;
  9724. }
  9725. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  9726. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  9727. continue;
  9728. }
  9729. push({ type: 'qmark', value, output: QMARK });
  9730. continue;
  9731. }
  9732. /**
  9733. * Exclamation
  9734. */
  9735. if (value === '!') {
  9736. if (opts.noextglob !== true && peek() === '(') {
  9737. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  9738. extglobOpen('negate', value);
  9739. continue;
  9740. }
  9741. }
  9742. if (opts.nonegate !== true && state.index === 0) {
  9743. negate();
  9744. continue;
  9745. }
  9746. }
  9747. /**
  9748. * Plus
  9749. */
  9750. if (value === '+') {
  9751. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9752. extglobOpen('plus', value);
  9753. continue;
  9754. }
  9755. if ((prev && prev.value === '(') || opts.regex === false) {
  9756. push({ type: 'plus', value, output: PLUS_LITERAL });
  9757. continue;
  9758. }
  9759. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  9760. push({ type: 'plus', value });
  9761. continue;
  9762. }
  9763. push({ type: 'plus', value: PLUS_LITERAL });
  9764. continue;
  9765. }
  9766. /**
  9767. * Plain text
  9768. */
  9769. if (value === '@') {
  9770. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9771. push({ type: 'at', extglob: true, value, output: '' });
  9772. continue;
  9773. }
  9774. push({ type: 'text', value });
  9775. continue;
  9776. }
  9777. /**
  9778. * Plain text
  9779. */
  9780. if (value !== '*') {
  9781. if (value === '$' || value === '^') {
  9782. value = `\\${value}`;
  9783. }
  9784. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  9785. if (match) {
  9786. value += match[0];
  9787. state.index += match[0].length;
  9788. }
  9789. push({ type: 'text', value });
  9790. continue;
  9791. }
  9792. /**
  9793. * Stars
  9794. */
  9795. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  9796. prev.type = 'star';
  9797. prev.star = true;
  9798. prev.value += value;
  9799. prev.output = star;
  9800. state.backtrack = true;
  9801. state.globstar = true;
  9802. consume(value);
  9803. continue;
  9804. }
  9805. let rest = remaining();
  9806. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  9807. extglobOpen('star', value);
  9808. continue;
  9809. }
  9810. if (prev.type === 'star') {
  9811. if (opts.noglobstar === true) {
  9812. consume(value);
  9813. continue;
  9814. }
  9815. const prior = prev.prev;
  9816. const before = prior.prev;
  9817. const isStart = prior.type === 'slash' || prior.type === 'bos';
  9818. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  9819. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  9820. push({ type: 'star', value, output: '' });
  9821. continue;
  9822. }
  9823. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  9824. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  9825. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  9826. push({ type: 'star', value, output: '' });
  9827. continue;
  9828. }
  9829. // strip consecutive `/**/`
  9830. while (rest.slice(0, 3) === '/**') {
  9831. const after = input[state.index + 4];
  9832. if (after && after !== '/') {
  9833. break;
  9834. }
  9835. rest = rest.slice(3);
  9836. consume('/**', 3);
  9837. }
  9838. if (prior.type === 'bos' && eos()) {
  9839. prev.type = 'globstar';
  9840. prev.value += value;
  9841. prev.output = globstar(opts);
  9842. state.output = prev.output;
  9843. state.globstar = true;
  9844. consume(value);
  9845. continue;
  9846. }
  9847. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  9848. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9849. prior.output = `(?:${prior.output}`;
  9850. prev.type = 'globstar';
  9851. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  9852. prev.value += value;
  9853. state.globstar = true;
  9854. state.output += prior.output + prev.output;
  9855. consume(value);
  9856. continue;
  9857. }
  9858. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  9859. const end = rest[1] !== void 0 ? '|$' : '';
  9860. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9861. prior.output = `(?:${prior.output}`;
  9862. prev.type = 'globstar';
  9863. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  9864. prev.value += value;
  9865. state.output += prior.output + prev.output;
  9866. state.globstar = true;
  9867. consume(value + advance());
  9868. push({ type: 'slash', value: '/', output: '' });
  9869. continue;
  9870. }
  9871. if (prior.type === 'bos' && rest[0] === '/') {
  9872. prev.type = 'globstar';
  9873. prev.value += value;
  9874. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  9875. state.output = prev.output;
  9876. state.globstar = true;
  9877. consume(value + advance());
  9878. push({ type: 'slash', value: '/', output: '' });
  9879. continue;
  9880. }
  9881. // remove single star from output
  9882. state.output = state.output.slice(0, -prev.output.length);
  9883. // reset previous token to globstar
  9884. prev.type = 'globstar';
  9885. prev.output = globstar(opts);
  9886. prev.value += value;
  9887. // reset output with globstar
  9888. state.output += prev.output;
  9889. state.globstar = true;
  9890. consume(value);
  9891. continue;
  9892. }
  9893. const token = { type: 'star', value, output: star };
  9894. if (opts.bash === true) {
  9895. token.output = '.*?';
  9896. if (prev.type === 'bos' || prev.type === 'slash') {
  9897. token.output = nodot + token.output;
  9898. }
  9899. push(token);
  9900. continue;
  9901. }
  9902. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  9903. token.output = value;
  9904. push(token);
  9905. continue;
  9906. }
  9907. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  9908. if (prev.type === 'dot') {
  9909. state.output += NO_DOT_SLASH;
  9910. prev.output += NO_DOT_SLASH;
  9911. } else if (opts.dot === true) {
  9912. state.output += NO_DOTS_SLASH;
  9913. prev.output += NO_DOTS_SLASH;
  9914. } else {
  9915. state.output += nodot;
  9916. prev.output += nodot;
  9917. }
  9918. if (peek() !== '*') {
  9919. state.output += ONE_CHAR;
  9920. prev.output += ONE_CHAR;
  9921. }
  9922. }
  9923. push(token);
  9924. }
  9925. while (state.brackets > 0) {
  9926. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  9927. state.output = utils.escapeLast(state.output, '[');
  9928. decrement('brackets');
  9929. }
  9930. while (state.parens > 0) {
  9931. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  9932. state.output = utils.escapeLast(state.output, '(');
  9933. decrement('parens');
  9934. }
  9935. while (state.braces > 0) {
  9936. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  9937. state.output = utils.escapeLast(state.output, '{');
  9938. decrement('braces');
  9939. }
  9940. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  9941. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  9942. }
  9943. // rebuild the output if we had to backtrack at any point
  9944. if (state.backtrack === true) {
  9945. state.output = '';
  9946. for (const token of state.tokens) {
  9947. state.output += token.output != null ? token.output : token.value;
  9948. if (token.suffix) {
  9949. state.output += token.suffix;
  9950. }
  9951. }
  9952. }
  9953. return state;
  9954. };
  9955. /**
  9956. * Fast paths for creating regular expressions for common glob patterns.
  9957. * This can significantly speed up processing and has very little downside
  9958. * impact when none of the fast paths match.
  9959. */
  9960. parse.fastpaths = (input, options) => {
  9961. const opts = { ...options };
  9962. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  9963. const len = input.length;
  9964. if (len > max) {
  9965. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  9966. }
  9967. input = REPLACEMENTS[input] || input;
  9968. // create constants based on platform, for windows or posix
  9969. const {
  9970. DOT_LITERAL,
  9971. SLASH_LITERAL,
  9972. ONE_CHAR,
  9973. DOTS_SLASH,
  9974. NO_DOT,
  9975. NO_DOTS,
  9976. NO_DOTS_SLASH,
  9977. STAR,
  9978. START_ANCHOR
  9979. } = constants.globChars(opts.windows);
  9980. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  9981. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  9982. const capture = opts.capture ? '' : '?:';
  9983. const state = { negated: false, prefix: '' };
  9984. let star = opts.bash === true ? '.*?' : STAR;
  9985. if (opts.capture) {
  9986. star = `(${star})`;
  9987. }
  9988. const globstar = opts => {
  9989. if (opts.noglobstar === true) return star;
  9990. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  9991. };
  9992. const create = str => {
  9993. switch (str) {
  9994. case '*':
  9995. return `${nodot}${ONE_CHAR}${star}`;
  9996. case '.*':
  9997. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  9998. case '*.*':
  9999. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10000. case '*/*':
  10001. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  10002. case '**':
  10003. return nodot + globstar(opts);
  10004. case '**/*':
  10005. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  10006. case '**/*.*':
  10007. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10008. case '**/.*':
  10009. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  10010. default: {
  10011. const match = /^(.*?)\.(\w+)$/.exec(str);
  10012. if (!match) return;
  10013. const source = create(match[1]);
  10014. if (!source) return;
  10015. return source + DOT_LITERAL + match[2];
  10016. }
  10017. }
  10018. };
  10019. const output = utils.removePrefix(input, state);
  10020. let source = create(output);
  10021. if (source && opts.strictSlashes !== true) {
  10022. source += `${SLASH_LITERAL}?`;
  10023. }
  10024. return source;
  10025. };
  10026. parse_1 = parse;
  10027. return parse_1;
  10028. }
  10029. var picomatch_1$1;
  10030. var hasRequiredPicomatch$1;
  10031. function requirePicomatch$1 () {
  10032. if (hasRequiredPicomatch$1) return picomatch_1$1;
  10033. hasRequiredPicomatch$1 = 1;
  10034. const scan = /*@__PURE__*/ requireScan();
  10035. const parse = /*@__PURE__*/ requireParse();
  10036. const utils = /*@__PURE__*/ requireUtils();
  10037. const constants = /*@__PURE__*/ requireConstants();
  10038. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  10039. /**
  10040. * Creates a matcher function from one or more glob patterns. The
  10041. * returned function takes a string to match as its first argument,
  10042. * and returns true if the string is a match. The returned matcher
  10043. * function also takes a boolean as the second argument that, when true,
  10044. * returns an object with additional information.
  10045. *
  10046. * ```js
  10047. * const picomatch = require('picomatch');
  10048. * // picomatch(glob[, options]);
  10049. *
  10050. * const isMatch = picomatch('*.!(*a)');
  10051. * console.log(isMatch('a.a')); //=> false
  10052. * console.log(isMatch('a.b')); //=> true
  10053. * ```
  10054. * @name picomatch
  10055. * @param {String|Array} `globs` One or more glob patterns.
  10056. * @param {Object=} `options`
  10057. * @return {Function=} Returns a matcher function.
  10058. * @api public
  10059. */
  10060. const picomatch = (glob, options, returnState = false) => {
  10061. if (Array.isArray(glob)) {
  10062. const fns = glob.map(input => picomatch(input, options, returnState));
  10063. const arrayMatcher = str => {
  10064. for (const isMatch of fns) {
  10065. const state = isMatch(str);
  10066. if (state) return state;
  10067. }
  10068. return false;
  10069. };
  10070. return arrayMatcher;
  10071. }
  10072. const isState = isObject(glob) && glob.tokens && glob.input;
  10073. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  10074. throw new TypeError('Expected pattern to be a non-empty string');
  10075. }
  10076. const opts = options || {};
  10077. const posix = opts.windows;
  10078. const regex = isState
  10079. ? picomatch.compileRe(glob, options)
  10080. : picomatch.makeRe(glob, options, false, true);
  10081. const state = regex.state;
  10082. delete regex.state;
  10083. let isIgnored = () => false;
  10084. if (opts.ignore) {
  10085. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  10086. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  10087. }
  10088. const matcher = (input, returnObject = false) => {
  10089. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  10090. const result = { glob, state, regex, posix, input, output, match, isMatch };
  10091. if (typeof opts.onResult === 'function') {
  10092. opts.onResult(result);
  10093. }
  10094. if (isMatch === false) {
  10095. result.isMatch = false;
  10096. return returnObject ? result : false;
  10097. }
  10098. if (isIgnored(input)) {
  10099. if (typeof opts.onIgnore === 'function') {
  10100. opts.onIgnore(result);
  10101. }
  10102. result.isMatch = false;
  10103. return returnObject ? result : false;
  10104. }
  10105. if (typeof opts.onMatch === 'function') {
  10106. opts.onMatch(result);
  10107. }
  10108. return returnObject ? result : true;
  10109. };
  10110. if (returnState) {
  10111. matcher.state = state;
  10112. }
  10113. return matcher;
  10114. };
  10115. /**
  10116. * Test `input` with the given `regex`. This is used by the main
  10117. * `picomatch()` function to test the input string.
  10118. *
  10119. * ```js
  10120. * const picomatch = require('picomatch');
  10121. * // picomatch.test(input, regex[, options]);
  10122. *
  10123. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  10124. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  10125. * ```
  10126. * @param {String} `input` String to test.
  10127. * @param {RegExp} `regex`
  10128. * @return {Object} Returns an object with matching info.
  10129. * @api public
  10130. */
  10131. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  10132. if (typeof input !== 'string') {
  10133. throw new TypeError('Expected input to be a string');
  10134. }
  10135. if (input === '') {
  10136. return { isMatch: false, output: '' };
  10137. }
  10138. const opts = options || {};
  10139. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  10140. let match = input === glob;
  10141. let output = (match && format) ? format(input) : input;
  10142. if (match === false) {
  10143. output = format ? format(input) : input;
  10144. match = output === glob;
  10145. }
  10146. if (match === false || opts.capture === true) {
  10147. if (opts.matchBase === true || opts.basename === true) {
  10148. match = picomatch.matchBase(input, regex, options, posix);
  10149. } else {
  10150. match = regex.exec(output);
  10151. }
  10152. }
  10153. return { isMatch: Boolean(match), match, output };
  10154. };
  10155. /**
  10156. * Match the basename of a filepath.
  10157. *
  10158. * ```js
  10159. * const picomatch = require('picomatch');
  10160. * // picomatch.matchBase(input, glob[, options]);
  10161. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  10162. * ```
  10163. * @param {String} `input` String to test.
  10164. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  10165. * @return {Boolean}
  10166. * @api public
  10167. */
  10168. picomatch.matchBase = (input, glob, options) => {
  10169. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  10170. return regex.test(utils.basename(input));
  10171. };
  10172. /**
  10173. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  10174. *
  10175. * ```js
  10176. * const picomatch = require('picomatch');
  10177. * // picomatch.isMatch(string, patterns[, options]);
  10178. *
  10179. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  10180. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  10181. * ```
  10182. * @param {String|Array} str The string to test.
  10183. * @param {String|Array} patterns One or more glob patterns to use for matching.
  10184. * @param {Object} [options] See available [options](#options).
  10185. * @return {Boolean} Returns true if any patterns match `str`
  10186. * @api public
  10187. */
  10188. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  10189. /**
  10190. * Parse a glob pattern to create the source string for a regular
  10191. * expression.
  10192. *
  10193. * ```js
  10194. * const picomatch = require('picomatch');
  10195. * const result = picomatch.parse(pattern[, options]);
  10196. * ```
  10197. * @param {String} `pattern`
  10198. * @param {Object} `options`
  10199. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  10200. * @api public
  10201. */
  10202. picomatch.parse = (pattern, options) => {
  10203. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  10204. return parse(pattern, { ...options, fastpaths: false });
  10205. };
  10206. /**
  10207. * Scan a glob pattern to separate the pattern into segments.
  10208. *
  10209. * ```js
  10210. * const picomatch = require('picomatch');
  10211. * // picomatch.scan(input[, options]);
  10212. *
  10213. * const result = picomatch.scan('!./foo/*.js');
  10214. * console.log(result);
  10215. * { prefix: '!./',
  10216. * input: '!./foo/*.js',
  10217. * start: 3,
  10218. * base: 'foo',
  10219. * glob: '*.js',
  10220. * isBrace: false,
  10221. * isBracket: false,
  10222. * isGlob: true,
  10223. * isExtglob: false,
  10224. * isGlobstar: false,
  10225. * negated: true }
  10226. * ```
  10227. * @param {String} `input` Glob pattern to scan.
  10228. * @param {Object} `options`
  10229. * @return {Object} Returns an object with
  10230. * @api public
  10231. */
  10232. picomatch.scan = (input, options) => scan(input, options);
  10233. /**
  10234. * Compile a regular expression from the `state` object returned by the
  10235. * [parse()](#parse) method.
  10236. *
  10237. * @param {Object} `state`
  10238. * @param {Object} `options`
  10239. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  10240. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  10241. * @return {RegExp}
  10242. * @api public
  10243. */
  10244. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  10245. if (returnOutput === true) {
  10246. return state.output;
  10247. }
  10248. const opts = options || {};
  10249. const prepend = opts.contains ? '' : '^';
  10250. const append = opts.contains ? '' : '$';
  10251. let source = `${prepend}(?:${state.output})${append}`;
  10252. if (state && state.negated === true) {
  10253. source = `^(?!${source}).*$`;
  10254. }
  10255. const regex = picomatch.toRegex(source, options);
  10256. if (returnState === true) {
  10257. regex.state = state;
  10258. }
  10259. return regex;
  10260. };
  10261. /**
  10262. * Create a regular expression from a parsed glob pattern.
  10263. *
  10264. * ```js
  10265. * const picomatch = require('picomatch');
  10266. * const state = picomatch.parse('*.js');
  10267. * // picomatch.compileRe(state[, options]);
  10268. *
  10269. * console.log(picomatch.compileRe(state));
  10270. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10271. * ```
  10272. * @param {String} `state` The object returned from the `.parse` method.
  10273. * @param {Object} `options`
  10274. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  10275. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  10276. * @return {RegExp} Returns a regex created from the given pattern.
  10277. * @api public
  10278. */
  10279. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  10280. if (!input || typeof input !== 'string') {
  10281. throw new TypeError('Expected a non-empty string');
  10282. }
  10283. let parsed = { negated: false, fastpaths: true };
  10284. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  10285. parsed.output = parse.fastpaths(input, options);
  10286. }
  10287. if (!parsed.output) {
  10288. parsed = parse(input, options);
  10289. }
  10290. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  10291. };
  10292. /**
  10293. * Create a regular expression from the given regex source string.
  10294. *
  10295. * ```js
  10296. * const picomatch = require('picomatch');
  10297. * // picomatch.toRegex(source[, options]);
  10298. *
  10299. * const { output } = picomatch.parse('*.js');
  10300. * console.log(picomatch.toRegex(output));
  10301. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10302. * ```
  10303. * @param {String} `source` Regular expression source string.
  10304. * @param {Object} `options`
  10305. * @return {RegExp}
  10306. * @api public
  10307. */
  10308. picomatch.toRegex = (source, options) => {
  10309. try {
  10310. const opts = options || {};
  10311. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  10312. } catch (err) {
  10313. if (options && options.debug === true) throw err;
  10314. return /$^/;
  10315. }
  10316. };
  10317. /**
  10318. * Picomatch constants.
  10319. * @return {Object}
  10320. */
  10321. picomatch.constants = constants;
  10322. /**
  10323. * Expose "picomatch"
  10324. */
  10325. picomatch_1$1 = picomatch;
  10326. return picomatch_1$1;
  10327. }
  10328. var picomatch_1;
  10329. var hasRequiredPicomatch;
  10330. function requirePicomatch () {
  10331. if (hasRequiredPicomatch) return picomatch_1;
  10332. hasRequiredPicomatch = 1;
  10333. const pico = /*@__PURE__*/ requirePicomatch$1();
  10334. const utils = /*@__PURE__*/ requireUtils();
  10335. function picomatch(glob, options, returnState = false) {
  10336. // default to os.platform()
  10337. if (options && (options.windows === null || options.windows === undefined)) {
  10338. // don't mutate the original options object
  10339. options = { ...options, windows: utils.isWindows() };
  10340. }
  10341. return pico(glob, options, returnState);
  10342. }
  10343. Object.assign(picomatch, pico);
  10344. picomatch_1 = picomatch;
  10345. return picomatch_1;
  10346. }
  10347. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  10348. const picomatch = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  10349. const extractors = {
  10350. ArrayPattern(names, param) {
  10351. for (const element of param.elements) {
  10352. if (element)
  10353. extractors[element.type](names, element);
  10354. }
  10355. },
  10356. AssignmentPattern(names, param) {
  10357. extractors[param.left.type](names, param.left);
  10358. },
  10359. Identifier(names, param) {
  10360. names.push(param.name);
  10361. },
  10362. MemberExpression() { },
  10363. ObjectPattern(names, param) {
  10364. for (const prop of param.properties) {
  10365. // @ts-ignore Typescript reports that this is not a valid type
  10366. if (prop.type === 'RestElement') {
  10367. extractors.RestElement(names, prop);
  10368. }
  10369. else {
  10370. extractors[prop.value.type](names, prop.value);
  10371. }
  10372. }
  10373. },
  10374. RestElement(names, param) {
  10375. extractors[param.argument.type](names, param.argument);
  10376. }
  10377. };
  10378. const extractAssignedNames = function extractAssignedNames(param) {
  10379. const names = [];
  10380. extractors[param.type](names, param);
  10381. return names;
  10382. };
  10383. // Helper since Typescript can't detect readonly arrays with Array.isArray
  10384. function isArray(arg) {
  10385. return Array.isArray(arg);
  10386. }
  10387. function ensureArray$1(thing) {
  10388. if (isArray(thing))
  10389. return thing;
  10390. if (thing == null)
  10391. return [];
  10392. return [thing];
  10393. }
  10394. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
  10395. const normalizePath = function normalizePath(filename) {
  10396. return filename.replace(normalizePathRegExp, posix.sep);
  10397. };
  10398. function getMatcherString$1(id, resolutionBase) {
  10399. if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
  10400. return normalizePath(id);
  10401. }
  10402. // resolve('') is valid and will default to process.cwd()
  10403. const basePath = normalizePath(resolve(resolutionBase || ''))
  10404. // escape all possible (posix + win) path characters that might interfere with regex
  10405. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  10406. // Note that we use posix.join because:
  10407. // 1. the basePath has been normalized to use /
  10408. // 2. the incoming glob (id) matcher, also uses /
  10409. // otherwise Node will force backslash (\) on windows
  10410. return posix.join(basePath, normalizePath(id));
  10411. }
  10412. const createFilter$1 = function createFilter(include, exclude, options) {
  10413. const resolutionBase = options && options.resolve;
  10414. const getMatcher = (id) => id instanceof RegExp
  10415. ? id
  10416. : {
  10417. test: (what) => {
  10418. // this refactor is a tad overly verbose but makes for easy debugging
  10419. const pattern = getMatcherString$1(id, resolutionBase);
  10420. const fn = picomatch(pattern, { dot: true });
  10421. const result = fn(what);
  10422. return result;
  10423. }
  10424. };
  10425. const includeMatchers = ensureArray$1(include).map(getMatcher);
  10426. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  10427. if (!includeMatchers.length && !excludeMatchers.length)
  10428. return (id) => typeof id === 'string' && !id.includes('\0');
  10429. return function result(id) {
  10430. if (typeof id !== 'string')
  10431. return false;
  10432. if (id.includes('\0'))
  10433. return false;
  10434. const pathId = normalizePath(id);
  10435. for (let i = 0; i < excludeMatchers.length; ++i) {
  10436. const matcher = excludeMatchers[i];
  10437. if (matcher instanceof RegExp) {
  10438. matcher.lastIndex = 0;
  10439. }
  10440. if (matcher.test(pathId))
  10441. return false;
  10442. }
  10443. for (let i = 0; i < includeMatchers.length; ++i) {
  10444. const matcher = includeMatchers[i];
  10445. if (matcher instanceof RegExp) {
  10446. matcher.lastIndex = 0;
  10447. }
  10448. if (matcher.test(pathId))
  10449. return true;
  10450. }
  10451. return !includeMatchers.length;
  10452. };
  10453. };
  10454. const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  10455. const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  10456. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  10457. forbiddenIdentifiers.add('');
  10458. class ArrayPattern extends NodeBase {
  10459. addExportedVariables(variables, exportNamesByVariable) {
  10460. for (const element of this.elements) {
  10461. element?.addExportedVariables(variables, exportNamesByVariable);
  10462. }
  10463. }
  10464. declare(kind, destructuredInitPath, init) {
  10465. const variables = [];
  10466. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10467. for (const element of this.elements) {
  10468. if (element !== null) {
  10469. variables.push(...element.declare(kind, includedPatternPath, init));
  10470. }
  10471. }
  10472. return variables;
  10473. }
  10474. deoptimizeAssignment(destructuredInitPath, init) {
  10475. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10476. for (const element of this.elements) {
  10477. element?.deoptimizeAssignment(includedPatternPath, init);
  10478. }
  10479. }
  10480. // Patterns can only be deoptimized at the empty path at the moment
  10481. deoptimizePath() {
  10482. for (const element of this.elements) {
  10483. element?.deoptimizePath(EMPTY_PATH);
  10484. }
  10485. }
  10486. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10487. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10488. for (const element of this.elements) {
  10489. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  10490. return true;
  10491. }
  10492. }
  10493. return false;
  10494. }
  10495. // Patterns are only checked at the empty path at the moment
  10496. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  10497. for (const element of this.elements) {
  10498. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10499. return true;
  10500. }
  10501. return false;
  10502. }
  10503. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10504. let included = false;
  10505. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10506. for (const element of this.elements) {
  10507. if (element) {
  10508. element.included ||= included;
  10509. included =
  10510. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  10511. }
  10512. }
  10513. if (included) {
  10514. // This is necessary so that if any pattern element is included, all are
  10515. // included for proper deconflicting
  10516. for (const element of this.elements) {
  10517. if (element && !element.included) {
  10518. element.included = true;
  10519. element.includeDestructuredIfNecessary(context, includedPatternPath, init);
  10520. }
  10521. }
  10522. }
  10523. return (this.included ||= included);
  10524. }
  10525. markDeclarationReached() {
  10526. for (const element of this.elements) {
  10527. element?.markDeclarationReached();
  10528. }
  10529. }
  10530. }
  10531. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  10532. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  10533. ? destructuredInitPath
  10534. : [...destructuredInitPath, UnknownInteger];
  10535. class ArrowFunctionExpression extends FunctionBase {
  10536. constructor() {
  10537. super(...arguments);
  10538. this.objectEntity = null;
  10539. }
  10540. get expression() {
  10541. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  10542. }
  10543. set expression(value) {
  10544. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  10545. }
  10546. createScope(parentScope) {
  10547. this.scope = new ReturnValueScope(parentScope, false);
  10548. }
  10549. hasEffects() {
  10550. return false;
  10551. }
  10552. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10553. if (this.annotationNoSideEffects &&
  10554. path.length === 0 &&
  10555. interaction.type === INTERACTION_CALLED) {
  10556. return false;
  10557. }
  10558. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  10559. return true;
  10560. }
  10561. if (interaction.type === INTERACTION_CALLED) {
  10562. const { ignore, brokenFlow } = context;
  10563. context.ignore = {
  10564. breaks: false,
  10565. continues: false,
  10566. labels: new Set(),
  10567. returnYield: true,
  10568. this: false
  10569. };
  10570. if (this.body.hasEffects(context))
  10571. return true;
  10572. context.ignore = ignore;
  10573. context.brokenFlow = brokenFlow;
  10574. }
  10575. return false;
  10576. }
  10577. onlyFunctionCallUsed() {
  10578. const isIIFE = this.parent.type === CallExpression$1 &&
  10579. this.parent.callee === this;
  10580. return isIIFE || super.onlyFunctionCallUsed();
  10581. }
  10582. include(context, includeChildrenRecursively) {
  10583. super.include(context, includeChildrenRecursively);
  10584. for (const parameter of this.params) {
  10585. if (!(parameter instanceof Identifier)) {
  10586. parameter.include(context, includeChildrenRecursively);
  10587. }
  10588. }
  10589. }
  10590. includeNode(context) {
  10591. this.included = true;
  10592. this.body.includePath(UNKNOWN_PATH, context);
  10593. for (const parameter of this.params) {
  10594. if (!(parameter instanceof Identifier)) {
  10595. parameter.includePath(UNKNOWN_PATH, context);
  10596. }
  10597. }
  10598. }
  10599. getObjectEntity() {
  10600. if (this.objectEntity !== null) {
  10601. return this.objectEntity;
  10602. }
  10603. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  10604. }
  10605. }
  10606. class ObjectPattern extends NodeBase {
  10607. addExportedVariables(variables, exportNamesByVariable) {
  10608. for (const property of this.properties) {
  10609. if (property.type === Property$1) {
  10610. property.value.addExportedVariables(variables, exportNamesByVariable);
  10611. }
  10612. else {
  10613. property.argument.addExportedVariables(variables, exportNamesByVariable);
  10614. }
  10615. }
  10616. }
  10617. declare(kind, destructuredInitPath, init) {
  10618. const variables = [];
  10619. for (const property of this.properties) {
  10620. variables.push(...property.declare(kind, destructuredInitPath, init));
  10621. }
  10622. return variables;
  10623. }
  10624. deoptimizeAssignment(destructuredInitPath, init) {
  10625. for (const property of this.properties) {
  10626. property.deoptimizeAssignment(destructuredInitPath, init);
  10627. }
  10628. }
  10629. deoptimizePath(path) {
  10630. if (path.length === 0) {
  10631. for (const property of this.properties) {
  10632. property.deoptimizePath(path);
  10633. }
  10634. }
  10635. }
  10636. hasEffectsOnInteractionAtPath(
  10637. // At the moment, this is only triggered for assignment left-hand sides,
  10638. // where the path is empty
  10639. _path, interaction, context) {
  10640. for (const property of this.properties) {
  10641. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10642. return true;
  10643. }
  10644. return false;
  10645. }
  10646. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10647. for (const property of this.properties) {
  10648. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  10649. return true;
  10650. }
  10651. return false;
  10652. }
  10653. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10654. if (!this.properties.length)
  10655. return false;
  10656. const lastProperty = this.properties.at(-1);
  10657. const lastPropertyIncluded = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  10658. const lastPropertyIsRestElement = lastProperty.type === RestElement$1;
  10659. let included = lastPropertyIsRestElement ? lastPropertyIncluded : false;
  10660. for (const property of this.properties.slice(0, -1)) {
  10661. if (lastPropertyIsRestElement && lastPropertyIncluded) {
  10662. property.includeNode(context);
  10663. }
  10664. included =
  10665. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  10666. }
  10667. return (this.included ||= included);
  10668. }
  10669. markDeclarationReached() {
  10670. for (const property of this.properties) {
  10671. property.markDeclarationReached();
  10672. }
  10673. }
  10674. render(code, options) {
  10675. if (this.properties.length > 0) {
  10676. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  10677. let lastSeparatorPos = null;
  10678. for (const { node, separator, start, end } of separatedNodes) {
  10679. if (!node.included) {
  10680. treeshakeNode(node, code, start, end);
  10681. continue;
  10682. }
  10683. lastSeparatorPos = separator;
  10684. node.render(code, options);
  10685. }
  10686. if (lastSeparatorPos) {
  10687. code.remove(lastSeparatorPos, this.end - 1);
  10688. }
  10689. }
  10690. }
  10691. }
  10692. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  10693. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  10694. class AssignmentExpression extends NodeBase {
  10695. hasEffects(context) {
  10696. const { deoptimized, left, operator, right } = this;
  10697. if (!deoptimized)
  10698. this.applyDeoptimizations();
  10699. // MemberExpressions do not access the property before assignments if the
  10700. // operator is '='.
  10701. return (right.hasEffects(context) ||
  10702. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  10703. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  10704. }
  10705. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10706. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  10707. }
  10708. include(context, includeChildrenRecursively) {
  10709. const { deoptimized, left, right, operator } = this;
  10710. if (!deoptimized)
  10711. this.applyDeoptimizations();
  10712. if (!this.included)
  10713. this.includeNode(context);
  10714. const hasEffectsContext = createHasEffectsContext();
  10715. if (includeChildrenRecursively ||
  10716. operator !== '=' ||
  10717. left.included ||
  10718. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  10719. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  10720. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  10721. }
  10722. right.include(context, includeChildrenRecursively);
  10723. }
  10724. includeNode(context) {
  10725. this.included = true;
  10726. if (!this.deoptimized)
  10727. this.applyDeoptimizations();
  10728. this.right.includePath(UNKNOWN_PATH, context);
  10729. }
  10730. initialise() {
  10731. super.initialise();
  10732. if (this.left instanceof Identifier) {
  10733. const variable = this.scope.variables.get(this.left.name);
  10734. if (variable?.kind === 'const') {
  10735. this.scope.context.error(logConstVariableReassignError(), this.left.start);
  10736. }
  10737. }
  10738. this.left.setAssignedValue(this.right);
  10739. }
  10740. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10741. const { left, right, start, end, parent } = this;
  10742. if (left.included) {
  10743. left.render(code, options);
  10744. right.render(code, options);
  10745. }
  10746. else {
  10747. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  10748. code.remove(start, inclusionStart);
  10749. if (preventASI) {
  10750. removeLineBreaks(code, inclusionStart, right.start);
  10751. }
  10752. right.render(code, options, {
  10753. renderedParentType: renderedParentType || parent.type,
  10754. renderedSurroundingElement: renderedSurroundingElement || parent.type
  10755. });
  10756. }
  10757. if (options.format === 'system') {
  10758. if (left instanceof Identifier) {
  10759. const variable = left.variable;
  10760. const exportNames = options.exportNamesByVariable.get(variable);
  10761. if (exportNames) {
  10762. if (exportNames.length === 1) {
  10763. renderSystemExportExpression(variable, start, end, code, options);
  10764. }
  10765. else {
  10766. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  10767. }
  10768. return;
  10769. }
  10770. }
  10771. else {
  10772. const systemPatternExports = [];
  10773. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  10774. if (systemPatternExports.length > 0) {
  10775. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  10776. return;
  10777. }
  10778. }
  10779. }
  10780. if (left.included &&
  10781. left instanceof ObjectPattern &&
  10782. (renderedSurroundingElement === ExpressionStatement$1 ||
  10783. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  10784. code.appendRight(start, '(');
  10785. code.prependLeft(end, ')');
  10786. }
  10787. }
  10788. applyDeoptimizations() {
  10789. this.deoptimized = true;
  10790. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  10791. this.scope.context.requestTreeshakingPass();
  10792. }
  10793. }
  10794. class AssignmentPattern extends NodeBase {
  10795. addExportedVariables(variables, exportNamesByVariable) {
  10796. this.left.addExportedVariables(variables, exportNamesByVariable);
  10797. }
  10798. declare(kind, destructuredInitPath, init) {
  10799. return this.left.declare(kind, destructuredInitPath, init);
  10800. }
  10801. deoptimizeAssignment(destructuredInitPath, init) {
  10802. this.left.deoptimizeAssignment(destructuredInitPath, init);
  10803. }
  10804. deoptimizePath(path) {
  10805. if (path.length === 0) {
  10806. this.left.deoptimizePath(path);
  10807. }
  10808. }
  10809. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10810. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  10811. }
  10812. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10813. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  10814. }
  10815. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10816. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  10817. this.included;
  10818. if ((included ||= this.right.shouldBeIncluded(context))) {
  10819. this.right.include(context, false);
  10820. if (!this.left.included) {
  10821. this.left.included = true;
  10822. // Unfortunately, we need to include the left side again now, so that
  10823. // any declared variables are properly included.
  10824. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  10825. }
  10826. }
  10827. return (this.included = included);
  10828. }
  10829. includeNode(context) {
  10830. this.included = true;
  10831. if (!this.deoptimized)
  10832. this.applyDeoptimizations();
  10833. this.right.includePath(UNKNOWN_PATH, context);
  10834. }
  10835. markDeclarationReached() {
  10836. this.left.markDeclarationReached();
  10837. }
  10838. render(code, options, { isShorthandProperty } = BLANK) {
  10839. this.left.render(code, options, { isShorthandProperty });
  10840. this.right.render(code, options);
  10841. }
  10842. applyDeoptimizations() {
  10843. this.deoptimized = true;
  10844. this.left.deoptimizePath(EMPTY_PATH);
  10845. this.right.deoptimizePath(UNKNOWN_PATH);
  10846. this.scope.context.requestTreeshakingPass();
  10847. }
  10848. }
  10849. class AwaitExpression extends NodeBase {
  10850. get isTopLevelAwait() {
  10851. return isFlagSet(this.flags, 134217728 /* Flag.isTopLevelAwait */);
  10852. }
  10853. set isTopLevelAwait(value) {
  10854. this.flags = setFlag(this.flags, 134217728 /* Flag.isTopLevelAwait */, value);
  10855. }
  10856. hasEffects() {
  10857. if (!this.deoptimized)
  10858. this.applyDeoptimizations();
  10859. return true;
  10860. }
  10861. include(context, includeChildrenRecursively) {
  10862. if (!this.included)
  10863. this.includeNode(context);
  10864. this.argument.include({ ...context, withinTopLevelAwait: this.isTopLevelAwait }, includeChildrenRecursively);
  10865. }
  10866. includeNode(context) {
  10867. this.included = true;
  10868. if (!this.deoptimized)
  10869. this.applyDeoptimizations();
  10870. checkTopLevelAwait: {
  10871. let parent = this.parent;
  10872. do {
  10873. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  10874. break checkTopLevelAwait;
  10875. } while ((parent = parent.parent));
  10876. this.scope.context.usesTopLevelAwait = true;
  10877. this.isTopLevelAwait = true;
  10878. }
  10879. // Thenables need to be included
  10880. this.argument.includePath(THEN_PATH, { ...context, withinTopLevelAwait: this.isTopLevelAwait });
  10881. }
  10882. includePath(path, context) {
  10883. if (!this.deoptimized)
  10884. this.applyDeoptimizations();
  10885. if (!this.included)
  10886. this.includeNode(context);
  10887. this.argument.includePath(path, { ...context, withinTopLevelAwait: this.isTopLevelAwait });
  10888. }
  10889. }
  10890. const THEN_PATH = ['then'];
  10891. const binaryOperators = {
  10892. '!=': (left, right) => left != right,
  10893. '!==': (left, right) => left !== right,
  10894. '%': (left, right) => left % right,
  10895. '&': (left, right) => left & right,
  10896. '*': (left, right) => left * right,
  10897. // At the moment, "**" will be transpiled to Math.pow
  10898. '**': (left, right) => left ** right,
  10899. '+': (left, right) => left + right,
  10900. '-': (left, right) => left - right,
  10901. '/': (left, right) => left / right,
  10902. '<': (left, right) => left < right,
  10903. '<<': (left, right) => left << right,
  10904. '<=': (left, right) => left <= right,
  10905. '==': (left, right) => left == right,
  10906. '===': (left, right) => left === right,
  10907. '>': (left, right) => left > right,
  10908. '>=': (left, right) => left >= right,
  10909. '>>': (left, right) => left >> right,
  10910. '>>>': (left, right) => left >>> right,
  10911. '^': (left, right) => left ^ right,
  10912. '|': (left, right) => left | right
  10913. // We use the fallback for cases where we return something unknown
  10914. // in: () => UnknownValue,
  10915. // instanceof: () => UnknownValue,
  10916. };
  10917. class BinaryExpression extends NodeBase {
  10918. deoptimizeCache() { }
  10919. getLiteralValueAtPath(path, recursionTracker, origin) {
  10920. if (path.length > 0)
  10921. return UnknownValue;
  10922. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10923. if (typeof leftValue === 'symbol')
  10924. return UnknownValue;
  10925. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10926. if (typeof rightValue === 'symbol')
  10927. return UnknownValue;
  10928. const operatorFunction = binaryOperators[this.operator];
  10929. if (!operatorFunction)
  10930. return UnknownValue;
  10931. return operatorFunction(leftValue, rightValue);
  10932. }
  10933. hasEffects(context) {
  10934. // support some implicit type coercion runtime errors
  10935. if (this.operator === '+' &&
  10936. this.parent instanceof ExpressionStatement &&
  10937. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  10938. return true;
  10939. }
  10940. return super.hasEffects(context);
  10941. }
  10942. hasEffectsOnInteractionAtPath(path, { type }) {
  10943. return type !== INTERACTION_ACCESSED || path.length > 1;
  10944. }
  10945. includeNode(context) {
  10946. this.included = true;
  10947. if (this.operator === 'in') {
  10948. this.right.includePath(UNKNOWN_PATH, context);
  10949. }
  10950. }
  10951. removeAnnotations(code) {
  10952. this.left.removeAnnotations(code);
  10953. }
  10954. render(code, options, { renderedSurroundingElement } = BLANK) {
  10955. this.left.render(code, options, { renderedSurroundingElement });
  10956. this.right.render(code, options);
  10957. }
  10958. }
  10959. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  10960. class BreakStatement extends NodeBase {
  10961. hasEffects(context) {
  10962. if (this.label) {
  10963. if (!context.ignore.labels.has(this.label.name))
  10964. return true;
  10965. context.includedLabels.add(this.label.name);
  10966. }
  10967. else {
  10968. if (!context.ignore.breaks)
  10969. return true;
  10970. context.hasBreak = true;
  10971. }
  10972. context.brokenFlow = true;
  10973. return false;
  10974. }
  10975. include(context, includeChildrenRecursively) {
  10976. this.included = true;
  10977. if (this.label) {
  10978. this.label.include(context, includeChildrenRecursively);
  10979. context.includedLabels.add(this.label.name);
  10980. }
  10981. else {
  10982. context.hasBreak = true;
  10983. }
  10984. context.brokenFlow = true;
  10985. }
  10986. }
  10987. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  10988. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  10989. function renderCallArguments(code, options, node) {
  10990. if (node.arguments.length > 0) {
  10991. if (node.arguments[node.arguments.length - 1].included) {
  10992. for (const argument of node.arguments) {
  10993. argument.render(code, options);
  10994. }
  10995. }
  10996. else {
  10997. let lastIncludedIndex = node.arguments.length - 2;
  10998. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  10999. lastIncludedIndex--;
  11000. }
  11001. if (lastIncludedIndex >= 0) {
  11002. for (let index = 0; index <= lastIncludedIndex; index++) {
  11003. node.arguments[index].render(code, options);
  11004. }
  11005. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  11006. }
  11007. else {
  11008. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  11009. }
  11010. }
  11011. }
  11012. }
  11013. class CallExpressionBase extends NodeBase {
  11014. constructor() {
  11015. super(...arguments);
  11016. this.returnExpression = null;
  11017. this.deoptimizableDependentExpressions = [];
  11018. this.expressionsToBeDeoptimized = new Set();
  11019. }
  11020. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11021. const { args } = interaction;
  11022. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  11023. if (isPure)
  11024. return;
  11025. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  11026. if (deoptimizedExpressions.length === 0)
  11027. return;
  11028. if (returnExpression === UNKNOWN_EXPRESSION) {
  11029. for (const expression of deoptimizedExpressions) {
  11030. expression.deoptimizePath(UNKNOWN_PATH);
  11031. }
  11032. }
  11033. else {
  11034. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11035. for (const expression of deoptimizedExpressions) {
  11036. this.expressionsToBeDeoptimized.add(expression);
  11037. }
  11038. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11039. }, null);
  11040. }
  11041. }
  11042. deoptimizeCache() {
  11043. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  11044. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11045. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  11046. this.expressionsToBeDeoptimized = EMPTY_SET;
  11047. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  11048. for (const expression of deoptimizableDependentExpressions) {
  11049. expression.deoptimizeCache();
  11050. }
  11051. for (const expression of expressionsToBeDeoptimized) {
  11052. expression.deoptimizePath(UNKNOWN_PATH);
  11053. }
  11054. }
  11055. }
  11056. deoptimizePath(path) {
  11057. if (path.length === 0 ||
  11058. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  11059. return;
  11060. }
  11061. const [returnExpression] = this.getReturnExpression();
  11062. if (returnExpression !== UNKNOWN_EXPRESSION) {
  11063. returnExpression.deoptimizePath(path);
  11064. }
  11065. }
  11066. getLiteralValueAtPath(path, recursionTracker, origin) {
  11067. const [returnExpression] = this.getReturnExpression(recursionTracker);
  11068. if (returnExpression === UNKNOWN_EXPRESSION) {
  11069. return UnknownValue;
  11070. }
  11071. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11072. this.deoptimizableDependentExpressions.push(origin);
  11073. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  11074. }, UnknownValue);
  11075. }
  11076. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11077. const returnExpression = this.getReturnExpression(recursionTracker);
  11078. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  11079. return returnExpression;
  11080. }
  11081. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11082. this.deoptimizableDependentExpressions.push(origin);
  11083. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11084. return [expression, isPure || returnExpression[1]];
  11085. }, UNKNOWN_RETURN_EXPRESSION);
  11086. }
  11087. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11088. const { type } = interaction;
  11089. if (type === INTERACTION_CALLED) {
  11090. const { args, withNew } = interaction;
  11091. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  11092. return false;
  11093. }
  11094. }
  11095. else if ((type === INTERACTION_ASSIGNED
  11096. ? context.assigned
  11097. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  11098. return false;
  11099. }
  11100. const [returnExpression, isPure] = this.getReturnExpression();
  11101. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  11102. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  11103. }
  11104. }
  11105. class CallExpression extends CallExpressionBase {
  11106. get hasCheckedForWarnings() {
  11107. return isFlagSet(this.flags, 536870912 /* Flag.checkedForWarnings */);
  11108. }
  11109. set hasCheckedForWarnings(value) {
  11110. this.flags = setFlag(this.flags, 536870912 /* Flag.checkedForWarnings */, value);
  11111. }
  11112. get optional() {
  11113. return isFlagSet(this.flags, 128 /* Flag.optional */);
  11114. }
  11115. set optional(value) {
  11116. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  11117. }
  11118. bind() {
  11119. super.bind();
  11120. this.interaction = {
  11121. args: [
  11122. this.callee instanceof MemberExpression && !this.callee.variable
  11123. ? this.callee.object
  11124. : null,
  11125. ...this.arguments
  11126. ],
  11127. type: INTERACTION_CALLED,
  11128. withNew: false
  11129. };
  11130. }
  11131. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  11132. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  11133. }
  11134. hasEffects(context) {
  11135. if (!this.deoptimized)
  11136. this.applyDeoptimizations();
  11137. for (const argument of this.arguments) {
  11138. if (argument.hasEffects(context))
  11139. return true;
  11140. }
  11141. if (this.annotationPure) {
  11142. return false;
  11143. }
  11144. return (this.callee.hasEffects(context) ||
  11145. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11146. }
  11147. hasEffectsAsChainElement(context) {
  11148. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  11149. ? this.callee.hasEffectsAsChainElement(context)
  11150. : this.callee.hasEffects(context);
  11151. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  11152. return IS_SKIPPED_CHAIN;
  11153. if (this.optional &&
  11154. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  11155. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  11156. }
  11157. // We only apply deoptimizations lazily once we know we are not skipping
  11158. if (!this.deoptimized)
  11159. this.applyDeoptimizations();
  11160. for (const argument of this.arguments) {
  11161. if (argument.hasEffects(context))
  11162. return true;
  11163. }
  11164. return (!this.annotationPure &&
  11165. (calleeHasEffects ||
  11166. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  11167. }
  11168. include(context, includeChildrenRecursively) {
  11169. if (!this.included)
  11170. this.includeNode(context);
  11171. if (includeChildrenRecursively) {
  11172. super.include(context, true);
  11173. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  11174. this.callee instanceof Identifier &&
  11175. this.callee.variable) {
  11176. this.callee.variable.markCalledFromTryStatement();
  11177. }
  11178. }
  11179. else {
  11180. this.callee.include(context, false);
  11181. this.callee.includeCallArguments(this.interaction, context);
  11182. }
  11183. }
  11184. includeNode(context) {
  11185. this.included = true;
  11186. if (!this.deoptimized)
  11187. this.applyDeoptimizations();
  11188. this.callee.includePath(UNKNOWN_PATH, context);
  11189. }
  11190. initialise() {
  11191. super.initialise();
  11192. if (this.annotations &&
  11193. this.scope.context.options.treeshake.annotations) {
  11194. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  11195. }
  11196. }
  11197. render(code, options, { renderedSurroundingElement } = BLANK) {
  11198. this.callee.render(code, options, {
  11199. isCalleeOfRenderedParent: true,
  11200. renderedSurroundingElement
  11201. });
  11202. renderCallArguments(code, options, this);
  11203. if (this.callee instanceof Identifier && !this.hasCheckedForWarnings) {
  11204. this.hasCheckedForWarnings = true;
  11205. const variable = this.scope.findVariable(this.callee.name);
  11206. if (variable.isNamespace) {
  11207. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  11208. }
  11209. if (this.callee.name === 'eval') {
  11210. this.scope.context.log(LOGLEVEL_WARN, logEval(this.scope.context.module.id), this.start);
  11211. }
  11212. }
  11213. }
  11214. applyDeoptimizations() {
  11215. this.deoptimized = true;
  11216. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11217. this.scope.context.requestTreeshakingPass();
  11218. }
  11219. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  11220. if (this.returnExpression === null) {
  11221. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11222. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  11223. }
  11224. return this.returnExpression;
  11225. }
  11226. }
  11227. class CatchClause extends NodeBase {
  11228. createScope(parentScope) {
  11229. this.scope = new ParameterScope(parentScope, true);
  11230. }
  11231. parseNode(esTreeNode) {
  11232. const { body, param, type } = esTreeNode;
  11233. this.type = type;
  11234. if (param) {
  11235. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  11236. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  11237. }
  11238. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  11239. return super.parseNode(esTreeNode);
  11240. }
  11241. }
  11242. CatchClause.prototype.preventChildBlockScope = true;
  11243. CatchClause.prototype.includeNode = onlyIncludeSelf;
  11244. class ChainExpression extends NodeBase {
  11245. // deoptimizations are not relevant as we are not caching values
  11246. deoptimizeCache() { }
  11247. getLiteralValueAtPath(path, recursionTracker, origin) {
  11248. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  11249. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  11250. }
  11251. hasEffects(context) {
  11252. return this.expression.hasEffectsAsChainElement(context) === true;
  11253. }
  11254. includePath(path, context) {
  11255. this.included = true;
  11256. this.expression.includePath(path, context);
  11257. }
  11258. removeAnnotations(code) {
  11259. this.expression.removeAnnotations(code);
  11260. }
  11261. }
  11262. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11263. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11264. class ClassBodyScope extends ChildScope {
  11265. constructor(parent, classNode) {
  11266. const { context } = parent;
  11267. super(parent, context);
  11268. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  11269. this.instanceScope = new ChildScope(this, context);
  11270. this.instanceScope.variables.set('this', new ThisVariable(context));
  11271. }
  11272. findLexicalBoundary() {
  11273. return this;
  11274. }
  11275. }
  11276. class ClassBody extends NodeBase {
  11277. createScope(parentScope) {
  11278. this.scope = new ClassBodyScope(parentScope, this.parent);
  11279. }
  11280. include(context, includeChildrenRecursively) {
  11281. this.included = true;
  11282. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  11283. for (const definition of this.body) {
  11284. definition.include(context, includeChildrenRecursively);
  11285. }
  11286. }
  11287. parseNode(esTreeNode) {
  11288. const body = (this.body = new Array(esTreeNode.body.length));
  11289. let index = 0;
  11290. for (const definition of esTreeNode.body) {
  11291. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  11292. }
  11293. return super.parseNode(esTreeNode);
  11294. }
  11295. }
  11296. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11297. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  11298. class ClassExpression extends ClassNode {
  11299. render(code, options, { renderedSurroundingElement } = BLANK) {
  11300. super.render(code, options);
  11301. if (renderedSurroundingElement === ExpressionStatement$1) {
  11302. code.appendRight(this.start, '(');
  11303. code.prependLeft(this.end, ')');
  11304. }
  11305. }
  11306. }
  11307. function tryCastLiteralValueToBoolean(literalValue) {
  11308. if (typeof literalValue === 'symbol') {
  11309. if (literalValue === UnknownFalsyValue) {
  11310. return false;
  11311. }
  11312. if (literalValue === UnknownTruthyValue) {
  11313. return true;
  11314. }
  11315. return UnknownValue;
  11316. }
  11317. return !!literalValue;
  11318. }
  11319. class MultiExpression extends ExpressionEntity {
  11320. constructor(expressions) {
  11321. super();
  11322. this.expressions = expressions;
  11323. }
  11324. deoptimizePath(path) {
  11325. for (const expression of this.expressions) {
  11326. expression.deoptimizePath(path);
  11327. }
  11328. }
  11329. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11330. return [
  11331. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  11332. false
  11333. ];
  11334. }
  11335. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11336. for (const expression of this.expressions) {
  11337. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  11338. return true;
  11339. }
  11340. return false;
  11341. }
  11342. }
  11343. class ConditionalExpression extends NodeBase {
  11344. constructor() {
  11345. super(...arguments);
  11346. this.expressionsToBeDeoptimized = [];
  11347. this.usedBranch = null;
  11348. }
  11349. get isBranchResolutionAnalysed() {
  11350. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  11351. }
  11352. set isBranchResolutionAnalysed(value) {
  11353. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  11354. }
  11355. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11356. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11357. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11358. }
  11359. deoptimizeCache() {
  11360. if (this.usedBranch !== null) {
  11361. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  11362. this.usedBranch = null;
  11363. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  11364. if (this.included) {
  11365. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  11366. }
  11367. const { expressionsToBeDeoptimized } = this;
  11368. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  11369. for (const expression of expressionsToBeDeoptimized) {
  11370. expression.deoptimizeCache();
  11371. }
  11372. }
  11373. }
  11374. deoptimizePath(path) {
  11375. const usedBranch = this.getUsedBranch();
  11376. if (usedBranch) {
  11377. usedBranch.deoptimizePath(path);
  11378. }
  11379. else {
  11380. this.consequent.deoptimizePath(path);
  11381. this.alternate.deoptimizePath(path);
  11382. }
  11383. }
  11384. getLiteralValueAtPath(path, recursionTracker, origin) {
  11385. const usedBranch = this.getUsedBranch();
  11386. if (!usedBranch)
  11387. return UnknownValue;
  11388. this.expressionsToBeDeoptimized.push(origin);
  11389. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  11390. }
  11391. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11392. const usedBranch = this.getUsedBranch();
  11393. if (!usedBranch)
  11394. return [
  11395. new MultiExpression([
  11396. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  11397. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  11398. ]),
  11399. false
  11400. ];
  11401. this.expressionsToBeDeoptimized.push(origin);
  11402. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11403. }
  11404. hasEffects(context) {
  11405. if (this.test.hasEffects(context))
  11406. return true;
  11407. const usedBranch = this.getUsedBranch();
  11408. if (!usedBranch) {
  11409. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  11410. }
  11411. return usedBranch.hasEffects(context);
  11412. }
  11413. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11414. const usedBranch = this.getUsedBranch();
  11415. if (!usedBranch) {
  11416. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  11417. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  11418. }
  11419. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  11420. }
  11421. include(context, includeChildrenRecursively) {
  11422. this.included = true;
  11423. const usedBranch = this.getUsedBranch();
  11424. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  11425. this.test.include(context, includeChildrenRecursively);
  11426. this.consequent.include(context, includeChildrenRecursively);
  11427. this.alternate.include(context, includeChildrenRecursively);
  11428. }
  11429. else {
  11430. usedBranch.include(context, includeChildrenRecursively);
  11431. }
  11432. }
  11433. includePath(path, context) {
  11434. this.included = true;
  11435. const usedBranch = this.getUsedBranch();
  11436. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  11437. this.consequent.includePath(path, context);
  11438. this.alternate.includePath(path, context);
  11439. }
  11440. else {
  11441. usedBranch.includePath(path, context);
  11442. }
  11443. }
  11444. includeCallArguments(interaction, context) {
  11445. const usedBranch = this.getUsedBranch();
  11446. if (usedBranch) {
  11447. usedBranch.includeCallArguments(interaction, context);
  11448. }
  11449. else {
  11450. this.consequent.includeCallArguments(interaction, context);
  11451. this.alternate.includeCallArguments(interaction, context);
  11452. }
  11453. }
  11454. removeAnnotations(code) {
  11455. this.test.removeAnnotations(code);
  11456. }
  11457. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11458. if (this.test.included) {
  11459. this.test.render(code, options, { renderedSurroundingElement });
  11460. this.consequent.render(code, options);
  11461. this.alternate.render(code, options);
  11462. }
  11463. else {
  11464. const usedBranch = this.getUsedBranch();
  11465. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  11466. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  11467. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  11468. : colonPos) + 1);
  11469. if (preventASI) {
  11470. removeLineBreaks(code, inclusionStart, usedBranch.start);
  11471. }
  11472. code.remove(this.start, inclusionStart);
  11473. if (this.consequent.included) {
  11474. code.remove(colonPos, this.end);
  11475. }
  11476. this.test.removeAnnotations(code);
  11477. usedBranch.render(code, options, {
  11478. isCalleeOfRenderedParent,
  11479. preventASI: true,
  11480. renderedParentType: renderedParentType || this.parent.type,
  11481. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  11482. });
  11483. }
  11484. }
  11485. getUsedBranch() {
  11486. if (this.isBranchResolutionAnalysed) {
  11487. return this.usedBranch;
  11488. }
  11489. this.isBranchResolutionAnalysed = true;
  11490. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  11491. return typeof testValue === 'symbol'
  11492. ? null
  11493. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  11494. }
  11495. }
  11496. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11497. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11498. class ContinueStatement extends NodeBase {
  11499. hasEffects(context) {
  11500. if (this.label) {
  11501. if (!context.ignore.labels.has(this.label.name))
  11502. return true;
  11503. context.includedLabels.add(this.label.name);
  11504. }
  11505. else {
  11506. if (!context.ignore.continues)
  11507. return true;
  11508. context.hasContinue = true;
  11509. }
  11510. context.brokenFlow = true;
  11511. return false;
  11512. }
  11513. include(context, includeChildrenRecursively) {
  11514. this.included = true;
  11515. if (this.label) {
  11516. this.label.include(context, includeChildrenRecursively);
  11517. context.includedLabels.add(this.label.name);
  11518. }
  11519. else {
  11520. context.hasContinue = true;
  11521. }
  11522. context.brokenFlow = true;
  11523. }
  11524. }
  11525. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11526. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11527. class DebuggerStatement extends NodeBase {
  11528. hasEffects() {
  11529. return true;
  11530. }
  11531. }
  11532. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  11533. class Decorator extends NodeBase {
  11534. hasEffects(context) {
  11535. return (this.expression.hasEffects(context) ||
  11536. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  11537. }
  11538. }
  11539. Decorator.prototype.includeNode = onlyIncludeSelf;
  11540. function hasLoopBodyEffects(context, body) {
  11541. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  11542. const { breaks, continues } = ignore;
  11543. ignore.breaks = true;
  11544. ignore.continues = true;
  11545. context.hasBreak = false;
  11546. context.hasContinue = false;
  11547. if (body.hasEffects(context))
  11548. return true;
  11549. ignore.breaks = breaks;
  11550. ignore.continues = continues;
  11551. context.hasBreak = hasBreak;
  11552. context.hasContinue = hasContinue;
  11553. context.brokenFlow = brokenFlow;
  11554. return false;
  11555. }
  11556. function includeLoopBody(context, body, includeChildrenRecursively) {
  11557. const { brokenFlow, hasBreak, hasContinue } = context;
  11558. context.hasBreak = false;
  11559. context.hasContinue = false;
  11560. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11561. context.hasBreak = hasBreak;
  11562. context.hasContinue = hasContinue;
  11563. context.brokenFlow = brokenFlow;
  11564. }
  11565. class DoWhileStatement extends NodeBase {
  11566. hasEffects(context) {
  11567. if (this.test.hasEffects(context))
  11568. return true;
  11569. return hasLoopBodyEffects(context, this.body);
  11570. }
  11571. include(context, includeChildrenRecursively) {
  11572. this.included = true;
  11573. this.test.include(context, includeChildrenRecursively);
  11574. includeLoopBody(context, this.body, includeChildrenRecursively);
  11575. }
  11576. }
  11577. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11578. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11579. class EmptyStatement extends NodeBase {
  11580. hasEffects() {
  11581. return false;
  11582. }
  11583. }
  11584. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  11585. class ExportAllDeclaration extends NodeBase {
  11586. hasEffects() {
  11587. return false;
  11588. }
  11589. initialise() {
  11590. super.initialise();
  11591. this.scope.context.addExport(this);
  11592. }
  11593. render(code, _options, nodeRenderOptions) {
  11594. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11595. }
  11596. }
  11597. ExportAllDeclaration.prototype.needsBoundaries = true;
  11598. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11599. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  11600. class ExportNamedDeclaration extends NodeBase {
  11601. bind() {
  11602. // Do not bind specifiers
  11603. this.declaration?.bind();
  11604. }
  11605. hasEffects(context) {
  11606. return !!this.declaration?.hasEffects(context);
  11607. }
  11608. initialise() {
  11609. super.initialise();
  11610. this.scope.context.addExport(this);
  11611. }
  11612. removeAnnotations(code) {
  11613. this.declaration?.removeAnnotations(code);
  11614. }
  11615. render(code, options, nodeRenderOptions) {
  11616. const { start, end } = nodeRenderOptions;
  11617. if (this.declaration === null) {
  11618. code.remove(start, end);
  11619. }
  11620. else {
  11621. let endBoundary = this.declaration.start;
  11622. // the start of the decorator may be before the start of the class declaration
  11623. if (this.declaration instanceof ClassDeclaration) {
  11624. const decorators = this.declaration.decorators;
  11625. for (const decorator of decorators) {
  11626. endBoundary = Math.min(endBoundary, decorator.start);
  11627. }
  11628. if (endBoundary <= this.start) {
  11629. endBoundary = this.declaration.start;
  11630. }
  11631. }
  11632. code.remove(this.start, endBoundary);
  11633. this.declaration.render(code, options, { end, start });
  11634. }
  11635. }
  11636. }
  11637. ExportNamedDeclaration.prototype.needsBoundaries = true;
  11638. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11639. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  11640. class ExportSpecifier extends NodeBase {
  11641. }
  11642. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11643. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  11644. class ForInStatement extends NodeBase {
  11645. createScope(parentScope) {
  11646. this.scope = new BlockScope(parentScope);
  11647. }
  11648. hasEffects(context) {
  11649. const { body, deoptimized, left, right } = this;
  11650. if (!deoptimized)
  11651. this.applyDeoptimizations();
  11652. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  11653. return true;
  11654. return hasLoopBodyEffects(context, body);
  11655. }
  11656. include(context, includeChildrenRecursively) {
  11657. const { body, deoptimized, left, right } = this;
  11658. if (!deoptimized)
  11659. this.applyDeoptimizations();
  11660. if (!this.included)
  11661. this.includeNode(context);
  11662. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11663. right.include(context, includeChildrenRecursively);
  11664. includeLoopBody(context, body, includeChildrenRecursively);
  11665. }
  11666. includeNode(context) {
  11667. this.included = true;
  11668. if (!this.deoptimized)
  11669. this.applyDeoptimizations();
  11670. this.right.includePath(UNKNOWN_PATH, context);
  11671. }
  11672. initialise() {
  11673. super.initialise();
  11674. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11675. }
  11676. render(code, options) {
  11677. this.left.render(code, options, NO_SEMICOLON);
  11678. this.right.render(code, options, NO_SEMICOLON);
  11679. // handle no space between "in" and the right side
  11680. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  11681. code.prependLeft(this.right.start, ' ');
  11682. }
  11683. this.body.render(code, options);
  11684. }
  11685. applyDeoptimizations() {
  11686. this.deoptimized = true;
  11687. this.left.deoptimizePath(EMPTY_PATH);
  11688. this.scope.context.requestTreeshakingPass();
  11689. }
  11690. }
  11691. class ForOfStatement extends NodeBase {
  11692. get await() {
  11693. return isFlagSet(this.flags, 131072 /* Flag.await */);
  11694. }
  11695. set await(value) {
  11696. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  11697. }
  11698. createScope(parentScope) {
  11699. this.scope = new BlockScope(parentScope);
  11700. }
  11701. hasEffects() {
  11702. if (!this.deoptimized)
  11703. this.applyDeoptimizations();
  11704. // Placeholder until proper Symbol.Iterator support
  11705. return true;
  11706. }
  11707. include(context, includeChildrenRecursively) {
  11708. const { body, deoptimized, left, right } = this;
  11709. if (!deoptimized)
  11710. this.applyDeoptimizations();
  11711. if (!this.included)
  11712. this.includeNode(context);
  11713. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11714. right.include(context, includeChildrenRecursively);
  11715. includeLoopBody(context, body, includeChildrenRecursively);
  11716. }
  11717. includeNode(context) {
  11718. this.included = true;
  11719. if (!this.deoptimized)
  11720. this.applyDeoptimizations();
  11721. this.right.includePath(UNKNOWN_PATH, context);
  11722. }
  11723. initialise() {
  11724. super.initialise();
  11725. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11726. }
  11727. render(code, options) {
  11728. this.left.render(code, options, NO_SEMICOLON);
  11729. this.right.render(code, options, NO_SEMICOLON);
  11730. // handle no space between "of" and the right side
  11731. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  11732. code.prependLeft(this.right.start, ' ');
  11733. }
  11734. this.body.render(code, options);
  11735. }
  11736. applyDeoptimizations() {
  11737. this.deoptimized = true;
  11738. this.left.deoptimizePath(EMPTY_PATH);
  11739. this.right.deoptimizePath(UNKNOWN_PATH);
  11740. this.scope.context.requestTreeshakingPass();
  11741. }
  11742. }
  11743. class ForStatement extends NodeBase {
  11744. createScope(parentScope) {
  11745. this.scope = new BlockScope(parentScope);
  11746. }
  11747. hasEffects(context) {
  11748. if (this.init?.hasEffects(context) ||
  11749. this.test?.hasEffects(context) ||
  11750. this.update?.hasEffects(context)) {
  11751. return true;
  11752. }
  11753. return hasLoopBodyEffects(context, this.body);
  11754. }
  11755. include(context, includeChildrenRecursively) {
  11756. this.included = true;
  11757. this.init?.include(context, includeChildrenRecursively, {
  11758. asSingleStatement: true
  11759. });
  11760. this.test?.include(context, includeChildrenRecursively);
  11761. this.update?.include(context, includeChildrenRecursively);
  11762. includeLoopBody(context, this.body, includeChildrenRecursively);
  11763. }
  11764. render(code, options) {
  11765. this.init?.render(code, options, NO_SEMICOLON);
  11766. this.test?.render(code, options, NO_SEMICOLON);
  11767. this.update?.render(code, options, NO_SEMICOLON);
  11768. this.body.render(code, options);
  11769. }
  11770. }
  11771. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11772. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11773. class FunctionExpression extends FunctionNode {
  11774. createScope(parentScope) {
  11775. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  11776. }
  11777. parseNode(esTreeNode) {
  11778. if (esTreeNode.id !== null) {
  11779. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  11780. }
  11781. return super.parseNode(esTreeNode);
  11782. }
  11783. onlyFunctionCallUsed() {
  11784. const isIIFE = this.parent.type === CallExpression$1 &&
  11785. this.parent.callee === this &&
  11786. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  11787. return isIIFE || super.onlyFunctionCallUsed();
  11788. }
  11789. render(code, options, { renderedSurroundingElement } = BLANK) {
  11790. super.render(code, options);
  11791. if (renderedSurroundingElement === ExpressionStatement$1) {
  11792. code.appendRight(this.start, '(');
  11793. code.prependLeft(this.end, ')');
  11794. }
  11795. }
  11796. }
  11797. class TrackingScope extends BlockScope {
  11798. constructor() {
  11799. super(...arguments);
  11800. this.hoistedDeclarations = [];
  11801. }
  11802. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  11803. this.hoistedDeclarations.push(identifier);
  11804. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  11805. }
  11806. }
  11807. const unset = Symbol('unset');
  11808. class IfStatement extends NodeBase {
  11809. constructor() {
  11810. super(...arguments);
  11811. this.testValue = unset;
  11812. }
  11813. deoptimizeCache() {
  11814. this.testValue = UnknownValue;
  11815. }
  11816. hasEffects(context) {
  11817. if (this.test.hasEffects(context)) {
  11818. return true;
  11819. }
  11820. const testValue = this.getTestValue();
  11821. if (typeof testValue === 'symbol') {
  11822. const { brokenFlow } = context;
  11823. if (this.consequent.hasEffects(context))
  11824. return true;
  11825. const consequentBrokenFlow = context.brokenFlow;
  11826. context.brokenFlow = brokenFlow;
  11827. if (this.alternate === null)
  11828. return false;
  11829. if (this.alternate.hasEffects(context))
  11830. return true;
  11831. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11832. return false;
  11833. }
  11834. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  11835. }
  11836. include(context, includeChildrenRecursively) {
  11837. this.included = true;
  11838. if (includeChildrenRecursively) {
  11839. this.includeRecursively(includeChildrenRecursively, context);
  11840. }
  11841. else {
  11842. const testValue = this.getTestValue();
  11843. if (typeof testValue === 'symbol') {
  11844. this.includeUnknownTest(context);
  11845. }
  11846. else {
  11847. this.includeKnownTest(context, testValue);
  11848. }
  11849. }
  11850. }
  11851. parseNode(esTreeNode) {
  11852. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  11853. if (esTreeNode.alternate) {
  11854. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  11855. }
  11856. return super.parseNode(esTreeNode);
  11857. }
  11858. render(code, options) {
  11859. const { snippets: { getPropertyAccess } } = options;
  11860. // Note that unknown test values are always included
  11861. const testValue = this.getTestValue();
  11862. const hoistedDeclarations = [];
  11863. const includesIfElse = this.test.included;
  11864. const noTreeshake = !this.scope.context.options.treeshake;
  11865. if (includesIfElse) {
  11866. this.test.render(code, options);
  11867. }
  11868. else {
  11869. code.remove(this.start, this.consequent.start);
  11870. }
  11871. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  11872. this.consequent.render(code, options);
  11873. }
  11874. else {
  11875. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  11876. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  11877. }
  11878. if (this.alternate) {
  11879. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  11880. if (includesIfElse) {
  11881. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  11882. code.prependLeft(this.alternate.start, ' ');
  11883. }
  11884. }
  11885. else {
  11886. code.remove(this.consequent.end, this.alternate.start);
  11887. }
  11888. this.alternate.render(code, options);
  11889. }
  11890. else {
  11891. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  11892. code.overwrite(this.alternate.start, this.end, ';');
  11893. }
  11894. else {
  11895. code.remove(this.consequent.end, this.end);
  11896. }
  11897. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  11898. }
  11899. }
  11900. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  11901. }
  11902. getTestValue() {
  11903. if (this.testValue === unset) {
  11904. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  11905. }
  11906. return this.testValue;
  11907. }
  11908. includeKnownTest(context, testValue) {
  11909. if (this.test.shouldBeIncluded(context)) {
  11910. this.test.include(context, false);
  11911. }
  11912. if (testValue && this.consequent.shouldBeIncluded(context)) {
  11913. this.consequent.include(context, false, { asSingleStatement: true });
  11914. }
  11915. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  11916. this.alternate.include(context, false, { asSingleStatement: true });
  11917. }
  11918. }
  11919. includeRecursively(includeChildrenRecursively, context) {
  11920. this.test.include(context, includeChildrenRecursively);
  11921. this.consequent.include(context, includeChildrenRecursively);
  11922. this.alternate?.include(context, includeChildrenRecursively);
  11923. }
  11924. includeUnknownTest(context) {
  11925. this.test.include(context, false);
  11926. const { brokenFlow } = context;
  11927. let consequentBrokenFlow = false;
  11928. if (this.consequent.shouldBeIncluded(context)) {
  11929. this.consequent.include(context, false, { asSingleStatement: true });
  11930. consequentBrokenFlow = context.brokenFlow;
  11931. context.brokenFlow = brokenFlow;
  11932. }
  11933. if (this.alternate?.shouldBeIncluded(context)) {
  11934. this.alternate.include(context, false, { asSingleStatement: true });
  11935. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11936. }
  11937. }
  11938. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  11939. const hoistedVariables = [
  11940. ...new Set(hoistedDeclarations.map(identifier => {
  11941. const variable = identifier.variable;
  11942. return variable.included ? variable.getName(getPropertyAccess) : '';
  11943. }))
  11944. ]
  11945. .filter(Boolean)
  11946. .join(', ');
  11947. if (hoistedVariables) {
  11948. const parentType = this.parent.type;
  11949. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  11950. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  11951. if (needsBraces) {
  11952. code.appendLeft(this.end, ` }`);
  11953. }
  11954. }
  11955. }
  11956. shouldKeepAlternateBranch() {
  11957. let currentParent = this.parent;
  11958. do {
  11959. if (currentParent instanceof IfStatement && currentParent.alternate) {
  11960. return true;
  11961. }
  11962. if (currentParent instanceof BlockStatement) {
  11963. return false;
  11964. }
  11965. currentParent = currentParent.parent;
  11966. } while (currentParent);
  11967. return false;
  11968. }
  11969. }
  11970. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11971. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11972. class ImportAttribute extends NodeBase {
  11973. }
  11974. class ImportDeclaration extends NodeBase {
  11975. // Do not bind specifiers or attributes
  11976. bind() { }
  11977. hasEffects() {
  11978. return false;
  11979. }
  11980. initialise() {
  11981. super.initialise();
  11982. this.scope.context.addImport(this);
  11983. }
  11984. render(code, _options, nodeRenderOptions) {
  11985. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11986. }
  11987. }
  11988. ImportDeclaration.prototype.needsBoundaries = true;
  11989. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11990. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  11991. class ImportDefaultSpecifier extends NodeBase {
  11992. }
  11993. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11994. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  11995. function isReassignedExportsMember(variable, exportNamesByVariable) {
  11996. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  11997. }
  11998. class VariableDeclarator extends NodeBase {
  11999. declareDeclarator(kind, isUsingDeclaration) {
  12000. this.isUsingDeclaration = isUsingDeclaration;
  12001. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  12002. }
  12003. deoptimizePath(path) {
  12004. this.id.deoptimizePath(path);
  12005. }
  12006. hasEffects(context) {
  12007. const initEffect = this.init?.hasEffects(context);
  12008. this.id.markDeclarationReached();
  12009. return (initEffect ||
  12010. this.isUsingDeclaration ||
  12011. this.id.hasEffects(context) ||
  12012. (this.scope.context.options.treeshake
  12013. .propertyReadSideEffects &&
  12014. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  12015. }
  12016. include(context, includeChildrenRecursively) {
  12017. const { id, init } = this;
  12018. if (!this.included)
  12019. this.includeNode();
  12020. init?.include(context, includeChildrenRecursively);
  12021. id.markDeclarationReached();
  12022. if (includeChildrenRecursively) {
  12023. id.include(context, includeChildrenRecursively);
  12024. }
  12025. else {
  12026. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  12027. }
  12028. }
  12029. removeAnnotations(code) {
  12030. this.init?.removeAnnotations(code);
  12031. }
  12032. render(code, options) {
  12033. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  12034. const { end, id, init, start } = this;
  12035. const renderId = id.included || this.isUsingDeclaration;
  12036. if (renderId) {
  12037. id.render(code, options);
  12038. }
  12039. else {
  12040. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  12041. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  12042. }
  12043. if (init) {
  12044. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12045. const renderedVariable = id.variable.getName(getPropertyAccess);
  12046. if (renderedVariable !== id.name) {
  12047. code.appendLeft(init.start + 5, ` ${id.name}`);
  12048. }
  12049. }
  12050. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  12051. }
  12052. else if (id instanceof Identifier &&
  12053. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  12054. code.appendLeft(end, `${_}=${_}void 0`);
  12055. }
  12056. }
  12057. includeNode() {
  12058. this.included = true;
  12059. const { id, init } = this;
  12060. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12061. const { name, variable } = id;
  12062. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  12063. if (accessedVariable !== variable) {
  12064. accessedVariable.forbidName(name);
  12065. }
  12066. }
  12067. }
  12068. }
  12069. }
  12070. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  12071. function getChunkInfoWithPath(chunk) {
  12072. return { fileName: chunk.getFileName(), ...chunk.getPreRenderedChunkInfo() };
  12073. }
  12074. class ImportExpression extends NodeBase {
  12075. constructor() {
  12076. super(...arguments);
  12077. this.inlineNamespace = null;
  12078. this.hasUnknownAccessedKey = false;
  12079. this.accessedPropKey = new Set();
  12080. this.attributes = null;
  12081. this.mechanism = null;
  12082. this.namespaceExportName = undefined;
  12083. this.resolution = null;
  12084. this.resolutionString = null;
  12085. }
  12086. get withinTopLevelAwait() {
  12087. return isFlagSet(this.flags, 268435456 /* Flag.withinTopLevelAwait */);
  12088. }
  12089. set withinTopLevelAwait(value) {
  12090. this.flags = setFlag(this.flags, 268435456 /* Flag.withinTopLevelAwait */, value);
  12091. }
  12092. // Do not bind attributes
  12093. bind() {
  12094. this.source.bind();
  12095. }
  12096. /**
  12097. * Get imported variables for deterministic usage, valid cases are:
  12098. *
  12099. * 1. `const { foo } = await import('bar')`.
  12100. * 2. `(await import('bar')).foo`
  12101. * 3. `import('bar').then((m) => m.foo)`
  12102. * 4. `import('bar').then(({ foo }) => {})`
  12103. *
  12104. * Returns empty array if it's side-effect only import.
  12105. * Returns undefined if it's not fully deterministic.
  12106. */
  12107. getDeterministicImportedNames() {
  12108. const parent1 = this.parent;
  12109. // Side-effect only: import('bar')
  12110. if (parent1 instanceof ExpressionStatement) {
  12111. return EMPTY_ARRAY;
  12112. }
  12113. if (parent1 instanceof AwaitExpression) {
  12114. const parent2 = parent1.parent;
  12115. // Side-effect only: await import('bar')
  12116. if (parent2 instanceof ExpressionStatement) {
  12117. return EMPTY_ARRAY;
  12118. }
  12119. // Case 1: const { foo } / module = await import('bar')
  12120. if (parent2 instanceof VariableDeclarator) {
  12121. const declaration = parent2.id;
  12122. if (declaration instanceof Identifier) {
  12123. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  12124. }
  12125. if (declaration instanceof ObjectPattern) {
  12126. return getDeterministicObjectDestructure(declaration);
  12127. }
  12128. }
  12129. // Case 2: (await import('bar')).foo
  12130. if (parent2 instanceof MemberExpression) {
  12131. const id = parent2.property;
  12132. if (!parent2.computed && id instanceof Identifier) {
  12133. return [id.name];
  12134. }
  12135. }
  12136. return;
  12137. }
  12138. if (parent1 instanceof MemberExpression) {
  12139. const callExpression = parent1.parent;
  12140. const property = parent1.property;
  12141. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  12142. return;
  12143. }
  12144. const memberName = property.name;
  12145. // side-effect only, when only chaining .catch or .finally
  12146. if (callExpression.parent instanceof ExpressionStatement &&
  12147. ['catch', 'finally'].includes(memberName)) {
  12148. return EMPTY_ARRAY;
  12149. }
  12150. if (memberName !== 'then')
  12151. return;
  12152. // Side-effect only: import('bar').then()
  12153. if (callExpression.arguments.length === 0) {
  12154. return EMPTY_ARRAY;
  12155. }
  12156. const thenCallback = callExpression.arguments[0];
  12157. if (callExpression.arguments.length !== 1 ||
  12158. !(thenCallback instanceof ArrowFunctionExpression ||
  12159. thenCallback instanceof FunctionExpression)) {
  12160. return;
  12161. }
  12162. // Side-effect only: import('bar').then(() => {})
  12163. if (thenCallback.params.length === 0) {
  12164. return EMPTY_ARRAY;
  12165. }
  12166. if (thenCallback.params.length === 1) {
  12167. // Promises .then() can only have one argument so only look at first one
  12168. const declaration = thenCallback.params[0];
  12169. // Case 3: import('bar').then(m => m.foo)
  12170. if (declaration instanceof Identifier) {
  12171. const starName = declaration.name;
  12172. const memberExpression = thenCallback.body;
  12173. if (!(memberExpression instanceof MemberExpression) ||
  12174. memberExpression.computed ||
  12175. !(memberExpression.property instanceof Identifier)) {
  12176. return;
  12177. }
  12178. const returnVariable = memberExpression.object;
  12179. if (!(returnVariable instanceof Identifier) || returnVariable.name !== starName) {
  12180. return;
  12181. }
  12182. return [memberExpression.property.name];
  12183. }
  12184. // Case 4: import('bar').then(({ foo }) => {})
  12185. if (declaration instanceof ObjectPattern) {
  12186. return getDeterministicObjectDestructure(declaration);
  12187. }
  12188. }
  12189. return;
  12190. }
  12191. }
  12192. hasEffects() {
  12193. return true;
  12194. }
  12195. include(context, includeChildrenRecursively) {
  12196. if (!this.included)
  12197. this.includeNode(context);
  12198. this.source.include(context, includeChildrenRecursively);
  12199. }
  12200. includeNode(context) {
  12201. this.included = true;
  12202. this.withinTopLevelAwait = context.withinTopLevelAwait;
  12203. this.scope.context.includeDynamicImport(this);
  12204. this.scope.addAccessedDynamicImport(this);
  12205. }
  12206. includePath(path, context) {
  12207. if (!this.included)
  12208. this.includeNode(context);
  12209. // Technically, this is not correct as dynamic imports return a Promise.
  12210. if (this.hasUnknownAccessedKey)
  12211. return;
  12212. if (path[0] === UnknownKey) {
  12213. this.hasUnknownAccessedKey = true;
  12214. }
  12215. else if (typeof path[0] === 'string') {
  12216. this.accessedPropKey.add(path[0]);
  12217. }
  12218. // Update included paths
  12219. this.scope.context.includeDynamicImport(this);
  12220. }
  12221. initialise() {
  12222. super.initialise();
  12223. this.scope.context.addDynamicImport(this);
  12224. }
  12225. parseNode(esTreeNode) {
  12226. this.sourceAstNode = esTreeNode.source;
  12227. return super.parseNode(esTreeNode);
  12228. }
  12229. render(code, options) {
  12230. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  12231. if (this.inlineNamespace) {
  12232. const [left, right] = getDirectReturnFunction([], {
  12233. functionReturn: true,
  12234. lineBreakIndent: null,
  12235. name: null
  12236. });
  12237. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  12238. return;
  12239. }
  12240. if (this.mechanism) {
  12241. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  12242. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  12243. }
  12244. if (this.resolutionString) {
  12245. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  12246. if (this.namespaceExportName) {
  12247. const [left, right] = getDirectReturnFunction(['n'], {
  12248. functionReturn: true,
  12249. lineBreakIndent: null,
  12250. name: null
  12251. });
  12252. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  12253. }
  12254. }
  12255. else {
  12256. this.source.render(code, options);
  12257. }
  12258. if (this.attributes !== true) {
  12259. if (this.options) {
  12260. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  12261. }
  12262. if (this.attributes) {
  12263. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  12264. lineBreakIndent: null
  12265. })}`);
  12266. }
  12267. }
  12268. }
  12269. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes, ownChunk, targetChunk) {
  12270. const { format } = options;
  12271. this.inlineNamespace = null;
  12272. this.resolution = resolution;
  12273. this.resolutionString = resolutionString;
  12274. this.namespaceExportName = namespaceExportName;
  12275. this.attributes = attributes;
  12276. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  12277. let helper;
  12278. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver, ownChunk, targetChunk));
  12279. if (helper) {
  12280. accessedGlobals.push(helper);
  12281. }
  12282. if (accessedGlobals.length > 0) {
  12283. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12284. }
  12285. }
  12286. setInternalResolution(inlineNamespace) {
  12287. this.inlineNamespace = inlineNamespace;
  12288. }
  12289. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver, ownChunk, targetChunk) {
  12290. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  12291. {
  12292. chunk: getChunkInfoWithPath(ownChunk),
  12293. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  12294. format,
  12295. getTargetChunkImports() {
  12296. if (targetChunk === null)
  12297. return null;
  12298. const chunkInfos = [];
  12299. const importerPath = ownChunk.getFileName();
  12300. for (const dep of targetChunk.dependencies) {
  12301. const resolvedImportPath = `'${dep.getImportPath(importerPath)}'`;
  12302. if (dep instanceof ExternalChunk) {
  12303. chunkInfos.push({
  12304. fileName: dep.getFileName(),
  12305. resolvedImportPath,
  12306. type: 'external'
  12307. });
  12308. }
  12309. else {
  12310. chunkInfos.push({
  12311. chunk: dep.getPreRenderedChunkInfo(),
  12312. fileName: dep.getFileName(),
  12313. resolvedImportPath,
  12314. type: 'internal'
  12315. });
  12316. }
  12317. }
  12318. return chunkInfos;
  12319. },
  12320. moduleId: this.scope.context.module.id,
  12321. targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
  12322. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  12323. }
  12324. ]);
  12325. if (mechanism) {
  12326. return { helper: null, mechanism };
  12327. }
  12328. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  12329. switch (format) {
  12330. case 'cjs': {
  12331. if (dynamicImportInCjs &&
  12332. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  12333. return { helper: null, mechanism: null };
  12334. }
  12335. const helper = getInteropHelper(resolution, exportMode, interop);
  12336. let left = `require(`;
  12337. let right = `)`;
  12338. if (helper) {
  12339. left = `/*#__PURE__*/${helper}(${left}`;
  12340. right += ')';
  12341. }
  12342. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  12343. functionReturn: true,
  12344. lineBreakIndent: null,
  12345. name: null
  12346. });
  12347. left = `Promise.resolve().then(${functionLeft}${left}`;
  12348. right += `${functionRight})`;
  12349. if (!arrowFunctions && hasDynamicTarget) {
  12350. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12351. needsArrowReturnParens: false,
  12352. needsWrappedFunction: true
  12353. });
  12354. right = ')';
  12355. }
  12356. return {
  12357. helper,
  12358. mechanism: { left, right }
  12359. };
  12360. }
  12361. case 'amd': {
  12362. const resolve = compact ? 'c' : 'resolve';
  12363. const reject = compact ? 'e' : 'reject';
  12364. const helper = getInteropHelper(resolution, exportMode, interop);
  12365. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  12366. functionReturn: false,
  12367. lineBreakIndent: null,
  12368. name: null
  12369. });
  12370. const resolveNamespace = helper
  12371. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  12372. : resolve;
  12373. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  12374. functionReturn: false,
  12375. lineBreakIndent: null,
  12376. name: null
  12377. });
  12378. let left = `new Promise(${handlerLeft}require([`;
  12379. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  12380. if (!arrowFunctions && hasDynamicTarget) {
  12381. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12382. needsArrowReturnParens: false,
  12383. needsWrappedFunction: true
  12384. });
  12385. right = ')';
  12386. }
  12387. return {
  12388. helper,
  12389. mechanism: { left, right }
  12390. };
  12391. }
  12392. case 'system': {
  12393. return {
  12394. helper: null,
  12395. mechanism: {
  12396. left: 'module.import(',
  12397. right: ')'
  12398. }
  12399. };
  12400. }
  12401. }
  12402. return { helper: null, mechanism: null };
  12403. }
  12404. }
  12405. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12406. function getInteropHelper(resolution, exportMode, interop) {
  12407. return exportMode === 'external'
  12408. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  12409. : exportMode === 'default'
  12410. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  12411. : null;
  12412. }
  12413. const accessedImportGlobals = {
  12414. amd: ['require'],
  12415. cjs: ['require'],
  12416. system: ['module']
  12417. };
  12418. function getDeterministicObjectDestructure(objectPattern) {
  12419. const variables = [];
  12420. for (const property of objectPattern.properties) {
  12421. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  12422. return;
  12423. variables.push(property.key.name);
  12424. }
  12425. return variables;
  12426. }
  12427. class ImportNamespaceSpecifier extends NodeBase {
  12428. }
  12429. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12430. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12431. class ImportSpecifier extends NodeBase {
  12432. }
  12433. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12434. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12435. class JSXIdentifier extends IdentifierBase {
  12436. constructor() {
  12437. super(...arguments);
  12438. this.isNativeElement = false;
  12439. }
  12440. bind() {
  12441. const type = this.getType();
  12442. if (type === 0 /* IdentifierType.Reference */) {
  12443. this.variable = this.scope.findVariable(this.name);
  12444. this.variable.addReference(this);
  12445. }
  12446. else if (type === 1 /* IdentifierType.NativeElementName */) {
  12447. this.isNativeElement = true;
  12448. }
  12449. }
  12450. include(context) {
  12451. if (!this.included)
  12452. this.includeNode(context);
  12453. }
  12454. includeNode(context) {
  12455. this.included = true;
  12456. if (!this.deoptimized)
  12457. this.applyDeoptimizations();
  12458. if (this.variable !== null) {
  12459. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  12460. }
  12461. }
  12462. includePath(path, context) {
  12463. if (!this.included) {
  12464. this.included = true;
  12465. if (this.variable !== null) {
  12466. this.scope.context.includeVariableInModule(this.variable, path, context);
  12467. }
  12468. }
  12469. else if (path.length > 0) {
  12470. this.variable?.includePath(path, context);
  12471. }
  12472. }
  12473. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  12474. if (this.variable) {
  12475. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  12476. if (name !== this.name) {
  12477. code.overwrite(this.start, this.end, name, {
  12478. contentOnly: true,
  12479. storeName: true
  12480. });
  12481. }
  12482. }
  12483. else if (this.isNativeElement &&
  12484. this.scope.context.options.jsx.mode !== 'preserve') {
  12485. code.update(this.start, this.end, JSON.stringify(this.name));
  12486. }
  12487. }
  12488. getType() {
  12489. switch (this.parent.type) {
  12490. case 'JSXOpeningElement':
  12491. case 'JSXClosingElement': {
  12492. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  12493. ? 0 /* IdentifierType.Reference */
  12494. : 1 /* IdentifierType.NativeElementName */;
  12495. }
  12496. case 'JSXMemberExpression': {
  12497. return this.parent.object === this
  12498. ? 0 /* IdentifierType.Reference */
  12499. : 2 /* IdentifierType.Other */;
  12500. }
  12501. case 'JSXAttribute':
  12502. case 'JSXNamespacedName': {
  12503. return 2 /* IdentifierType.Other */;
  12504. }
  12505. default: {
  12506. /* istanbul ignore next */
  12507. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  12508. }
  12509. }
  12510. }
  12511. }
  12512. class JSXAttribute extends NodeBase {
  12513. render(code, options, { jsxMode } = BLANK) {
  12514. super.render(code, options);
  12515. if (['classic', 'automatic'].includes(jsxMode)) {
  12516. const { name, value } = this;
  12517. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  12518. if (!(jsxMode === 'automatic' && key === 'key')) {
  12519. const safeKey = stringifyObjectKeyIfNeeded(key);
  12520. if (key !== safeKey) {
  12521. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  12522. }
  12523. if (value) {
  12524. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  12525. }
  12526. else {
  12527. code.appendLeft(name.end, ': true');
  12528. }
  12529. }
  12530. }
  12531. }
  12532. }
  12533. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  12534. class JSXClosingBase extends NodeBase {
  12535. render(code, options) {
  12536. const { mode } = this.scope.context.options.jsx;
  12537. if (mode !== 'preserve') {
  12538. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  12539. }
  12540. else {
  12541. super.render(code, options);
  12542. }
  12543. }
  12544. }
  12545. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  12546. class JSXClosingElement extends JSXClosingBase {
  12547. }
  12548. class JSXClosingFragment extends JSXClosingBase {
  12549. }
  12550. class JSXSpreadAttribute extends NodeBase {
  12551. render(code, options) {
  12552. this.argument.render(code, options);
  12553. const { mode } = this.scope.context.options.jsx;
  12554. if (mode !== 'preserve') {
  12555. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  12556. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  12557. }
  12558. }
  12559. }
  12560. class JSXEmptyExpression extends NodeBase {
  12561. }
  12562. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  12563. class JSXExpressionContainer extends NodeBase {
  12564. includeNode(context) {
  12565. this.included = true;
  12566. if (!this.deoptimized)
  12567. this.applyDeoptimizations();
  12568. this.expression.includePath(UNKNOWN_PATH, context);
  12569. }
  12570. render(code, options) {
  12571. const { mode } = this.scope.context.options.jsx;
  12572. if (mode !== 'preserve') {
  12573. code.remove(this.start, this.expression.start);
  12574. code.remove(this.expression.end, this.end);
  12575. }
  12576. this.expression.render(code, options);
  12577. }
  12578. }
  12579. function getRenderedJsxChildren(children) {
  12580. let renderedChildren = 0;
  12581. for (const child of children) {
  12582. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression)) {
  12583. renderedChildren++;
  12584. }
  12585. }
  12586. return renderedChildren;
  12587. }
  12588. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  12589. const [baseName, nestedName] = factory.split('.');
  12590. let factoryVariable;
  12591. if (importSource) {
  12592. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  12593. if (preserve) {
  12594. // This pretends we are accessing an included global variable of the same name
  12595. const globalVariable = node.scope.findGlobal(baseName);
  12596. globalVariable.includePath(UNKNOWN_PATH, context);
  12597. // This excludes this variable from renaming
  12598. factoryVariable.globalName = baseName;
  12599. }
  12600. }
  12601. else {
  12602. factoryVariable = node.scope.findGlobal(baseName);
  12603. }
  12604. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  12605. if (factoryVariable instanceof LocalVariable) {
  12606. factoryVariable.consolidateInitializers();
  12607. factoryVariable.addUsedPlace(node);
  12608. node.scope.context.requestTreeshakingPass();
  12609. }
  12610. return factoryVariable;
  12611. }
  12612. class JSXElementBase extends NodeBase {
  12613. constructor() {
  12614. super(...arguments);
  12615. this.factoryVariable = null;
  12616. this.factory = null;
  12617. }
  12618. initialise() {
  12619. super.initialise();
  12620. const { importSource } = (this.jsxMode = this.getRenderingMode());
  12621. if (importSource) {
  12622. this.scope.context.addImportSource(importSource);
  12623. }
  12624. }
  12625. include(context, includeChildrenRecursively) {
  12626. if (!this.included)
  12627. this.includeNode(context);
  12628. for (const child of this.children) {
  12629. child.include(context, includeChildrenRecursively);
  12630. }
  12631. }
  12632. includeNode(context) {
  12633. this.included = true;
  12634. const { factory, importSource, mode } = this.jsxMode;
  12635. if (factory) {
  12636. this.factory = factory;
  12637. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  12638. }
  12639. }
  12640. getRenderingMode() {
  12641. const jsx = this.scope.context.options.jsx;
  12642. const { mode, factory, importSource } = jsx;
  12643. if (mode === 'automatic') {
  12644. return {
  12645. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  12646. importSource: jsx.jsxImportSource,
  12647. mode
  12648. };
  12649. }
  12650. return { factory, importSource, mode };
  12651. }
  12652. renderChildren(code, options, openingEnd) {
  12653. const { children } = this;
  12654. let hasMultipleChildren = false;
  12655. let childrenEnd = openingEnd;
  12656. let firstChild = null;
  12657. for (const child of children) {
  12658. if (child instanceof JSXExpressionContainer &&
  12659. child.expression instanceof JSXEmptyExpression) {
  12660. code.remove(childrenEnd, child.end);
  12661. }
  12662. else {
  12663. code.appendLeft(childrenEnd, ', ');
  12664. child.render(code, options);
  12665. if (firstChild) {
  12666. hasMultipleChildren = true;
  12667. }
  12668. else {
  12669. firstChild = child;
  12670. }
  12671. }
  12672. childrenEnd = child.end;
  12673. }
  12674. return { childrenEnd, firstChild, hasMultipleChildren };
  12675. }
  12676. }
  12677. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  12678. class JSXElement extends JSXElementBase {
  12679. include(context, includeChildrenRecursively) {
  12680. super.include(context, includeChildrenRecursively);
  12681. this.openingElement.include(context, includeChildrenRecursively);
  12682. this.closingElement?.include(context, includeChildrenRecursively);
  12683. }
  12684. render(code, options) {
  12685. switch (this.jsxMode.mode) {
  12686. case 'classic': {
  12687. this.renderClassicMode(code, options);
  12688. break;
  12689. }
  12690. case 'automatic': {
  12691. this.renderAutomaticMode(code, options);
  12692. break;
  12693. }
  12694. default: {
  12695. super.render(code, options);
  12696. }
  12697. }
  12698. }
  12699. getRenderingMode() {
  12700. const jsx = this.scope.context.options.jsx;
  12701. const { mode, factory, importSource } = jsx;
  12702. if (mode === 'automatic') {
  12703. // In the case there is a key after a spread attribute, we fall back to
  12704. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  12705. // for reasoning.
  12706. let hasSpread = false;
  12707. for (const attribute of this.openingElement.attributes) {
  12708. if (attribute instanceof JSXSpreadAttribute) {
  12709. hasSpread = true;
  12710. }
  12711. else if (hasSpread && attribute.name.name === 'key') {
  12712. return { factory, importSource, mode: 'classic' };
  12713. }
  12714. }
  12715. }
  12716. return super.getRenderingMode();
  12717. }
  12718. renderClassicMode(code, options) {
  12719. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12720. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  12721. const [, ...nestedName] = factory.split('.');
  12722. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  12723. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  12724. this.renderChildren(code, options, openingEnd);
  12725. if (selfClosing) {
  12726. code.appendLeft(end, ')');
  12727. }
  12728. else {
  12729. closingElement.render(code, options);
  12730. }
  12731. }
  12732. renderAutomaticMode(code, options) {
  12733. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12734. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  12735. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  12736. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  12737. if (firstChild) {
  12738. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  12739. if (!inObject) {
  12740. code.prependRight(firstChild.start, '{ ');
  12741. inObject = true;
  12742. }
  12743. previousEnd = closingElement.start;
  12744. if (hasMultipleChildren) {
  12745. code.appendLeft(previousEnd, ']');
  12746. }
  12747. }
  12748. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  12749. if (keyAttribute) {
  12750. const { value } = keyAttribute;
  12751. // This will appear to the left of the moved code...
  12752. code.appendLeft(childrenEnd, ', ');
  12753. if (value) {
  12754. code.move(value.start, value.end, childrenEnd);
  12755. }
  12756. else {
  12757. code.appendLeft(childrenEnd, 'true');
  12758. }
  12759. }
  12760. if (selfClosing) {
  12761. // Moving the key attribute will also move the parenthesis to the right position
  12762. code.appendLeft(keyAttribute?.value?.end || end, ')');
  12763. }
  12764. else {
  12765. closingElement.render(code, options);
  12766. }
  12767. }
  12768. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  12769. const { jsxMode: { mode }, openingElement } = this;
  12770. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  12771. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  12772. openingElement.render(code, options, { jsxMode: mode });
  12773. let keyAttribute = null;
  12774. let hasSpread = false;
  12775. let inObject = false;
  12776. let previousEnd = nameEnd;
  12777. let hasAttributes = false;
  12778. let firstAttribute = null;
  12779. for (const attribute of attributes) {
  12780. if (attribute instanceof JSXAttribute) {
  12781. if (extractKeyAttribute && attribute.name.name === 'key') {
  12782. keyAttribute = attribute;
  12783. code.remove(previousEnd, attribute.value?.start || attribute.end);
  12784. continue;
  12785. }
  12786. code.appendLeft(previousEnd, ',');
  12787. if (!inObject) {
  12788. code.prependRight(attribute.start, '{ ');
  12789. inObject = true;
  12790. }
  12791. hasAttributes = true;
  12792. }
  12793. else {
  12794. if (inObject) {
  12795. if (hasAttributes) {
  12796. code.appendLeft(previousEnd, ' ');
  12797. }
  12798. code.appendLeft(previousEnd, '},');
  12799. inObject = false;
  12800. }
  12801. else {
  12802. code.appendLeft(previousEnd, ',');
  12803. }
  12804. hasSpread = true;
  12805. }
  12806. previousEnd = attribute.end;
  12807. if (!firstAttribute) {
  12808. firstAttribute = attribute;
  12809. }
  12810. }
  12811. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  12812. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  12813. }
  12814. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  12815. if (inObject) {
  12816. code.appendLeft(attributesEnd, ' }');
  12817. }
  12818. if (hasSpread) {
  12819. if (hasAttributes) {
  12820. const { start } = firstAttribute;
  12821. if (firstAttribute instanceof JSXSpreadAttribute) {
  12822. code.prependRight(start, '{}, ');
  12823. }
  12824. code.prependRight(start, 'Object.assign(');
  12825. code.appendLeft(attributesEnd, ')');
  12826. }
  12827. }
  12828. else if (!hasAttributes) {
  12829. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  12830. }
  12831. }
  12832. }
  12833. class JSXFragment extends JSXElementBase {
  12834. include(context, includeChildrenRecursively) {
  12835. super.include(context, includeChildrenRecursively);
  12836. this.openingFragment.include(context, includeChildrenRecursively);
  12837. this.closingFragment.include(context, includeChildrenRecursively);
  12838. }
  12839. render(code, options) {
  12840. switch (this.jsxMode.mode) {
  12841. case 'classic': {
  12842. this.renderClassicMode(code, options);
  12843. break;
  12844. }
  12845. case 'automatic': {
  12846. this.renderAutomaticMode(code, options);
  12847. break;
  12848. }
  12849. default: {
  12850. super.render(code, options);
  12851. }
  12852. }
  12853. }
  12854. renderClassicMode(code, options) {
  12855. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12856. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  12857. const [, ...nestedName] = factory.split('.');
  12858. openingFragment.render(code, options);
  12859. code.prependRight(start, `/*#__PURE__*/${[
  12860. factoryVariable.getName(getPropertyAccess, useOriginalName),
  12861. ...nestedName
  12862. ].join('.')}(`);
  12863. code.appendLeft(openingFragment.end, ', null');
  12864. this.renderChildren(code, options, openingFragment.end);
  12865. closingFragment.render(code, options);
  12866. }
  12867. renderAutomaticMode(code, options) {
  12868. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12869. const { closingFragment, factoryVariable, openingFragment, start } = this;
  12870. openingFragment.render(code, options);
  12871. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  12872. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  12873. if (firstChild) {
  12874. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  12875. if (hasMultipleChildren) {
  12876. code.appendLeft(closingFragment.start, ']');
  12877. }
  12878. code.appendLeft(childrenEnd, ' }');
  12879. }
  12880. else {
  12881. code.appendLeft(openingFragment.end, ', {}');
  12882. }
  12883. closingFragment.render(code, options);
  12884. }
  12885. }
  12886. class JSXMemberExpression extends NodeBase {
  12887. includeNode(context) {
  12888. this.included = true;
  12889. if (!this.deoptimized)
  12890. this.applyDeoptimizations();
  12891. this.object.includePath([this.property.name], context);
  12892. }
  12893. includePath(path, context) {
  12894. if (!this.included)
  12895. this.includeNode(context);
  12896. this.object.includePath([this.property.name, ...path], context);
  12897. }
  12898. }
  12899. class JSXNamespacedName extends NodeBase {
  12900. }
  12901. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  12902. class JSXOpeningElement extends NodeBase {
  12903. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  12904. this.name.render(code, options);
  12905. for (const attribute of this.attributes) {
  12906. attribute.render(code, options, { jsxMode });
  12907. }
  12908. }
  12909. }
  12910. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  12911. class JSXOpeningFragment extends NodeBase {
  12912. constructor() {
  12913. super(...arguments);
  12914. this.fragment = null;
  12915. this.fragmentVariable = null;
  12916. }
  12917. includeNode(context) {
  12918. this.included = true;
  12919. if (!this.deoptimized)
  12920. this.applyDeoptimizations();
  12921. const jsx = this.scope.context.options.jsx;
  12922. if (jsx.mode === 'automatic') {
  12923. this.fragment = 'Fragment';
  12924. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  12925. }
  12926. else {
  12927. const { fragment, importSource, mode } = jsx;
  12928. if (fragment != null) {
  12929. this.fragment = fragment;
  12930. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  12931. }
  12932. }
  12933. }
  12934. render(code, options) {
  12935. const { mode } = this.scope.context.options.jsx;
  12936. if (mode !== 'preserve') {
  12937. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12938. const [, ...nestedFragment] = this.fragment.split('.');
  12939. const fragment = [
  12940. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  12941. ...nestedFragment
  12942. ].join('.');
  12943. code.update(this.start, this.end, fragment);
  12944. }
  12945. }
  12946. }
  12947. class JSXSpreadChild extends NodeBase {
  12948. render(code, options) {
  12949. super.render(code, options);
  12950. const { mode } = this.scope.context.options.jsx;
  12951. if (mode !== 'preserve') {
  12952. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  12953. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  12954. }
  12955. }
  12956. }
  12957. class JSXText extends NodeBase {
  12958. render(code) {
  12959. const { mode } = this.scope.context.options.jsx;
  12960. if (mode !== 'preserve') {
  12961. code.overwrite(this.start, this.end, JSON.stringify(this.value), {
  12962. contentOnly: true
  12963. });
  12964. }
  12965. }
  12966. }
  12967. JSXText.prototype.includeNode = onlyIncludeSelf;
  12968. class LabeledStatement extends NodeBase {
  12969. hasEffects(context) {
  12970. const { brokenFlow, includedLabels } = context;
  12971. context.ignore.labels.add(this.label.name);
  12972. context.includedLabels = new Set();
  12973. let bodyHasEffects = false;
  12974. if (this.body.hasEffects(context)) {
  12975. bodyHasEffects = true;
  12976. }
  12977. else {
  12978. context.ignore.labels.delete(this.label.name);
  12979. if (context.includedLabels.has(this.label.name)) {
  12980. context.includedLabels.delete(this.label.name);
  12981. context.brokenFlow = brokenFlow;
  12982. }
  12983. }
  12984. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  12985. return bodyHasEffects;
  12986. }
  12987. include(context, includeChildrenRecursively) {
  12988. if (!this.included)
  12989. this.includeNode(context);
  12990. const { brokenFlow, includedLabels } = context;
  12991. context.includedLabels = new Set();
  12992. this.body.include(context, includeChildrenRecursively);
  12993. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  12994. this.label.include(context, includeChildrenRecursively);
  12995. context.includedLabels.delete(this.label.name);
  12996. context.brokenFlow = brokenFlow;
  12997. }
  12998. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  12999. }
  13000. includeNode(context) {
  13001. this.included = true;
  13002. this.body.includePath(UNKNOWN_PATH, context);
  13003. }
  13004. render(code, options) {
  13005. if (this.label.included) {
  13006. this.label.render(code, options);
  13007. }
  13008. else {
  13009. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  13010. }
  13011. this.body.render(code, options);
  13012. }
  13013. }
  13014. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13015. class LogicalExpression extends NodeBase {
  13016. constructor() {
  13017. super(...arguments);
  13018. // We collect deoptimization information if usedBranch !== null
  13019. this.expressionsToBeDeoptimized = [];
  13020. this.usedBranch = null;
  13021. }
  13022. //private isBranchResolutionAnalysed = false;
  13023. get isBranchResolutionAnalysed() {
  13024. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  13025. }
  13026. set isBranchResolutionAnalysed(value) {
  13027. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  13028. }
  13029. get hasDeoptimizedCache() {
  13030. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  13031. }
  13032. set hasDeoptimizedCache(value) {
  13033. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  13034. }
  13035. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13036. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13037. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13038. }
  13039. deoptimizeCache() {
  13040. if (this.hasDeoptimizedCache)
  13041. return;
  13042. this.hasDeoptimizedCache = true;
  13043. if (this.usedBranch) {
  13044. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  13045. this.usedBranch = null;
  13046. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  13047. if (this.included) {
  13048. // As we are not tracking inclusions, we just include everything
  13049. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  13050. }
  13051. }
  13052. const { scope: { context }, expressionsToBeDeoptimized } = this;
  13053. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  13054. for (const expression of expressionsToBeDeoptimized) {
  13055. expression.deoptimizeCache();
  13056. }
  13057. // Request another pass because we need to ensure "include" runs again if
  13058. // it is rendered
  13059. context.requestTreeshakingPass();
  13060. }
  13061. deoptimizePath(path) {
  13062. const usedBranch = this.getUsedBranch();
  13063. if (usedBranch) {
  13064. usedBranch.deoptimizePath(path);
  13065. }
  13066. else {
  13067. this.left.deoptimizePath(path);
  13068. this.right.deoptimizePath(path);
  13069. }
  13070. }
  13071. getLiteralValueAtPath(path, recursionTracker, origin) {
  13072. if (origin === this)
  13073. return UnknownValue;
  13074. const usedBranch = this.getUsedBranch();
  13075. if (usedBranch) {
  13076. this.expressionsToBeDeoptimized.push(origin);
  13077. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  13078. }
  13079. else if (!this.hasDeoptimizedCache && !path.length) {
  13080. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  13081. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  13082. if (typeof booleanOrUnknown !== 'symbol') {
  13083. if (!booleanOrUnknown && this.operator === '&&') {
  13084. this.expressionsToBeDeoptimized.push(origin);
  13085. return UnknownFalsyValue;
  13086. }
  13087. if (booleanOrUnknown && this.operator === '||') {
  13088. this.expressionsToBeDeoptimized.push(origin);
  13089. return UnknownTruthyValue;
  13090. }
  13091. }
  13092. }
  13093. return UnknownValue;
  13094. }
  13095. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13096. const usedBranch = this.getUsedBranch();
  13097. if (usedBranch) {
  13098. this.expressionsToBeDeoptimized.push(origin);
  13099. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13100. }
  13101. return [
  13102. new MultiExpression([
  13103. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13104. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13105. ]),
  13106. false
  13107. ];
  13108. }
  13109. hasEffects(context) {
  13110. if (this.left.hasEffects(context)) {
  13111. return true;
  13112. }
  13113. if (this.getUsedBranch() !== this.left) {
  13114. return this.right.hasEffects(context);
  13115. }
  13116. return false;
  13117. }
  13118. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13119. const usedBranch = this.getUsedBranch();
  13120. if (usedBranch) {
  13121. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13122. }
  13123. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13124. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  13125. }
  13126. include(context, includeChildrenRecursively) {
  13127. this.included = true;
  13128. const usedBranch = this.getUsedBranch();
  13129. if (includeChildrenRecursively ||
  13130. !usedBranch ||
  13131. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13132. this.left.include(context, includeChildrenRecursively);
  13133. this.right.include(context, includeChildrenRecursively);
  13134. }
  13135. else {
  13136. usedBranch.include(context, includeChildrenRecursively);
  13137. }
  13138. }
  13139. includePath(path, context) {
  13140. this.included = true;
  13141. const usedBranch = this.getUsedBranch();
  13142. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13143. this.left.includePath(path, context);
  13144. this.right.includePath(path, context);
  13145. }
  13146. else {
  13147. usedBranch.includePath(path, context);
  13148. }
  13149. }
  13150. removeAnnotations(code) {
  13151. this.left.removeAnnotations(code);
  13152. }
  13153. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  13154. if (!this.left.included || !this.right.included) {
  13155. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  13156. if (this.right.included) {
  13157. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  13158. code.remove(this.start, removePos);
  13159. if (preventASI) {
  13160. removeLineBreaks(code, removePos, this.right.start);
  13161. }
  13162. this.left.removeAnnotations(code);
  13163. }
  13164. else {
  13165. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  13166. }
  13167. this.getUsedBranch().render(code, options, {
  13168. isCalleeOfRenderedParent,
  13169. preventASI,
  13170. renderedParentType: renderedParentType || this.parent.type,
  13171. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13172. });
  13173. }
  13174. else {
  13175. this.left.render(code, options, {
  13176. preventASI,
  13177. renderedSurroundingElement
  13178. });
  13179. this.right.render(code, options);
  13180. }
  13181. }
  13182. getUsedBranch() {
  13183. if (!this.isBranchResolutionAnalysed) {
  13184. this.isBranchResolutionAnalysed = true;
  13185. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13186. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  13187. if (typeof booleanOrUnknown === 'symbol') {
  13188. return null;
  13189. }
  13190. else {
  13191. this.usedBranch =
  13192. (this.operator === '||' && booleanOrUnknown) ||
  13193. (this.operator === '&&' && !booleanOrUnknown) ||
  13194. (this.operator === '??' && leftValue != null)
  13195. ? this.left
  13196. : this.right;
  13197. }
  13198. }
  13199. return this.usedBranch;
  13200. }
  13201. }
  13202. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13203. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13204. class NewExpression extends NodeBase {
  13205. hasEffects(context) {
  13206. if (!this.deoptimized)
  13207. this.applyDeoptimizations();
  13208. for (const argument of this.arguments) {
  13209. if (argument.hasEffects(context))
  13210. return true;
  13211. }
  13212. if (this.annotationPure) {
  13213. return false;
  13214. }
  13215. return (this.callee.hasEffects(context) ||
  13216. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13217. }
  13218. hasEffectsOnInteractionAtPath(path, { type }) {
  13219. return path.length > 0 || type !== INTERACTION_ACCESSED;
  13220. }
  13221. include(context, includeChildrenRecursively) {
  13222. if (!this.included)
  13223. this.includeNode(context);
  13224. if (includeChildrenRecursively) {
  13225. super.include(context, true);
  13226. }
  13227. else {
  13228. this.callee.include(context, false);
  13229. this.callee.includeCallArguments(this.interaction, context);
  13230. }
  13231. }
  13232. includeNode(context) {
  13233. this.included = true;
  13234. if (!this.deoptimized)
  13235. this.applyDeoptimizations();
  13236. this.callee.includePath(UNKNOWN_PATH, context);
  13237. }
  13238. initialise() {
  13239. super.initialise();
  13240. this.interaction = {
  13241. args: [null, ...this.arguments],
  13242. type: INTERACTION_CALLED,
  13243. withNew: true
  13244. };
  13245. if (this.annotations &&
  13246. this.scope.context.options.treeshake.annotations) {
  13247. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  13248. }
  13249. }
  13250. render(code, options) {
  13251. this.callee.render(code, options);
  13252. renderCallArguments(code, options, this);
  13253. }
  13254. applyDeoptimizations() {
  13255. this.deoptimized = true;
  13256. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13257. this.scope.context.requestTreeshakingPass();
  13258. }
  13259. }
  13260. class ObjectExpression extends NodeBase {
  13261. constructor() {
  13262. super(...arguments);
  13263. this.objectEntity = null;
  13264. this.protoProp = null;
  13265. }
  13266. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13267. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13268. }
  13269. deoptimizeCache() {
  13270. this.getObjectEntity().deoptimizeAllProperties();
  13271. }
  13272. deoptimizePath(path) {
  13273. this.getObjectEntity().deoptimizePath(path);
  13274. }
  13275. getLiteralValueAtPath(path, recursionTracker, origin) {
  13276. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  13277. }
  13278. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13279. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13280. }
  13281. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13282. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  13283. }
  13284. include(context, includeChildrenRecursively) {
  13285. if (!this.included)
  13286. this.includeNode(context);
  13287. this.getObjectEntity().include(context, includeChildrenRecursively);
  13288. this.protoProp?.include(context, includeChildrenRecursively);
  13289. }
  13290. includeNode(context) {
  13291. this.included = true;
  13292. this.protoProp?.includePath(UNKNOWN_PATH, context);
  13293. }
  13294. includePath(path, context) {
  13295. if (!this.included)
  13296. this.includeNode(context);
  13297. this.getObjectEntity().includePath(path, context);
  13298. }
  13299. render(code, options, { renderedSurroundingElement } = BLANK) {
  13300. if (renderedSurroundingElement === ExpressionStatement$1 ||
  13301. renderedSurroundingElement === ArrowFunctionExpression$1) {
  13302. code.appendRight(this.start, '(');
  13303. code.prependLeft(this.end, ')');
  13304. }
  13305. if (this.properties.length > 0) {
  13306. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  13307. let lastSeparatorPos = null;
  13308. for (const { node, separator, start, end } of separatedNodes) {
  13309. if (!node.included) {
  13310. treeshakeNode(node, code, start, end);
  13311. continue;
  13312. }
  13313. lastSeparatorPos = separator;
  13314. node.render(code, options);
  13315. }
  13316. if (lastSeparatorPos) {
  13317. code.remove(lastSeparatorPos, this.end - 1);
  13318. }
  13319. }
  13320. }
  13321. getObjectEntity() {
  13322. if (this.objectEntity !== null) {
  13323. return this.objectEntity;
  13324. }
  13325. let prototype = OBJECT_PROTOTYPE;
  13326. const properties = [];
  13327. for (const property of this.properties) {
  13328. if (property instanceof SpreadElement) {
  13329. properties.push({ key: UnknownKey, kind: 'init', property });
  13330. continue;
  13331. }
  13332. let key;
  13333. if (property.computed) {
  13334. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13335. if (typeof keyValue === 'symbol') {
  13336. properties.push({ key: UnknownKey, kind: property.kind, property });
  13337. continue;
  13338. }
  13339. else {
  13340. key = String(keyValue);
  13341. }
  13342. }
  13343. else {
  13344. key =
  13345. property.key instanceof Identifier
  13346. ? property.key.name
  13347. : String(property.key.value);
  13348. if (key === '__proto__' && property.kind === 'init') {
  13349. this.protoProp = property;
  13350. prototype =
  13351. property.value instanceof Literal && property.value.value === null
  13352. ? null
  13353. : property.value;
  13354. continue;
  13355. }
  13356. }
  13357. properties.push({ key, kind: property.kind, property });
  13358. }
  13359. return (this.objectEntity = new ObjectEntity(properties, prototype));
  13360. }
  13361. }
  13362. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13363. class PanicError extends NodeBase {
  13364. initialise() {
  13365. const id = this.scope.context.module.id;
  13366. // This simulates the current nested error structure. We could also just
  13367. // replace it with a flat error.
  13368. const parseError = getRollupError(logParseError(this.message));
  13369. const moduleParseError = logModuleParseError(parseError, id);
  13370. return error(moduleParseError);
  13371. }
  13372. }
  13373. class ParseError extends NodeBase {
  13374. initialise() {
  13375. const pos = this.start;
  13376. const id = this.scope.context.module.id;
  13377. // This simulates the current nested error structure. We could also just
  13378. // replace it with a flat error.
  13379. const parseError = getRollupError(logParseError(this.message, pos));
  13380. const moduleParseError = logModuleParseError(parseError, id);
  13381. this.scope.context.error(moduleParseError, pos);
  13382. }
  13383. }
  13384. class PrivateIdentifier extends NodeBase {
  13385. }
  13386. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  13387. class Program extends NodeBase {
  13388. constructor() {
  13389. super(...arguments);
  13390. this.hasCachedEffect = null;
  13391. this.hasLoggedEffect = false;
  13392. }
  13393. hasCachedEffects() {
  13394. if (!this.included) {
  13395. return false;
  13396. }
  13397. return this.hasCachedEffect === null
  13398. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  13399. : this.hasCachedEffect;
  13400. }
  13401. hasEffects(context) {
  13402. for (const node of this.body) {
  13403. if (node.hasEffects(context)) {
  13404. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  13405. this.hasLoggedEffect = true;
  13406. const { code, log, module } = this.scope.context;
  13407. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  13408. }
  13409. return (this.hasCachedEffect = true);
  13410. }
  13411. }
  13412. return false;
  13413. }
  13414. include(context, includeChildrenRecursively) {
  13415. this.included = true;
  13416. for (const node of this.body) {
  13417. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  13418. node.include(context, includeChildrenRecursively);
  13419. }
  13420. }
  13421. }
  13422. initialise() {
  13423. super.initialise();
  13424. if (this.invalidAnnotations)
  13425. for (const { start, end, type } of this.invalidAnnotations) {
  13426. this.scope.context.magicString.remove(start, end);
  13427. if (type === 'pure' || type === 'noSideEffects') {
  13428. this.scope.context.log(LOGLEVEL_WARN, logInvalidAnnotation(this.scope.context.code.slice(start, end), this.scope.context.module.id, type), start);
  13429. }
  13430. }
  13431. }
  13432. render(code, options) {
  13433. let start = this.start;
  13434. if (code.original.startsWith('#!')) {
  13435. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  13436. code.remove(0, start);
  13437. }
  13438. if (this.body.length > 0) {
  13439. // Keep all consecutive lines that start with a comment
  13440. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  13441. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  13442. if (firstLineBreak[0] === -1) {
  13443. break;
  13444. }
  13445. start += firstLineBreak[1];
  13446. }
  13447. renderStatementList(this.body, code, start, this.end, options);
  13448. }
  13449. else {
  13450. super.render(code, options);
  13451. }
  13452. }
  13453. }
  13454. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13455. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  13456. class Property extends MethodBase {
  13457. //declare method: boolean;
  13458. get method() {
  13459. return isFlagSet(this.flags, 262144 /* Flag.method */);
  13460. }
  13461. set method(value) {
  13462. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  13463. }
  13464. //declare shorthand: boolean;
  13465. get shorthand() {
  13466. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  13467. }
  13468. set shorthand(value) {
  13469. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  13470. }
  13471. declare(kind, destructuredInitPath, init) {
  13472. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  13473. }
  13474. deoptimizeAssignment(destructuredInitPath, init) {
  13475. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  13476. }
  13477. hasEffects(context) {
  13478. return this.key.hasEffects(context) || this.value.hasEffects(context);
  13479. }
  13480. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  13481. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  13482. }
  13483. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  13484. const path = this.getPathInProperty(destructuredInitPath);
  13485. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  13486. this.included;
  13487. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  13488. this.key.include(context, false);
  13489. if (!this.value.included) {
  13490. this.value.included = true;
  13491. // Unfortunately, we need to include the value again now, so that any
  13492. // declared variables are properly included.
  13493. this.value.includeDestructuredIfNecessary(context, path, init);
  13494. }
  13495. }
  13496. return (this.included = included);
  13497. }
  13498. include(context, includeChildrenRecursively) {
  13499. this.included = true;
  13500. this.key.include(context, includeChildrenRecursively);
  13501. this.value.include(context, includeChildrenRecursively);
  13502. }
  13503. includePath(path, context) {
  13504. this.included = true;
  13505. this.value.includePath(path, context);
  13506. }
  13507. markDeclarationReached() {
  13508. this.value.markDeclarationReached();
  13509. }
  13510. render(code, options) {
  13511. if (!this.shorthand) {
  13512. this.key.render(code, options);
  13513. }
  13514. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  13515. }
  13516. getPathInProperty(destructuredInitPath) {
  13517. return destructuredInitPath.at(-1) === UnknownKey
  13518. ? destructuredInitPath
  13519. : // For now, we only consider static paths as we do not know how to
  13520. // deoptimize the path in the dynamic case.
  13521. this.computed
  13522. ? [...destructuredInitPath, UnknownKey]
  13523. : this.key instanceof Identifier
  13524. ? [...destructuredInitPath, this.key.name]
  13525. : [...destructuredInitPath, String(this.key.value)];
  13526. }
  13527. }
  13528. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13529. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  13530. class PropertyDefinition extends NodeBase {
  13531. get computed() {
  13532. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  13533. }
  13534. set computed(value) {
  13535. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  13536. }
  13537. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13538. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13539. }
  13540. deoptimizePath(path) {
  13541. this.value?.deoptimizePath(path);
  13542. }
  13543. getLiteralValueAtPath(path, recursionTracker, origin) {
  13544. return this.value
  13545. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  13546. : UnknownValue;
  13547. }
  13548. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13549. return this.value
  13550. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  13551. : UNKNOWN_RETURN_EXPRESSION;
  13552. }
  13553. hasEffects(context) {
  13554. return (this.key.hasEffects(context) ||
  13555. (this.static && !!this.value?.hasEffects(context)) ||
  13556. checkEffectForNodes(this.decorators, context));
  13557. }
  13558. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13559. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  13560. }
  13561. includeNode(context) {
  13562. this.included = true;
  13563. this.value?.includePath(UNKNOWN_PATH, context);
  13564. for (const decorator of this.decorators) {
  13565. decorator.includePath(UNKNOWN_PATH, context);
  13566. }
  13567. }
  13568. }
  13569. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  13570. class ReturnStatement extends NodeBase {
  13571. hasEffects(context) {
  13572. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  13573. return true;
  13574. context.brokenFlow = true;
  13575. return false;
  13576. }
  13577. include(context, includeChildrenRecursively) {
  13578. if (!this.included)
  13579. this.includeNode(context);
  13580. this.argument?.include(context, includeChildrenRecursively);
  13581. context.brokenFlow = true;
  13582. }
  13583. includeNode(context) {
  13584. this.included = true;
  13585. this.argument?.includePath(UNKNOWN_PATH, context);
  13586. }
  13587. initialise() {
  13588. super.initialise();
  13589. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  13590. }
  13591. render(code, options) {
  13592. if (this.argument) {
  13593. this.argument.render(code, options, { preventASI: true });
  13594. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  13595. code.prependLeft(this.start + 6, ' ');
  13596. }
  13597. }
  13598. }
  13599. }
  13600. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13601. class SequenceExpression extends NodeBase {
  13602. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13603. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13604. }
  13605. deoptimizePath(path) {
  13606. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  13607. }
  13608. getLiteralValueAtPath(path, recursionTracker, origin) {
  13609. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  13610. }
  13611. hasEffects(context) {
  13612. for (const expression of this.expressions) {
  13613. if (expression.hasEffects(context))
  13614. return true;
  13615. }
  13616. return false;
  13617. }
  13618. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13619. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  13620. }
  13621. include(context, includeChildrenRecursively) {
  13622. this.included = true;
  13623. const lastExpression = this.expressions[this.expressions.length - 1];
  13624. for (const expression of this.expressions) {
  13625. if (includeChildrenRecursively ||
  13626. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  13627. expression.shouldBeIncluded(context)) {
  13628. expression.include(context, includeChildrenRecursively);
  13629. }
  13630. }
  13631. }
  13632. includePath(path, context) {
  13633. this.included = true;
  13634. this.expressions[this.expressions.length - 1].includePath(path, context);
  13635. }
  13636. removeAnnotations(code) {
  13637. this.expressions[0].removeAnnotations(code);
  13638. }
  13639. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  13640. let includedNodes = 0;
  13641. let lastSeparatorPos = null;
  13642. const lastNode = this.expressions[this.expressions.length - 1];
  13643. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  13644. if (!node.included) {
  13645. treeshakeNode(node, code, start, end);
  13646. continue;
  13647. }
  13648. includedNodes++;
  13649. lastSeparatorPos = separator;
  13650. if (includedNodes === 1 && preventASI) {
  13651. removeLineBreaks(code, start, node.start);
  13652. }
  13653. if (includedNodes === 1) {
  13654. const parentType = renderedParentType || this.parent.type;
  13655. node.render(code, options, {
  13656. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  13657. renderedParentType: parentType,
  13658. renderedSurroundingElement: parentType
  13659. });
  13660. }
  13661. else {
  13662. node.render(code, options);
  13663. }
  13664. }
  13665. if (lastSeparatorPos) {
  13666. code.remove(lastSeparatorPos, this.end);
  13667. }
  13668. }
  13669. }
  13670. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13671. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13672. class Super extends NodeBase {
  13673. bind() {
  13674. this.variable = this.scope.findVariable('this');
  13675. }
  13676. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13677. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13678. }
  13679. deoptimizePath(path) {
  13680. this.variable.deoptimizePath(path);
  13681. }
  13682. include(context) {
  13683. if (!this.included)
  13684. this.includeNode(context);
  13685. }
  13686. includeNode(context) {
  13687. this.included = true;
  13688. if (!this.deoptimized)
  13689. this.applyDeoptimizations();
  13690. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  13691. }
  13692. }
  13693. class SwitchCase extends NodeBase {
  13694. hasEffects(context) {
  13695. if (this.test?.hasEffects(context))
  13696. return true;
  13697. for (const node of this.consequent) {
  13698. if (context.brokenFlow)
  13699. break;
  13700. if (node.hasEffects(context))
  13701. return true;
  13702. }
  13703. return false;
  13704. }
  13705. include(context, includeChildrenRecursively) {
  13706. this.included = true;
  13707. this.test?.include(context, includeChildrenRecursively);
  13708. for (const node of this.consequent) {
  13709. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  13710. node.include(context, includeChildrenRecursively);
  13711. }
  13712. }
  13713. render(code, options, nodeRenderOptions) {
  13714. if (this.test) {
  13715. this.test.render(code, options);
  13716. if (this.test.start === this.start + 4) {
  13717. code.prependLeft(this.test.start, ' ');
  13718. }
  13719. }
  13720. if (this.consequent.length > 0) {
  13721. const testEnd = this.test
  13722. ? this.test.end
  13723. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  13724. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  13725. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  13726. }
  13727. }
  13728. }
  13729. SwitchCase.prototype.needsBoundaries = true;
  13730. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13731. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  13732. class SwitchStatement extends NodeBase {
  13733. createScope(parentScope) {
  13734. this.parentScope = parentScope;
  13735. this.scope = new BlockScope(parentScope);
  13736. }
  13737. hasEffects(context) {
  13738. if (this.discriminant.hasEffects(context))
  13739. return true;
  13740. const { brokenFlow, hasBreak, ignore } = context;
  13741. const { breaks } = ignore;
  13742. ignore.breaks = true;
  13743. context.hasBreak = false;
  13744. let onlyHasBrokenFlow = true;
  13745. for (const switchCase of this.cases) {
  13746. if (switchCase.hasEffects(context))
  13747. return true;
  13748. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  13749. context.hasBreak = false;
  13750. context.brokenFlow = brokenFlow;
  13751. }
  13752. if (this.defaultCase !== null) {
  13753. context.brokenFlow = onlyHasBrokenFlow;
  13754. }
  13755. ignore.breaks = breaks;
  13756. context.hasBreak = hasBreak;
  13757. return false;
  13758. }
  13759. include(context, includeChildrenRecursively) {
  13760. this.included = true;
  13761. this.discriminant.include(context, includeChildrenRecursively);
  13762. const { brokenFlow, hasBreak } = context;
  13763. context.hasBreak = false;
  13764. let onlyHasBrokenFlow = true;
  13765. let isCaseIncluded = includeChildrenRecursively ||
  13766. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  13767. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  13768. const switchCase = this.cases[caseIndex];
  13769. if (switchCase.included) {
  13770. isCaseIncluded = true;
  13771. }
  13772. if (!isCaseIncluded) {
  13773. const hasEffectsContext = createHasEffectsContext();
  13774. hasEffectsContext.ignore.breaks = true;
  13775. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  13776. }
  13777. if (isCaseIncluded) {
  13778. switchCase.include(context, includeChildrenRecursively);
  13779. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  13780. context.hasBreak = false;
  13781. context.brokenFlow = brokenFlow;
  13782. }
  13783. else {
  13784. onlyHasBrokenFlow = brokenFlow;
  13785. }
  13786. }
  13787. if (isCaseIncluded && this.defaultCase !== null) {
  13788. context.brokenFlow = onlyHasBrokenFlow;
  13789. }
  13790. context.hasBreak = hasBreak;
  13791. }
  13792. initialise() {
  13793. super.initialise();
  13794. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  13795. if (this.cases[caseIndex].test === null) {
  13796. this.defaultCase = caseIndex;
  13797. return;
  13798. }
  13799. }
  13800. this.defaultCase = null;
  13801. }
  13802. parseNode(esTreeNode) {
  13803. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  13804. return super.parseNode(esTreeNode);
  13805. }
  13806. render(code, options) {
  13807. this.discriminant.render(code, options);
  13808. if (this.cases.length > 0) {
  13809. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  13810. }
  13811. }
  13812. }
  13813. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13814. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13815. class TaggedTemplateExpression extends CallExpressionBase {
  13816. get hasCheckedForWarnings() {
  13817. return isFlagSet(this.flags, 536870912 /* Flag.checkedForWarnings */);
  13818. }
  13819. set hasCheckedForWarnings(value) {
  13820. this.flags = setFlag(this.flags, 536870912 /* Flag.checkedForWarnings */, value);
  13821. }
  13822. bind() {
  13823. super.bind();
  13824. }
  13825. hasEffects(context) {
  13826. if (!this.deoptimized)
  13827. this.applyDeoptimizations();
  13828. for (const argument of this.quasi.expressions) {
  13829. if (argument.hasEffects(context))
  13830. return true;
  13831. }
  13832. return (this.tag.hasEffects(context) ||
  13833. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13834. }
  13835. include(context, includeChildrenRecursively) {
  13836. if (!this.included)
  13837. this.includeNode(context);
  13838. if (includeChildrenRecursively) {
  13839. super.include(context, true);
  13840. }
  13841. else {
  13842. this.quasi.include(context, false);
  13843. this.tag.include(context, false);
  13844. this.tag.includeCallArguments(this.interaction, context);
  13845. }
  13846. }
  13847. initialise() {
  13848. super.initialise();
  13849. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  13850. this.interaction = {
  13851. args: [
  13852. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  13853. ...this.args
  13854. ],
  13855. type: INTERACTION_CALLED,
  13856. withNew: false
  13857. };
  13858. }
  13859. render(code, options) {
  13860. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  13861. this.quasi.render(code, options);
  13862. if (!this.hasCheckedForWarnings && this.tag.type === Identifier$1) {
  13863. this.hasCheckedForWarnings = true;
  13864. const name = this.tag.name;
  13865. const variable = this.scope.findVariable(name);
  13866. if (variable.isNamespace) {
  13867. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  13868. }
  13869. }
  13870. }
  13871. applyDeoptimizations() {
  13872. this.deoptimized = true;
  13873. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13874. this.scope.context.requestTreeshakingPass();
  13875. }
  13876. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  13877. if (this.returnExpression === null) {
  13878. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  13879. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  13880. }
  13881. return this.returnExpression;
  13882. }
  13883. }
  13884. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  13885. class TemplateElement extends NodeBase {
  13886. get tail() {
  13887. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  13888. }
  13889. set tail(value) {
  13890. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  13891. }
  13892. // Do not try to bind value
  13893. bind() { }
  13894. hasEffects() {
  13895. return false;
  13896. }
  13897. parseNode(esTreeNode) {
  13898. this.value = esTreeNode.value;
  13899. return super.parseNode(esTreeNode);
  13900. }
  13901. render() { }
  13902. }
  13903. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  13904. class TemplateLiteral extends NodeBase {
  13905. deoptimizeArgumentsOnInteractionAtPath() { }
  13906. getLiteralValueAtPath(path) {
  13907. if (path.length > 0 || this.quasis.length !== 1) {
  13908. return UnknownValue;
  13909. }
  13910. return this.quasis[0].value.cooked;
  13911. }
  13912. getReturnExpressionWhenCalledAtPath(path) {
  13913. if (path.length !== 1) {
  13914. return UNKNOWN_RETURN_EXPRESSION;
  13915. }
  13916. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  13917. }
  13918. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13919. if (interaction.type === INTERACTION_ACCESSED) {
  13920. return path.length > 1;
  13921. }
  13922. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  13923. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  13924. }
  13925. return true;
  13926. }
  13927. includeNode(context) {
  13928. this.included = true;
  13929. if (!this.deoptimized)
  13930. this.applyDeoptimizations();
  13931. for (const node of this.expressions) {
  13932. node.includePath(UNKNOWN_PATH, context);
  13933. }
  13934. }
  13935. render(code, options) {
  13936. code.indentExclusionRanges.push([this.start, this.end]);
  13937. super.render(code, options);
  13938. }
  13939. }
  13940. class ModuleScope extends ChildScope {
  13941. constructor(parent, context) {
  13942. super(parent, context);
  13943. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  13944. }
  13945. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  13946. if (this.context.module.importDescriptions.has(identifier.name)) {
  13947. context.error(logRedeclarationError(identifier.name), identifier.start);
  13948. }
  13949. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  13950. }
  13951. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  13952. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  13953. this.variables.set('default', variable);
  13954. return variable;
  13955. }
  13956. addNamespaceMemberAccess() { }
  13957. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  13958. // all module level variables are already deconflicted when deconflicting the chunk
  13959. for (const scope of this.children)
  13960. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13961. }
  13962. findLexicalBoundary() {
  13963. return this;
  13964. }
  13965. findVariable(name) {
  13966. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  13967. if (knownVariable) {
  13968. return knownVariable;
  13969. }
  13970. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  13971. if (variable instanceof GlobalVariable) {
  13972. this.accessedOutsideVariables.set(name, variable);
  13973. }
  13974. return variable;
  13975. }
  13976. }
  13977. class ThisExpression extends NodeBase {
  13978. bind() {
  13979. this.variable = this.scope.findVariable('this');
  13980. }
  13981. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13982. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13983. }
  13984. deoptimizePath(path) {
  13985. this.variable.deoptimizePath(path);
  13986. }
  13987. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13988. if (path.length === 0) {
  13989. return interaction.type !== INTERACTION_ACCESSED;
  13990. }
  13991. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  13992. }
  13993. include(context) {
  13994. if (!this.included)
  13995. this.includeNode(context);
  13996. }
  13997. includeNode(context) {
  13998. this.included = true;
  13999. if (!this.deoptimized)
  14000. this.applyDeoptimizations();
  14001. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14002. }
  14003. includePath(path, context) {
  14004. if (!this.included) {
  14005. this.included = true;
  14006. this.scope.context.includeVariableInModule(this.variable, path, context);
  14007. }
  14008. else if (path.length > 0) {
  14009. this.variable.includePath(path, context);
  14010. }
  14011. const functionScope = findFunctionScope(this.scope, this.variable);
  14012. if (functionScope &&
  14013. functionScope.functionNode.parent instanceof Property &&
  14014. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  14015. functionScope.functionNode.parent.parent.includePath(path, context);
  14016. }
  14017. }
  14018. initialise() {
  14019. super.initialise();
  14020. this.alias =
  14021. this.scope.findLexicalBoundary() instanceof ModuleScope
  14022. ? this.scope.context.moduleContext
  14023. : null;
  14024. if (this.alias === 'undefined') {
  14025. this.scope.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  14026. }
  14027. }
  14028. render(code) {
  14029. if (this.alias !== null) {
  14030. code.overwrite(this.start, this.end, this.alias, {
  14031. contentOnly: false,
  14032. storeName: true
  14033. });
  14034. }
  14035. }
  14036. }
  14037. function findFunctionScope(scope, thisVariable) {
  14038. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  14039. if (!(scope instanceof ChildScope)) {
  14040. return null;
  14041. }
  14042. scope = scope.parent;
  14043. }
  14044. return scope;
  14045. }
  14046. class ThrowStatement extends NodeBase {
  14047. hasEffects() {
  14048. return true;
  14049. }
  14050. include(context, includeChildrenRecursively) {
  14051. if (!this.included)
  14052. this.includeNode(context);
  14053. this.argument.include(context, includeChildrenRecursively);
  14054. context.brokenFlow = true;
  14055. }
  14056. includeNode(context) {
  14057. if (!this.included) {
  14058. this.included = true;
  14059. this.argument.includePath(UNKNOWN_PATH, context);
  14060. }
  14061. }
  14062. render(code, options) {
  14063. this.argument.render(code, options, { preventASI: true });
  14064. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  14065. code.prependLeft(this.start + 5, ' ');
  14066. }
  14067. }
  14068. }
  14069. class TryStatement extends NodeBase {
  14070. constructor() {
  14071. super(...arguments);
  14072. this.directlyIncluded = false;
  14073. this.includedLabelsAfterBlock = null;
  14074. }
  14075. hasEffects(context) {
  14076. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  14077. ? this.block.body.length > 0
  14078. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  14079. }
  14080. include(context, includeChildrenRecursively) {
  14081. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  14082. const { brokenFlow, includedLabels } = context;
  14083. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  14084. this.included = true;
  14085. this.directlyIncluded = true;
  14086. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  14087. if (includedLabels.size > 0) {
  14088. this.includedLabelsAfterBlock = [...includedLabels];
  14089. }
  14090. context.brokenFlow = brokenFlow;
  14091. }
  14092. else if (this.includedLabelsAfterBlock) {
  14093. for (const label of this.includedLabelsAfterBlock) {
  14094. includedLabels.add(label);
  14095. }
  14096. }
  14097. if (this.handler !== null) {
  14098. this.handler.include(context, includeChildrenRecursively);
  14099. context.brokenFlow = brokenFlow;
  14100. }
  14101. this.finalizer?.include(context, includeChildrenRecursively);
  14102. }
  14103. }
  14104. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14105. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14106. const unaryOperators = {
  14107. '!': value => !value,
  14108. '+': value => +value,
  14109. '-': value => -value,
  14110. delete: () => UnknownValue,
  14111. typeof: value => typeof value,
  14112. void: () => undefined,
  14113. '~': value => ~value
  14114. };
  14115. const UNASSIGNED = Symbol('Unassigned');
  14116. class UnaryExpression extends NodeBase {
  14117. constructor() {
  14118. super(...arguments);
  14119. this.renderedLiteralValue = UNASSIGNED;
  14120. }
  14121. get prefix() {
  14122. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  14123. }
  14124. set prefix(value) {
  14125. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  14126. }
  14127. deoptimizeCache() {
  14128. this.renderedLiteralValue = UnknownValue;
  14129. }
  14130. getLiteralValueAtPath(path, recursionTracker, origin) {
  14131. if (path.length > 0)
  14132. return UnknownValue;
  14133. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  14134. if (typeof argumentValue === 'symbol') {
  14135. if (this.operator === 'void')
  14136. return undefined;
  14137. if (this.operator === '!') {
  14138. if (argumentValue === UnknownFalsyValue)
  14139. return true;
  14140. if (argumentValue === UnknownTruthyValue)
  14141. return false;
  14142. }
  14143. return UnknownValue;
  14144. }
  14145. return unaryOperators[this.operator](argumentValue);
  14146. }
  14147. hasEffects(context) {
  14148. if (!this.deoptimized)
  14149. this.applyDeoptimizations();
  14150. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  14151. return false;
  14152. return (this.argument.hasEffects(context) ||
  14153. (this.operator === 'delete' &&
  14154. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  14155. }
  14156. hasEffectsOnInteractionAtPath(path, { type }) {
  14157. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  14158. }
  14159. applyDeoptimizations() {
  14160. this.deoptimized = true;
  14161. if (this.operator === 'delete') {
  14162. this.argument.deoptimizePath(EMPTY_PATH);
  14163. this.scope.context.requestTreeshakingPass();
  14164. }
  14165. }
  14166. getRenderedLiteralValue(includeChildrenRecursively) {
  14167. if (this.renderedLiteralValue !== UNASSIGNED)
  14168. return this.renderedLiteralValue;
  14169. return (this.renderedLiteralValue = includeChildrenRecursively
  14170. ? UnknownValue
  14171. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  14172. }
  14173. include(context, includeChildrenRecursively, _options) {
  14174. if (!this.deoptimized)
  14175. this.applyDeoptimizations();
  14176. this.included = true;
  14177. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  14178. this.argument.shouldBeIncluded(context)) {
  14179. this.argument.include(context, includeChildrenRecursively);
  14180. this.renderedLiteralValue = UnknownValue;
  14181. }
  14182. }
  14183. render(code, options) {
  14184. if (typeof this.renderedLiteralValue === 'symbol') {
  14185. super.render(code, options);
  14186. }
  14187. else {
  14188. let value = this.renderedLiteralValue;
  14189. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  14190. value = ` ${value}`;
  14191. }
  14192. code.overwrite(this.start, this.end, value);
  14193. }
  14194. }
  14195. }
  14196. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  14197. function getRenderedLiteralValue(value) {
  14198. if (value === undefined) {
  14199. // At the moment, the undefined only happens when the operator is void
  14200. return 'void 0';
  14201. }
  14202. if (typeof value === 'boolean') {
  14203. return String(value);
  14204. }
  14205. if (typeof value === 'string') {
  14206. return JSON.stringify(value);
  14207. }
  14208. if (typeof value === 'number') {
  14209. return getSimplifiedNumber(value);
  14210. }
  14211. return UnknownValue;
  14212. }
  14213. function getSimplifiedNumber(value) {
  14214. if (Object.is(-0, value)) {
  14215. return '-0';
  14216. }
  14217. const exp = value.toExponential();
  14218. const [base, exponent] = exp.split('e');
  14219. const floatLength = base.split('.')[1]?.length || 0;
  14220. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  14221. const stringifiedValue = String(value).replace('+', '');
  14222. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  14223. }
  14224. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  14225. class UpdateExpression extends NodeBase {
  14226. hasEffects(context) {
  14227. if (!this.deoptimized)
  14228. this.applyDeoptimizations();
  14229. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  14230. }
  14231. hasEffectsOnInteractionAtPath(path, { type }) {
  14232. return path.length > 1 || type !== INTERACTION_ACCESSED;
  14233. }
  14234. include(context, includeChildrenRecursively) {
  14235. if (!this.included)
  14236. this.includeNode(context);
  14237. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  14238. }
  14239. initialise() {
  14240. super.initialise();
  14241. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  14242. }
  14243. render(code, options) {
  14244. const { exportNamesByVariable, format, snippets: { _ } } = options;
  14245. this.argument.render(code, options);
  14246. if (format === 'system') {
  14247. const variable = this.argument.variable;
  14248. const exportNames = exportNamesByVariable.get(variable);
  14249. if (exportNames) {
  14250. if (this.prefix) {
  14251. if (exportNames.length === 1) {
  14252. renderSystemExportExpression(variable, this.start, this.end, code, options);
  14253. }
  14254. else {
  14255. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  14256. }
  14257. }
  14258. else {
  14259. const operator = this.operator[0];
  14260. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  14261. }
  14262. }
  14263. }
  14264. }
  14265. applyDeoptimizations() {
  14266. this.deoptimized = true;
  14267. this.argument.deoptimizePath(EMPTY_PATH);
  14268. if (this.argument instanceof Identifier) {
  14269. const variable = this.scope.findVariable(this.argument.name);
  14270. variable.markReassigned();
  14271. }
  14272. this.scope.context.requestTreeshakingPass();
  14273. }
  14274. }
  14275. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  14276. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  14277. for (const declarator of declarations) {
  14278. if (!declarator.id.included)
  14279. return false;
  14280. if (declarator.id.type === Identifier$1) {
  14281. if (exportNamesByVariable.has(declarator.id.variable))
  14282. return false;
  14283. }
  14284. else {
  14285. const exportedVariables = [];
  14286. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  14287. if (exportedVariables.length > 0)
  14288. return false;
  14289. }
  14290. }
  14291. return true;
  14292. }
  14293. class VariableDeclaration extends NodeBase {
  14294. deoptimizePath() {
  14295. for (const declarator of this.declarations) {
  14296. declarator.deoptimizePath(EMPTY_PATH);
  14297. }
  14298. }
  14299. hasEffectsOnInteractionAtPath() {
  14300. return false;
  14301. }
  14302. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  14303. this.included = true;
  14304. for (const declarator of this.declarations) {
  14305. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  14306. declarator.include(context, includeChildrenRecursively);
  14307. }
  14308. const { id, init } = declarator;
  14309. if (asSingleStatement) {
  14310. id.include(context, includeChildrenRecursively);
  14311. }
  14312. if (init &&
  14313. id.included &&
  14314. !init.included &&
  14315. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  14316. init.include(context, includeChildrenRecursively);
  14317. }
  14318. }
  14319. }
  14320. initialise() {
  14321. super.initialise();
  14322. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  14323. for (const declarator of this.declarations) {
  14324. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  14325. }
  14326. }
  14327. removeAnnotations(code) {
  14328. this.declarations[0].removeAnnotations(code);
  14329. }
  14330. render(code, options, nodeRenderOptions = BLANK) {
  14331. if (this.isUsingDeclaration ||
  14332. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  14333. for (const declarator of this.declarations) {
  14334. declarator.render(code, options);
  14335. }
  14336. if (!nodeRenderOptions.isNoStatement &&
  14337. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  14338. code.appendLeft(this.end, ';');
  14339. }
  14340. }
  14341. else {
  14342. this.renderReplacedDeclarations(code, options);
  14343. }
  14344. }
  14345. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  14346. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  14347. code.remove(this.end - 1, this.end);
  14348. }
  14349. separatorString += ';';
  14350. if (lastSeparatorPos === null) {
  14351. code.appendLeft(renderedContentEnd, separatorString);
  14352. }
  14353. else {
  14354. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  14355. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  14356. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  14357. actualContentEnd--;
  14358. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  14359. actualContentEnd--;
  14360. }
  14361. }
  14362. if (actualContentEnd === lastSeparatorPos + 1) {
  14363. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  14364. }
  14365. else {
  14366. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14367. code.remove(actualContentEnd, renderedContentEnd);
  14368. }
  14369. }
  14370. if (systemPatternExports.length > 0) {
  14371. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  14372. }
  14373. }
  14374. renderReplacedDeclarations(code, options) {
  14375. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  14376. let actualContentEnd, renderedContentEnd;
  14377. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  14378. let lastSeparatorPos = renderedContentEnd - 1;
  14379. code.remove(this.start, lastSeparatorPos);
  14380. let isInDeclaration = false;
  14381. let hasRenderedContent = false;
  14382. let separatorString = '', leadingString, nextSeparatorString;
  14383. const aggregatedSystemExports = [];
  14384. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  14385. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  14386. if (!node.included) {
  14387. treeshakeNode(node, code, start, end);
  14388. continue;
  14389. }
  14390. node.render(code, options);
  14391. leadingString = '';
  14392. nextSeparatorString = '';
  14393. if (!node.id.included ||
  14394. (node.id instanceof Identifier &&
  14395. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  14396. if (hasRenderedContent) {
  14397. separatorString += ';';
  14398. }
  14399. isInDeclaration = false;
  14400. }
  14401. else {
  14402. if (singleSystemExport && singleSystemExport === node.id.variable) {
  14403. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  14404. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  14405. }
  14406. if (isInDeclaration) {
  14407. separatorString += ',';
  14408. }
  14409. else {
  14410. if (hasRenderedContent) {
  14411. separatorString += ';';
  14412. }
  14413. leadingString += `${this.kind} `;
  14414. isInDeclaration = true;
  14415. }
  14416. }
  14417. if (renderedContentEnd === lastSeparatorPos + 1) {
  14418. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  14419. }
  14420. else {
  14421. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14422. code.appendLeft(renderedContentEnd, leadingString);
  14423. }
  14424. actualContentEnd = contentEnd;
  14425. renderedContentEnd = end;
  14426. hasRenderedContent = true;
  14427. lastSeparatorPos = separator;
  14428. separatorString = nextSeparatorString;
  14429. }
  14430. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  14431. }
  14432. }
  14433. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  14434. let singleSystemExport = null;
  14435. if (options.format === 'system') {
  14436. for (const { node } of separatedNodes) {
  14437. if (node.id instanceof Identifier &&
  14438. node.init &&
  14439. aggregatedSystemExports.length === 0 &&
  14440. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  14441. singleSystemExport = node.id.variable;
  14442. aggregatedSystemExports.push(singleSystemExport);
  14443. }
  14444. else {
  14445. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  14446. }
  14447. }
  14448. if (aggregatedSystemExports.length > 1) {
  14449. singleSystemExport = null;
  14450. }
  14451. else if (singleSystemExport) {
  14452. aggregatedSystemExports.length = 0;
  14453. }
  14454. }
  14455. return singleSystemExport;
  14456. }
  14457. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14458. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  14459. class WhileStatement extends NodeBase {
  14460. hasEffects(context) {
  14461. if (this.test.hasEffects(context))
  14462. return true;
  14463. return hasLoopBodyEffects(context, this.body);
  14464. }
  14465. include(context, includeChildrenRecursively) {
  14466. this.included = true;
  14467. this.test.include(context, includeChildrenRecursively);
  14468. includeLoopBody(context, this.body, includeChildrenRecursively);
  14469. }
  14470. }
  14471. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14472. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14473. class YieldExpression extends NodeBase {
  14474. applyDeoptimizations() {
  14475. this.deoptimized = true;
  14476. this.argument?.deoptimizePath(UNKNOWN_PATH);
  14477. }
  14478. hasEffects(context) {
  14479. if (!this.deoptimized)
  14480. this.applyDeoptimizations();
  14481. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  14482. }
  14483. includeNode(context) {
  14484. this.included = true;
  14485. if (!this.deoptimized)
  14486. this.applyDeoptimizations();
  14487. this.argument?.includePath(UNKNOWN_PATH, context);
  14488. }
  14489. render(code, options) {
  14490. if (this.argument) {
  14491. this.argument.render(code, options, { preventASI: true });
  14492. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  14493. code.prependLeft(this.start + 5, ' ');
  14494. }
  14495. }
  14496. }
  14497. }
  14498. // This file is generated by scripts/generate-buffer-parsers.js.
  14499. // Do not edit this file directly.
  14500. function convertProgram(buffer, parent, parentScope) {
  14501. return convertNode(parent, parentScope, 0, getAstBuffer(buffer));
  14502. }
  14503. const nodeTypeStrings = [
  14504. 'PanicError',
  14505. 'ParseError',
  14506. 'ArrayExpression',
  14507. 'ArrayPattern',
  14508. 'ArrowFunctionExpression',
  14509. 'AssignmentExpression',
  14510. 'AssignmentPattern',
  14511. 'AwaitExpression',
  14512. 'BinaryExpression',
  14513. 'BlockStatement',
  14514. 'BreakStatement',
  14515. 'CallExpression',
  14516. 'CatchClause',
  14517. 'ChainExpression',
  14518. 'ClassBody',
  14519. 'ClassDeclaration',
  14520. 'ClassExpression',
  14521. 'ConditionalExpression',
  14522. 'ContinueStatement',
  14523. 'DebuggerStatement',
  14524. 'Decorator',
  14525. 'ExpressionStatement',
  14526. 'DoWhileStatement',
  14527. 'EmptyStatement',
  14528. 'ExportAllDeclaration',
  14529. 'ExportDefaultDeclaration',
  14530. 'ExportNamedDeclaration',
  14531. 'ExportSpecifier',
  14532. 'ExpressionStatement',
  14533. 'ForInStatement',
  14534. 'ForOfStatement',
  14535. 'ForStatement',
  14536. 'FunctionDeclaration',
  14537. 'FunctionExpression',
  14538. 'Identifier',
  14539. 'IfStatement',
  14540. 'ImportAttribute',
  14541. 'ImportDeclaration',
  14542. 'ImportDefaultSpecifier',
  14543. 'ImportExpression',
  14544. 'ImportNamespaceSpecifier',
  14545. 'ImportSpecifier',
  14546. 'JSXAttribute',
  14547. 'JSXClosingElement',
  14548. 'JSXClosingFragment',
  14549. 'JSXElement',
  14550. 'JSXEmptyExpression',
  14551. 'JSXExpressionContainer',
  14552. 'JSXFragment',
  14553. 'JSXIdentifier',
  14554. 'JSXMemberExpression',
  14555. 'JSXNamespacedName',
  14556. 'JSXOpeningElement',
  14557. 'JSXOpeningFragment',
  14558. 'JSXSpreadAttribute',
  14559. 'JSXSpreadChild',
  14560. 'JSXText',
  14561. 'LabeledStatement',
  14562. 'Literal',
  14563. 'Literal',
  14564. 'Literal',
  14565. 'Literal',
  14566. 'Literal',
  14567. 'Literal',
  14568. 'LogicalExpression',
  14569. 'MemberExpression',
  14570. 'MetaProperty',
  14571. 'MethodDefinition',
  14572. 'NewExpression',
  14573. 'ObjectExpression',
  14574. 'ObjectPattern',
  14575. 'PrivateIdentifier',
  14576. 'Program',
  14577. 'Property',
  14578. 'PropertyDefinition',
  14579. 'RestElement',
  14580. 'ReturnStatement',
  14581. 'SequenceExpression',
  14582. 'SpreadElement',
  14583. 'StaticBlock',
  14584. 'Super',
  14585. 'SwitchCase',
  14586. 'SwitchStatement',
  14587. 'TaggedTemplateExpression',
  14588. 'TemplateElement',
  14589. 'TemplateLiteral',
  14590. 'ThisExpression',
  14591. 'ThrowStatement',
  14592. 'TryStatement',
  14593. 'UnaryExpression',
  14594. 'UpdateExpression',
  14595. 'VariableDeclaration',
  14596. 'VariableDeclarator',
  14597. 'WhileStatement',
  14598. 'YieldExpression'
  14599. ];
  14600. const nodeConstructors$1 = [
  14601. PanicError,
  14602. ParseError,
  14603. ArrayExpression,
  14604. ArrayPattern,
  14605. ArrowFunctionExpression,
  14606. AssignmentExpression,
  14607. AssignmentPattern,
  14608. AwaitExpression,
  14609. BinaryExpression,
  14610. BlockStatement,
  14611. BreakStatement,
  14612. CallExpression,
  14613. CatchClause,
  14614. ChainExpression,
  14615. ClassBody,
  14616. ClassDeclaration,
  14617. ClassExpression,
  14618. ConditionalExpression,
  14619. ContinueStatement,
  14620. DebuggerStatement,
  14621. Decorator,
  14622. ExpressionStatement,
  14623. DoWhileStatement,
  14624. EmptyStatement,
  14625. ExportAllDeclaration,
  14626. ExportDefaultDeclaration,
  14627. ExportNamedDeclaration,
  14628. ExportSpecifier,
  14629. ExpressionStatement,
  14630. ForInStatement,
  14631. ForOfStatement,
  14632. ForStatement,
  14633. FunctionDeclaration,
  14634. FunctionExpression,
  14635. Identifier,
  14636. IfStatement,
  14637. ImportAttribute,
  14638. ImportDeclaration,
  14639. ImportDefaultSpecifier,
  14640. ImportExpression,
  14641. ImportNamespaceSpecifier,
  14642. ImportSpecifier,
  14643. JSXAttribute,
  14644. JSXClosingElement,
  14645. JSXClosingFragment,
  14646. JSXElement,
  14647. JSXEmptyExpression,
  14648. JSXExpressionContainer,
  14649. JSXFragment,
  14650. JSXIdentifier,
  14651. JSXMemberExpression,
  14652. JSXNamespacedName,
  14653. JSXOpeningElement,
  14654. JSXOpeningFragment,
  14655. JSXSpreadAttribute,
  14656. JSXSpreadChild,
  14657. JSXText,
  14658. LabeledStatement,
  14659. Literal,
  14660. Literal,
  14661. Literal,
  14662. Literal,
  14663. Literal,
  14664. Literal,
  14665. LogicalExpression,
  14666. MemberExpression,
  14667. MetaProperty,
  14668. MethodDefinition,
  14669. NewExpression,
  14670. ObjectExpression,
  14671. ObjectPattern,
  14672. PrivateIdentifier,
  14673. Program,
  14674. Property,
  14675. PropertyDefinition,
  14676. RestElement,
  14677. ReturnStatement,
  14678. SequenceExpression,
  14679. SpreadElement,
  14680. StaticBlock,
  14681. Super,
  14682. SwitchCase,
  14683. SwitchStatement,
  14684. TaggedTemplateExpression,
  14685. TemplateElement,
  14686. TemplateLiteral,
  14687. ThisExpression,
  14688. ThrowStatement,
  14689. TryStatement,
  14690. UnaryExpression,
  14691. UpdateExpression,
  14692. VariableDeclaration,
  14693. VariableDeclarator,
  14694. WhileStatement,
  14695. YieldExpression
  14696. ];
  14697. const bufferParsers = [
  14698. function panicError(node, position, buffer) {
  14699. node.message = buffer.convertString(buffer[position]);
  14700. },
  14701. function parseError(node, position, buffer) {
  14702. node.message = buffer.convertString(buffer[position]);
  14703. },
  14704. function arrayExpression(node, position, buffer) {
  14705. const { scope } = node;
  14706. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  14707. },
  14708. function arrayPattern(node, position, buffer) {
  14709. const { scope } = node;
  14710. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  14711. },
  14712. function arrowFunctionExpression(node, position, buffer) {
  14713. const { scope } = node;
  14714. const flags = buffer[position];
  14715. node.async = (flags & 1) === 1;
  14716. node.expression = (flags & 2) === 2;
  14717. node.generator = (flags & 4) === 4;
  14718. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  14719. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  14720. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  14721. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  14722. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  14723. },
  14724. function assignmentExpression(node, position, buffer) {
  14725. const { scope } = node;
  14726. node.operator = FIXED_STRINGS[buffer[position]];
  14727. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14728. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14729. },
  14730. function assignmentPattern(node, position, buffer) {
  14731. const { scope } = node;
  14732. node.left = convertNode(node, scope, buffer[position], buffer);
  14733. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  14734. },
  14735. function awaitExpression(node, position, buffer) {
  14736. const { scope } = node;
  14737. node.argument = convertNode(node, scope, buffer[position], buffer);
  14738. },
  14739. function binaryExpression(node, position, buffer) {
  14740. const { scope } = node;
  14741. node.operator = FIXED_STRINGS[buffer[position]];
  14742. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14743. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14744. },
  14745. function blockStatement(node, position, buffer) {
  14746. const { scope } = node;
  14747. node.body = convertNodeList(node, scope, buffer[position], buffer);
  14748. },
  14749. function breakStatement(node, position, buffer) {
  14750. const { scope } = node;
  14751. const labelPosition = buffer[position];
  14752. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  14753. },
  14754. function callExpression(node, position, buffer) {
  14755. const { scope } = node;
  14756. const flags = buffer[position];
  14757. node.optional = (flags & 1) === 1;
  14758. node.annotations = convertAnnotations(buffer[position + 1], buffer);
  14759. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  14760. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  14761. },
  14762. function catchClause(node, position, buffer) {
  14763. const { scope } = node;
  14764. const parameterPosition = buffer[position];
  14765. const parameter = (node.param =
  14766. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  14767. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  14768. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  14769. },
  14770. function chainExpression(node, position, buffer) {
  14771. const { scope } = node;
  14772. node.expression = convertNode(node, scope, buffer[position], buffer);
  14773. },
  14774. function classBody(node, position, buffer) {
  14775. const { scope } = node;
  14776. const bodyPosition = buffer[position];
  14777. if (bodyPosition) {
  14778. const length = buffer[bodyPosition];
  14779. const body = (node.body = new Array(length));
  14780. for (let index = 0; index < length; index++) {
  14781. const nodePosition = buffer[bodyPosition + 1 + index];
  14782. body[index] = convertNode(node, (buffer[nodePosition + 3] & 1) === 0 ? scope.instanceScope : scope, nodePosition, buffer);
  14783. }
  14784. }
  14785. else {
  14786. node.body = [];
  14787. }
  14788. },
  14789. function classDeclaration(node, position, buffer) {
  14790. const { scope } = node;
  14791. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  14792. const idPosition = buffer[position + 1];
  14793. node.id =
  14794. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  14795. const superClassPosition = buffer[position + 2];
  14796. node.superClass =
  14797. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  14798. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14799. },
  14800. function classExpression(node, position, buffer) {
  14801. const { scope } = node;
  14802. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  14803. const idPosition = buffer[position + 1];
  14804. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  14805. const superClassPosition = buffer[position + 2];
  14806. node.superClass =
  14807. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  14808. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14809. },
  14810. function conditionalExpression(node, position, buffer) {
  14811. const { scope } = node;
  14812. node.test = convertNode(node, scope, buffer[position], buffer);
  14813. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  14814. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  14815. },
  14816. function continueStatement(node, position, buffer) {
  14817. const { scope } = node;
  14818. const labelPosition = buffer[position];
  14819. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  14820. },
  14821. function debuggerStatement() { },
  14822. function decorator(node, position, buffer) {
  14823. const { scope } = node;
  14824. node.expression = convertNode(node, scope, buffer[position], buffer);
  14825. },
  14826. function directive(node, position, buffer) {
  14827. const { scope } = node;
  14828. node.directive = buffer.convertString(buffer[position]);
  14829. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  14830. },
  14831. function doWhileStatement(node, position, buffer) {
  14832. const { scope } = node;
  14833. node.body = convertNode(node, scope, buffer[position], buffer);
  14834. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  14835. },
  14836. function emptyStatement() { },
  14837. function exportAllDeclaration(node, position, buffer) {
  14838. const { scope } = node;
  14839. const exportedPosition = buffer[position];
  14840. node.exported =
  14841. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  14842. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  14843. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  14844. },
  14845. function exportDefaultDeclaration(node, position, buffer) {
  14846. const { scope } = node;
  14847. node.declaration = convertNode(node, scope, buffer[position], buffer);
  14848. },
  14849. function exportNamedDeclaration(node, position, buffer) {
  14850. const { scope } = node;
  14851. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  14852. const sourcePosition = buffer[position + 1];
  14853. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  14854. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  14855. const declarationPosition = buffer[position + 3];
  14856. node.declaration =
  14857. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  14858. },
  14859. function exportSpecifier(node, position, buffer) {
  14860. const { scope } = node;
  14861. node.local = convertNode(node, scope, buffer[position], buffer);
  14862. const exportedPosition = buffer[position + 1];
  14863. node.exported =
  14864. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  14865. },
  14866. function expressionStatement(node, position, buffer) {
  14867. const { scope } = node;
  14868. node.expression = convertNode(node, scope, buffer[position], buffer);
  14869. },
  14870. function forInStatement(node, position, buffer) {
  14871. const { scope } = node;
  14872. node.left = convertNode(node, scope, buffer[position], buffer);
  14873. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  14874. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  14875. },
  14876. function forOfStatement(node, position, buffer) {
  14877. const { scope } = node;
  14878. const flags = buffer[position];
  14879. node.await = (flags & 1) === 1;
  14880. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  14881. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  14882. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14883. },
  14884. function forStatement(node, position, buffer) {
  14885. const { scope } = node;
  14886. const initPosition = buffer[position];
  14887. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  14888. const testPosition = buffer[position + 1];
  14889. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  14890. const updatePosition = buffer[position + 2];
  14891. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  14892. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  14893. },
  14894. function functionDeclaration(node, position, buffer) {
  14895. const { scope } = node;
  14896. const flags = buffer[position];
  14897. node.async = (flags & 1) === 1;
  14898. node.generator = (flags & 2) === 2;
  14899. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  14900. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  14901. const idPosition = buffer[position + 2];
  14902. node.id =
  14903. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  14904. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  14905. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  14906. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  14907. },
  14908. function functionExpression(node, position, buffer) {
  14909. const { scope } = node;
  14910. const flags = buffer[position];
  14911. node.async = (flags & 1) === 1;
  14912. node.generator = (flags & 2) === 2;
  14913. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  14914. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  14915. const idPosition = buffer[position + 2];
  14916. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  14917. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  14918. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  14919. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  14920. },
  14921. function identifier(node, position, buffer) {
  14922. node.name = buffer.convertString(buffer[position]);
  14923. },
  14924. function ifStatement(node, position, buffer) {
  14925. const { scope } = node;
  14926. node.test = convertNode(node, scope, buffer[position], buffer);
  14927. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  14928. const alternatePosition = buffer[position + 2];
  14929. node.alternate =
  14930. alternatePosition === 0
  14931. ? null
  14932. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  14933. },
  14934. function importAttribute(node, position, buffer) {
  14935. const { scope } = node;
  14936. node.key = convertNode(node, scope, buffer[position], buffer);
  14937. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  14938. },
  14939. function importDeclaration(node, position, buffer) {
  14940. const { scope } = node;
  14941. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  14942. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  14943. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  14944. },
  14945. function importDefaultSpecifier(node, position, buffer) {
  14946. const { scope } = node;
  14947. node.local = convertNode(node, scope, buffer[position], buffer);
  14948. },
  14949. function importExpression(node, position, buffer) {
  14950. const { scope } = node;
  14951. node.source = convertNode(node, scope, buffer[position], buffer);
  14952. node.sourceAstNode = convertNode$1(buffer[position], buffer);
  14953. const optionsPosition = buffer[position + 1];
  14954. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  14955. },
  14956. function importNamespaceSpecifier(node, position, buffer) {
  14957. const { scope } = node;
  14958. node.local = convertNode(node, scope, buffer[position], buffer);
  14959. },
  14960. function importSpecifier(node, position, buffer) {
  14961. const { scope } = node;
  14962. const importedPosition = buffer[position];
  14963. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  14964. node.imported =
  14965. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  14966. },
  14967. function jsxAttribute(node, position, buffer) {
  14968. const { scope } = node;
  14969. node.name = convertNode(node, scope, buffer[position], buffer);
  14970. const valuePosition = buffer[position + 1];
  14971. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  14972. },
  14973. function jsxClosingElement(node, position, buffer) {
  14974. const { scope } = node;
  14975. node.name = convertNode(node, scope, buffer[position], buffer);
  14976. },
  14977. function jsxClosingFragment() { },
  14978. function jsxElement(node, position, buffer) {
  14979. const { scope } = node;
  14980. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  14981. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  14982. const closingElementPosition = buffer[position + 2];
  14983. node.closingElement =
  14984. closingElementPosition === 0
  14985. ? null
  14986. : convertNode(node, scope, closingElementPosition, buffer);
  14987. },
  14988. function jsxEmptyExpression() { },
  14989. function jsxExpressionContainer(node, position, buffer) {
  14990. const { scope } = node;
  14991. node.expression = convertNode(node, scope, buffer[position], buffer);
  14992. },
  14993. function jsxFragment(node, position, buffer) {
  14994. const { scope } = node;
  14995. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  14996. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  14997. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  14998. },
  14999. function jsxIdentifier(node, position, buffer) {
  15000. node.name = buffer.convertString(buffer[position]);
  15001. },
  15002. function jsxMemberExpression(node, position, buffer) {
  15003. const { scope } = node;
  15004. node.object = convertNode(node, scope, buffer[position], buffer);
  15005. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15006. },
  15007. function jsxNamespacedName(node, position, buffer) {
  15008. const { scope } = node;
  15009. node.namespace = convertNode(node, scope, buffer[position], buffer);
  15010. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15011. },
  15012. function jsxOpeningElement(node, position, buffer) {
  15013. const { scope } = node;
  15014. const flags = buffer[position];
  15015. node.selfClosing = (flags & 1) === 1;
  15016. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15017. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15018. },
  15019. function jsxOpeningFragment(node) {
  15020. node.attributes = [];
  15021. node.selfClosing = false;
  15022. },
  15023. function jsxSpreadAttribute(node, position, buffer) {
  15024. const { scope } = node;
  15025. node.argument = convertNode(node, scope, buffer[position], buffer);
  15026. },
  15027. function jsxSpreadChild(node, position, buffer) {
  15028. const { scope } = node;
  15029. node.expression = convertNode(node, scope, buffer[position], buffer);
  15030. },
  15031. function jsxText(node, position, buffer) {
  15032. node.value = buffer.convertString(buffer[position]);
  15033. node.raw = buffer.convertString(buffer[position + 1]);
  15034. },
  15035. function labeledStatement(node, position, buffer) {
  15036. const { scope } = node;
  15037. node.label = convertNode(node, scope, buffer[position], buffer);
  15038. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15039. },
  15040. function literalBigInt(node, position, buffer) {
  15041. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  15042. node.raw = buffer.convertString(buffer[position + 1]);
  15043. node.value = BigInt(bigint);
  15044. },
  15045. function literalBoolean(node, position, buffer) {
  15046. const flags = buffer[position];
  15047. const value = (node.value = (flags & 1) === 1);
  15048. node.raw = value ? 'true' : 'false';
  15049. },
  15050. function literalNull(node) {
  15051. node.value = null;
  15052. },
  15053. function literalNumber(node, position, buffer) {
  15054. const rawPosition = buffer[position];
  15055. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15056. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  15057. },
  15058. function literalRegExp(node, position, buffer) {
  15059. const flags = buffer.convertString(buffer[position]);
  15060. const pattern = buffer.convertString(buffer[position + 1]);
  15061. node.raw = `/${pattern}/${flags}`;
  15062. node.regex = { flags, pattern };
  15063. node.value = new RegExp(pattern, flags);
  15064. },
  15065. function literalString(node, position, buffer) {
  15066. node.value = buffer.convertString(buffer[position]);
  15067. const rawPosition = buffer[position + 1];
  15068. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15069. },
  15070. function logicalExpression(node, position, buffer) {
  15071. const { scope } = node;
  15072. node.operator = FIXED_STRINGS[buffer[position]];
  15073. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15074. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15075. },
  15076. function memberExpression(node, position, buffer) {
  15077. const { scope } = node;
  15078. const flags = buffer[position];
  15079. node.computed = (flags & 1) === 1;
  15080. node.optional = (flags & 2) === 2;
  15081. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  15082. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  15083. },
  15084. function metaProperty(node, position, buffer) {
  15085. const { scope } = node;
  15086. node.meta = convertNode(node, scope, buffer[position], buffer);
  15087. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15088. },
  15089. function methodDefinition(node, position, buffer) {
  15090. const { scope } = node;
  15091. const flags = buffer[position];
  15092. node.static = (flags & 1) === 1;
  15093. node.computed = (flags & 2) === 2;
  15094. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15095. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15096. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  15097. node.kind = FIXED_STRINGS[buffer[position + 4]];
  15098. },
  15099. function newExpression(node, position, buffer) {
  15100. const { scope } = node;
  15101. node.annotations = convertAnnotations(buffer[position], buffer);
  15102. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  15103. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  15104. },
  15105. function objectExpression(node, position, buffer) {
  15106. const { scope } = node;
  15107. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15108. },
  15109. function objectPattern(node, position, buffer) {
  15110. const { scope } = node;
  15111. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15112. },
  15113. function privateIdentifier(node, position, buffer) {
  15114. node.name = buffer.convertString(buffer[position]);
  15115. },
  15116. function program(node, position, buffer) {
  15117. const { scope } = node;
  15118. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15119. node.invalidAnnotations = convertAnnotations(buffer[position + 1], buffer);
  15120. },
  15121. function property(node, position, buffer) {
  15122. const { scope } = node;
  15123. const flags = buffer[position];
  15124. node.method = (flags & 1) === 1;
  15125. node.shorthand = (flags & 2) === 2;
  15126. node.computed = (flags & 4) === 4;
  15127. const keyPosition = buffer[position + 1];
  15128. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  15129. node.kind = FIXED_STRINGS[buffer[position + 3]];
  15130. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  15131. },
  15132. function propertyDefinition(node, position, buffer) {
  15133. const { scope } = node;
  15134. const flags = buffer[position];
  15135. node.static = (flags & 1) === 1;
  15136. node.computed = (flags & 2) === 2;
  15137. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15138. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15139. const valuePosition = buffer[position + 3];
  15140. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15141. },
  15142. function restElement(node, position, buffer) {
  15143. const { scope } = node;
  15144. node.argument = convertNode(node, scope, buffer[position], buffer);
  15145. },
  15146. function returnStatement(node, position, buffer) {
  15147. const { scope } = node;
  15148. const argumentPosition = buffer[position];
  15149. node.argument =
  15150. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15151. },
  15152. function sequenceExpression(node, position, buffer) {
  15153. const { scope } = node;
  15154. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  15155. },
  15156. function spreadElement(node, position, buffer) {
  15157. const { scope } = node;
  15158. node.argument = convertNode(node, scope, buffer[position], buffer);
  15159. },
  15160. function staticBlock(node, position, buffer) {
  15161. const { scope } = node;
  15162. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15163. },
  15164. function superElement() { },
  15165. function switchCase(node, position, buffer) {
  15166. const { scope } = node;
  15167. const testPosition = buffer[position];
  15168. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15169. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  15170. },
  15171. function switchStatement(node, position, buffer) {
  15172. const { scope } = node;
  15173. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  15174. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  15175. },
  15176. function taggedTemplateExpression(node, position, buffer) {
  15177. const { scope } = node;
  15178. node.tag = convertNode(node, scope, buffer[position], buffer);
  15179. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  15180. },
  15181. function templateElement(node, position, buffer) {
  15182. const flags = buffer[position];
  15183. node.tail = (flags & 1) === 1;
  15184. const cookedPosition = buffer[position + 1];
  15185. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  15186. const raw = buffer.convertString(buffer[position + 2]);
  15187. node.value = { cooked, raw };
  15188. },
  15189. function templateLiteral(node, position, buffer) {
  15190. const { scope } = node;
  15191. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  15192. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  15193. },
  15194. function thisExpression() { },
  15195. function throwStatement(node, position, buffer) {
  15196. const { scope } = node;
  15197. node.argument = convertNode(node, scope, buffer[position], buffer);
  15198. },
  15199. function tryStatement(node, position, buffer) {
  15200. const { scope } = node;
  15201. node.block = convertNode(node, scope, buffer[position], buffer);
  15202. const handlerPosition = buffer[position + 1];
  15203. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  15204. const finalizerPosition = buffer[position + 2];
  15205. node.finalizer =
  15206. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  15207. },
  15208. function unaryExpression(node, position, buffer) {
  15209. const { scope } = node;
  15210. node.operator = FIXED_STRINGS[buffer[position]];
  15211. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  15212. },
  15213. function updateExpression(node, position, buffer) {
  15214. const { scope } = node;
  15215. const flags = buffer[position];
  15216. node.prefix = (flags & 1) === 1;
  15217. node.operator = FIXED_STRINGS[buffer[position + 1]];
  15218. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  15219. },
  15220. function variableDeclaration(node, position, buffer) {
  15221. const { scope } = node;
  15222. node.kind = FIXED_STRINGS[buffer[position]];
  15223. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  15224. },
  15225. function variableDeclarator(node, position, buffer) {
  15226. const { scope } = node;
  15227. node.id = convertNode(node, scope, buffer[position], buffer);
  15228. const initPosition = buffer[position + 1];
  15229. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15230. },
  15231. function whileStatement(node, position, buffer) {
  15232. const { scope } = node;
  15233. node.test = convertNode(node, scope, buffer[position], buffer);
  15234. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15235. },
  15236. function yieldExpression(node, position, buffer) {
  15237. const { scope } = node;
  15238. const flags = buffer[position];
  15239. node.delegate = (flags & 1) === 1;
  15240. const argumentPosition = buffer[position + 1];
  15241. node.argument =
  15242. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15243. }
  15244. ];
  15245. function convertNode(parent, parentScope, position, buffer) {
  15246. const nodeType = buffer[position];
  15247. const NodeConstructor = nodeConstructors$1[nodeType];
  15248. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  15249. if (!NodeConstructor) {
  15250. console.trace();
  15251. throw new Error(`Unknown node type: ${nodeType}`);
  15252. }
  15253. const node = new NodeConstructor(parent, parentScope);
  15254. node.type = nodeTypeStrings[nodeType];
  15255. node.start = buffer[position + 1];
  15256. node.end = buffer[position + 2];
  15257. bufferParsers[nodeType](node, position + 3, buffer);
  15258. node.initialise();
  15259. return node;
  15260. }
  15261. function convertNodeList(parent, parentScope, position, buffer) {
  15262. if (position === 0)
  15263. return EMPTY_ARRAY;
  15264. const length = buffer[position++];
  15265. const list = new Array(length);
  15266. for (let index = 0; index < length; index++) {
  15267. const nodePosition = buffer[position++];
  15268. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  15269. }
  15270. return list;
  15271. }
  15272. class UnknownNode extends NodeBase {
  15273. hasEffects() {
  15274. return true;
  15275. }
  15276. include(context) {
  15277. super.include(context, true);
  15278. }
  15279. }
  15280. // This file is generated by scripts/generate-node-index.js.
  15281. // Do not edit this file directly.
  15282. const nodeConstructors = {
  15283. ArrayExpression,
  15284. ArrayPattern,
  15285. ArrowFunctionExpression,
  15286. AssignmentExpression,
  15287. AssignmentPattern,
  15288. AwaitExpression,
  15289. BinaryExpression,
  15290. BlockStatement,
  15291. BreakStatement,
  15292. CallExpression,
  15293. CatchClause,
  15294. ChainExpression,
  15295. ClassBody,
  15296. ClassDeclaration,
  15297. ClassExpression,
  15298. ConditionalExpression,
  15299. ContinueStatement,
  15300. DebuggerStatement,
  15301. Decorator,
  15302. DoWhileStatement,
  15303. EmptyStatement,
  15304. ExportAllDeclaration,
  15305. ExportDefaultDeclaration,
  15306. ExportNamedDeclaration,
  15307. ExportSpecifier,
  15308. ExpressionStatement,
  15309. ForInStatement,
  15310. ForOfStatement,
  15311. ForStatement,
  15312. FunctionDeclaration,
  15313. FunctionExpression,
  15314. Identifier,
  15315. IfStatement,
  15316. ImportAttribute,
  15317. ImportDeclaration,
  15318. ImportDefaultSpecifier,
  15319. ImportExpression,
  15320. ImportNamespaceSpecifier,
  15321. ImportSpecifier,
  15322. JSXAttribute,
  15323. JSXClosingElement,
  15324. JSXClosingFragment,
  15325. JSXElement,
  15326. JSXEmptyExpression,
  15327. JSXExpressionContainer,
  15328. JSXFragment,
  15329. JSXIdentifier,
  15330. JSXMemberExpression,
  15331. JSXNamespacedName,
  15332. JSXOpeningElement,
  15333. JSXOpeningFragment,
  15334. JSXSpreadAttribute,
  15335. JSXSpreadChild,
  15336. JSXText,
  15337. LabeledStatement,
  15338. Literal,
  15339. LogicalExpression,
  15340. MemberExpression,
  15341. MetaProperty,
  15342. MethodDefinition,
  15343. NewExpression,
  15344. ObjectExpression,
  15345. ObjectPattern,
  15346. PanicError,
  15347. ParseError,
  15348. PrivateIdentifier,
  15349. Program,
  15350. Property,
  15351. PropertyDefinition,
  15352. RestElement,
  15353. ReturnStatement,
  15354. SequenceExpression,
  15355. SpreadElement,
  15356. StaticBlock,
  15357. Super,
  15358. SwitchCase,
  15359. SwitchStatement,
  15360. TaggedTemplateExpression,
  15361. TemplateElement,
  15362. TemplateLiteral,
  15363. ThisExpression,
  15364. ThrowStatement,
  15365. TryStatement,
  15366. UnaryExpression,
  15367. UnknownNode,
  15368. UpdateExpression,
  15369. VariableDeclaration,
  15370. VariableDeclarator,
  15371. WhileStatement,
  15372. YieldExpression
  15373. };
  15374. class ExportShimVariable extends Variable {
  15375. constructor(module) {
  15376. super(MISSING_EXPORT_SHIM_VARIABLE);
  15377. this.module = module;
  15378. }
  15379. includePath(path, context) {
  15380. super.includePath(path, context);
  15381. this.module.needsExportShim = true;
  15382. }
  15383. }
  15384. var BuildPhase;
  15385. (function (BuildPhase) {
  15386. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  15387. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  15388. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  15389. })(BuildPhase || (BuildPhase = {}));
  15390. const sourceMapCache = new WeakMap();
  15391. /**
  15392. * This clears the decoded array and falls back to the encoded string form.
  15393. * Sourcemap mappings arrays can be very large and holding on to them for longer
  15394. * than is necessary leads to poor heap utilization.
  15395. */
  15396. function resetCacheToEncoded(cache) {
  15397. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  15398. cache.encodedMappings = encode(cache.decodedMappings);
  15399. }
  15400. cache.decodedMappings = undefined;
  15401. }
  15402. function resetSourcemapCache(map, sourcemapChain) {
  15403. if (map) {
  15404. const cache = sourceMapCache.get(map);
  15405. if (cache) {
  15406. resetCacheToEncoded(cache);
  15407. }
  15408. }
  15409. if (!sourcemapChain) {
  15410. return;
  15411. }
  15412. for (const map of sourcemapChain) {
  15413. if (map.missing)
  15414. continue;
  15415. resetSourcemapCache(map);
  15416. }
  15417. }
  15418. function decodedSourcemap(map) {
  15419. if (!map)
  15420. return null;
  15421. if (typeof map === 'string') {
  15422. map = JSON.parse(map);
  15423. }
  15424. if (!map.mappings) {
  15425. return {
  15426. mappings: [],
  15427. names: [],
  15428. sources: [],
  15429. version: 3
  15430. };
  15431. }
  15432. const originalMappings = map.mappings;
  15433. const isAlreadyDecoded = Array.isArray(originalMappings);
  15434. const cache = {
  15435. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  15436. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  15437. };
  15438. const decodedMap = {
  15439. ...map,
  15440. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  15441. // where the mappings field is never actually accessed. This appears to greatly reduce
  15442. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  15443. get mappings() {
  15444. if (cache.decodedMappings) {
  15445. return cache.decodedMappings;
  15446. }
  15447. // If decodedMappings doesn't exist then encodedMappings should.
  15448. // The only scenario where cache.encodedMappings should be undefined is if the map
  15449. // this was constructed from was already decoded, or if mappings was set to a new
  15450. // decoded string. In either case, this line shouldn't get hit.
  15451. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  15452. cache.encodedMappings = undefined;
  15453. return cache.decodedMappings;
  15454. }
  15455. };
  15456. sourceMapCache.set(decodedMap, cache);
  15457. return decodedMap;
  15458. }
  15459. function getId(m) {
  15460. return m.id;
  15461. }
  15462. function getOriginalLocation(sourcemapChain, location) {
  15463. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  15464. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  15465. const sourcemap = filteredSourcemapChain.pop();
  15466. const line = sourcemap.mappings[location.line - 1];
  15467. if (line) {
  15468. const filteredLine = line.filter((segment) => segment.length > 1);
  15469. const lastSegment = filteredLine[filteredLine.length - 1];
  15470. for (const segment of filteredLine) {
  15471. if (segment[0] >= location.column || segment === lastSegment) {
  15472. location = {
  15473. column: segment[3],
  15474. line: segment[2] + 1
  15475. };
  15476. continue traceSourcemap;
  15477. }
  15478. }
  15479. }
  15480. throw new Error("Can't resolve original location of error.");
  15481. }
  15482. return location;
  15483. }
  15484. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  15485. function getAttributesFromImportExpression(node) {
  15486. const { scope: { context }, options, start } = node;
  15487. if (!(options instanceof ObjectExpression)) {
  15488. if (options) {
  15489. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), start);
  15490. }
  15491. return EMPTY_OBJECT;
  15492. }
  15493. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  15494. if (!assertProperty) {
  15495. return EMPTY_OBJECT;
  15496. }
  15497. if (!(assertProperty instanceof ObjectExpression)) {
  15498. context.module.log(LOGLEVEL_WARN, logImportOptionsAreInvalid(context.module.id), start);
  15499. return EMPTY_OBJECT;
  15500. }
  15501. const assertFields = assertProperty.properties
  15502. .map(property => {
  15503. const key = getPropertyKey(property);
  15504. if (typeof key === 'string' &&
  15505. typeof property.value.value === 'string') {
  15506. return [key, property.value.value];
  15507. }
  15508. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), property.start);
  15509. return null;
  15510. })
  15511. .filter((property) => !!property);
  15512. if (assertFields.length > 0) {
  15513. return Object.fromEntries(assertFields);
  15514. }
  15515. return EMPTY_OBJECT;
  15516. }
  15517. const getPropertyKey = (property) => {
  15518. const key = property.key;
  15519. return (key &&
  15520. !property.computed &&
  15521. (key.name || key.value));
  15522. };
  15523. function getAttributesFromImportExportDeclaration(attributes) {
  15524. return attributes?.length
  15525. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  15526. : EMPTY_OBJECT;
  15527. }
  15528. function doAttributesDiffer(assertionA, assertionB) {
  15529. const keysA = Object.keys(assertionA);
  15530. return (keysA.length !== Object.keys(assertionB).length ||
  15531. keysA.some(key => assertionA[key] !== assertionB[key]));
  15532. }
  15533. let timers = new Map();
  15534. function getPersistedLabel(label, level) {
  15535. switch (level) {
  15536. case 1: {
  15537. return `# ${label}`;
  15538. }
  15539. case 2: {
  15540. return `## ${label}`;
  15541. }
  15542. case 3: {
  15543. return label;
  15544. }
  15545. default: {
  15546. return `- ${label}`;
  15547. }
  15548. }
  15549. }
  15550. function timeStartImpl(label, level = 3) {
  15551. label = getPersistedLabel(label, level);
  15552. const startMemory = process$1.memoryUsage().heapUsed;
  15553. const startTime = performance.now();
  15554. const timer = timers.get(label);
  15555. if (timer === undefined) {
  15556. timers.set(label, {
  15557. memory: 0,
  15558. startMemory,
  15559. startTime,
  15560. time: 0,
  15561. totalMemory: 0
  15562. });
  15563. }
  15564. else {
  15565. timer.startMemory = startMemory;
  15566. timer.startTime = startTime;
  15567. }
  15568. }
  15569. function timeEndImpl(label, level = 3) {
  15570. label = getPersistedLabel(label, level);
  15571. const timer = timers.get(label);
  15572. if (timer !== undefined) {
  15573. const currentMemory = process$1.memoryUsage().heapUsed;
  15574. timer.memory += currentMemory - timer.startMemory;
  15575. timer.time += performance.now() - timer.startTime;
  15576. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  15577. }
  15578. }
  15579. function getTimings() {
  15580. const newTimings = {};
  15581. for (const [label, { memory, time, totalMemory }] of timers) {
  15582. newTimings[label] = [time, memory, totalMemory];
  15583. }
  15584. return newTimings;
  15585. }
  15586. let timeStart = doNothing;
  15587. let timeEnd = doNothing;
  15588. const TIMED_PLUGIN_HOOKS = [
  15589. 'augmentChunkHash',
  15590. 'buildEnd',
  15591. 'buildStart',
  15592. 'generateBundle',
  15593. 'load',
  15594. 'moduleParsed',
  15595. 'options',
  15596. 'outputOptions',
  15597. 'renderChunk',
  15598. 'renderDynamicImport',
  15599. 'renderStart',
  15600. 'resolveDynamicImport',
  15601. 'resolveFileUrl',
  15602. 'resolveId',
  15603. 'resolveImportMeta',
  15604. 'shouldTransformCachedModule',
  15605. 'transform',
  15606. 'writeBundle'
  15607. ];
  15608. function getPluginWithTimers(plugin, index) {
  15609. if (plugin._hasTimer)
  15610. return plugin;
  15611. plugin._hasTimer = true;
  15612. for (const hook of TIMED_PLUGIN_HOOKS) {
  15613. if (hook in plugin) {
  15614. let timerLabel = `plugin ${index}`;
  15615. if (plugin.name) {
  15616. timerLabel += ` (${plugin.name})`;
  15617. }
  15618. timerLabel += ` - ${hook}`;
  15619. const handler = function (...parameters) {
  15620. timeStart(timerLabel, 4);
  15621. const result = hookFunction.apply(this, parameters);
  15622. timeEnd(timerLabel, 4);
  15623. return result;
  15624. };
  15625. let hookFunction;
  15626. if (typeof plugin[hook].handler === 'function') {
  15627. hookFunction = plugin[hook].handler;
  15628. plugin[hook].handler = handler;
  15629. }
  15630. else {
  15631. hookFunction = plugin[hook];
  15632. plugin[hook] = handler;
  15633. }
  15634. }
  15635. }
  15636. return plugin;
  15637. }
  15638. function initialiseTimers(inputOptions) {
  15639. if (inputOptions.perf) {
  15640. timers = new Map();
  15641. timeStart = timeStartImpl;
  15642. timeEnd = timeEndImpl;
  15643. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  15644. }
  15645. else {
  15646. timeStart = doNothing;
  15647. timeEnd = doNothing;
  15648. }
  15649. }
  15650. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  15651. identifier: null,
  15652. localName: MISSING_EXPORT_SHIM_VARIABLE
  15653. };
  15654. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  15655. const searchedModules = searchedNamesAndModules.get(name);
  15656. if (searchedModules) {
  15657. if (searchedModules.has(target)) {
  15658. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  15659. }
  15660. searchedModules.add(target);
  15661. }
  15662. else {
  15663. searchedNamesAndModules.set(name, new Set([target]));
  15664. }
  15665. return target.getVariableForExportName(name, {
  15666. importerForSideEffects,
  15667. isExportAllSearch,
  15668. searchedNamesAndModules
  15669. });
  15670. }
  15671. function getAndExtendSideEffectModules(variable, module) {
  15672. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  15673. let currentVariable = variable;
  15674. const referencedVariables = new Set([currentVariable]);
  15675. while (true) {
  15676. const importingModule = currentVariable.module;
  15677. currentVariable =
  15678. currentVariable instanceof ExportDefaultVariable
  15679. ? currentVariable.getDirectOriginalVariable()
  15680. : currentVariable instanceof SyntheticNamedExportVariable
  15681. ? currentVariable.syntheticNamespace
  15682. : null;
  15683. if (!currentVariable || referencedVariables.has(currentVariable)) {
  15684. break;
  15685. }
  15686. referencedVariables.add(currentVariable);
  15687. sideEffectModules.add(importingModule);
  15688. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  15689. if (originalSideEffects) {
  15690. for (const module of originalSideEffects) {
  15691. sideEffectModules.add(module);
  15692. }
  15693. }
  15694. }
  15695. return sideEffectModules;
  15696. }
  15697. class Module {
  15698. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  15699. this.graph = graph;
  15700. this.id = id;
  15701. this.options = options;
  15702. this.alternativeReexportModules = new Map();
  15703. this.chunkFileNames = new Set();
  15704. this.chunkNames = [];
  15705. this.cycles = new Set();
  15706. this.dependencies = new Set();
  15707. this.dynamicDependencies = new Set();
  15708. this.dynamicImporters = [];
  15709. this.dynamicImports = [];
  15710. this.execIndex = Infinity;
  15711. this.hasTreeShakingPassStarted = false;
  15712. this.implicitlyLoadedAfter = new Set();
  15713. this.implicitlyLoadedBefore = new Set();
  15714. this.importDescriptions = new Map();
  15715. this.importMetas = [];
  15716. this.importedFromNotTreeshaken = false;
  15717. this.importers = [];
  15718. this.includedDynamicImporters = [];
  15719. this.includedDirectTopLevelAwaitingDynamicImporters = new Set();
  15720. this.includedImports = new Set();
  15721. this.isExecuted = false;
  15722. this.isUserDefinedEntryPoint = false;
  15723. this.needsExportShim = false;
  15724. this.sideEffectDependenciesByVariable = new Map();
  15725. this.sourcesWithAttributes = new Map();
  15726. this.allExportNames = null;
  15727. this.allExportsIncluded = false;
  15728. this.ast = null;
  15729. this.exportAllModules = [];
  15730. this.exportAllSources = new Set();
  15731. this.exportNamesByVariable = null;
  15732. this.exportShimVariable = new ExportShimVariable(this);
  15733. this.exports = new Map();
  15734. this.namespaceReexportsByName = new Map();
  15735. this.reexportDescriptions = new Map();
  15736. this.relevantDependencies = null;
  15737. this.syntheticExports = new Map();
  15738. this.syntheticNamespace = null;
  15739. this.transformDependencies = [];
  15740. this.transitiveReexports = null;
  15741. this.excludeFromSourcemap = /\0/.test(id);
  15742. this.context = options.moduleContext(id);
  15743. this.preserveSignature = this.options.preserveEntrySignatures;
  15744. // eslint-disable-next-line @typescript-eslint/no-this-alias
  15745. const module = this;
  15746. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  15747. this.info = {
  15748. ast: null,
  15749. attributes,
  15750. code: null,
  15751. get dynamicallyImportedIdResolutions() {
  15752. return dynamicImports
  15753. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  15754. .filter(Boolean);
  15755. },
  15756. get dynamicallyImportedIds() {
  15757. // We cannot use this.dynamicDependencies because this is needed before
  15758. // dynamicDependencies are populated
  15759. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  15760. },
  15761. get dynamicImporters() {
  15762. return dynamicImporters.sort();
  15763. },
  15764. get exportedBindings() {
  15765. const exportBindings = { '.': [...exports.keys()] };
  15766. for (const [name, { source }] of reexportDescriptions) {
  15767. (exportBindings[source] ??= []).push(name);
  15768. }
  15769. for (const source of exportAllSources) {
  15770. (exportBindings[source] ??= []).push('*');
  15771. }
  15772. return exportBindings;
  15773. },
  15774. get exports() {
  15775. return [
  15776. ...exports.keys(),
  15777. ...reexportDescriptions.keys(),
  15778. ...[...exportAllSources].map(() => '*')
  15779. ];
  15780. },
  15781. get hasDefaultExport() {
  15782. // This information is only valid after parsing
  15783. if (!module.ast) {
  15784. return null;
  15785. }
  15786. return module.exports.has('default') || reexportDescriptions.has('default');
  15787. },
  15788. id,
  15789. get implicitlyLoadedAfterOneOf() {
  15790. return Array.from(implicitlyLoadedAfter, getId).sort();
  15791. },
  15792. get implicitlyLoadedBefore() {
  15793. return Array.from(implicitlyLoadedBefore, getId).sort();
  15794. },
  15795. get importedIdResolutions() {
  15796. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  15797. },
  15798. get importedIds() {
  15799. // We cannot use this.dependencies because this is needed before
  15800. // dependencies are populated
  15801. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  15802. },
  15803. get importers() {
  15804. return importers.sort();
  15805. },
  15806. isEntry,
  15807. isExternal: false,
  15808. get isIncluded() {
  15809. if (graph.phase !== BuildPhase.GENERATE) {
  15810. return null;
  15811. }
  15812. return module.isIncluded();
  15813. },
  15814. meta: { ...meta },
  15815. moduleSideEffects,
  15816. syntheticNamedExports
  15817. };
  15818. }
  15819. basename() {
  15820. const base = basename(this.id);
  15821. const extension = extname(this.id);
  15822. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  15823. }
  15824. bindReferences() {
  15825. this.ast.bind();
  15826. }
  15827. cacheInfoGetters() {
  15828. cacheObjectGetters(this.info, [
  15829. 'dynamicallyImportedIdResolutions',
  15830. 'dynamicallyImportedIds',
  15831. 'dynamicImporters',
  15832. 'exportedBindings',
  15833. 'exports',
  15834. 'hasDefaultExport',
  15835. 'implicitlyLoadedAfterOneOf',
  15836. 'implicitlyLoadedBefore',
  15837. 'importedIdResolutions',
  15838. 'importedIds',
  15839. 'importers'
  15840. ]);
  15841. }
  15842. error(properties, pos) {
  15843. if (pos !== undefined) {
  15844. this.addLocationToLogProps(properties, pos);
  15845. }
  15846. return error(properties);
  15847. }
  15848. // sum up the length of all ast nodes that are included
  15849. estimateSize() {
  15850. let size = 0;
  15851. for (const node of this.ast.body) {
  15852. if (node.included) {
  15853. size += node.end - node.start;
  15854. }
  15855. }
  15856. return size;
  15857. }
  15858. getAllExportNames() {
  15859. if (this.allExportNames) {
  15860. return this.allExportNames;
  15861. }
  15862. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  15863. for (const module of this.exportAllModules) {
  15864. if (module instanceof ExternalModule) {
  15865. this.allExportNames.add(`*${module.id}`);
  15866. continue;
  15867. }
  15868. for (const name of module.getAllExportNames()) {
  15869. if (name !== 'default')
  15870. this.allExportNames.add(name);
  15871. }
  15872. }
  15873. // We do not count the synthetic namespace as a regular export to hide it
  15874. // from entry signatures and namespace objects
  15875. if (typeof this.info.syntheticNamedExports === 'string') {
  15876. this.allExportNames.delete(this.info.syntheticNamedExports);
  15877. }
  15878. return this.allExportNames;
  15879. }
  15880. getDependenciesToBeIncluded() {
  15881. if (this.relevantDependencies)
  15882. return this.relevantDependencies;
  15883. this.relevantDependencies = new Set();
  15884. const necessaryDependencies = new Set();
  15885. const alwaysCheckedDependencies = new Set();
  15886. const dependencyVariables = new Set(this.includedImports);
  15887. if (this.info.isEntry ||
  15888. this.includedDynamicImporters.length > 0 ||
  15889. this.namespace.included ||
  15890. this.implicitlyLoadedAfter.size > 0) {
  15891. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  15892. const [exportedVariable] = this.getVariableForExportName(exportName);
  15893. if (exportedVariable?.included) {
  15894. dependencyVariables.add(exportedVariable);
  15895. }
  15896. }
  15897. }
  15898. for (let variable of dependencyVariables) {
  15899. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  15900. if (sideEffectDependencies) {
  15901. for (const module of sideEffectDependencies) {
  15902. alwaysCheckedDependencies.add(module);
  15903. }
  15904. }
  15905. if (variable instanceof SyntheticNamedExportVariable) {
  15906. variable = variable.getBaseVariable();
  15907. }
  15908. else if (variable instanceof ExportDefaultVariable) {
  15909. variable = variable.getOriginalVariable();
  15910. }
  15911. necessaryDependencies.add(variable.module);
  15912. }
  15913. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  15914. for (const dependency of this.dependencies) {
  15915. this.relevantDependencies.add(dependency);
  15916. }
  15917. }
  15918. else {
  15919. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  15920. }
  15921. for (const dependency of necessaryDependencies) {
  15922. this.relevantDependencies.add(dependency);
  15923. }
  15924. return this.relevantDependencies;
  15925. }
  15926. getExportNamesByVariable() {
  15927. if (this.exportNamesByVariable) {
  15928. return this.exportNamesByVariable;
  15929. }
  15930. const exportNamesByVariable = new Map();
  15931. for (const exportName of this.getAllExportNames()) {
  15932. let [tracedVariable] = this.getVariableForExportName(exportName);
  15933. if (tracedVariable instanceof ExportDefaultVariable) {
  15934. tracedVariable = tracedVariable.getOriginalVariable();
  15935. }
  15936. if (!tracedVariable ||
  15937. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  15938. continue;
  15939. }
  15940. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  15941. if (existingExportNames) {
  15942. existingExportNames.push(exportName);
  15943. }
  15944. else {
  15945. exportNamesByVariable.set(tracedVariable, [exportName]);
  15946. }
  15947. }
  15948. return (this.exportNamesByVariable = exportNamesByVariable);
  15949. }
  15950. getExports() {
  15951. return [...this.exports.keys()];
  15952. }
  15953. getReexports() {
  15954. if (this.transitiveReexports) {
  15955. return this.transitiveReexports;
  15956. }
  15957. // to avoid infinite recursion when using circular `export * from X`
  15958. this.transitiveReexports = [];
  15959. const reexports = new Set(this.reexportDescriptions.keys());
  15960. for (const module of this.exportAllModules) {
  15961. if (module instanceof ExternalModule) {
  15962. reexports.add(`*${module.id}`);
  15963. }
  15964. else {
  15965. for (const name of [...module.getReexports(), ...module.getExports()]) {
  15966. if (name !== 'default')
  15967. reexports.add(name);
  15968. }
  15969. }
  15970. }
  15971. return (this.transitiveReexports = [...reexports]);
  15972. }
  15973. getRenderedExports() {
  15974. // only direct exports are counted here, not reexports at all
  15975. const renderedExports = [];
  15976. const removedExports = [];
  15977. for (const exportName of this.exports.keys()) {
  15978. const [variable] = this.getVariableForExportName(exportName);
  15979. (variable?.included ? renderedExports : removedExports).push(exportName);
  15980. }
  15981. return { removedExports, renderedExports };
  15982. }
  15983. getSyntheticNamespace() {
  15984. if (this.syntheticNamespace === null) {
  15985. this.syntheticNamespace = undefined;
  15986. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  15987. ? this.info.syntheticNamedExports
  15988. : 'default', { onlyExplicit: true });
  15989. }
  15990. if (!this.syntheticNamespace) {
  15991. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  15992. }
  15993. return this.syntheticNamespace;
  15994. }
  15995. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  15996. if (name[0] === '*') {
  15997. if (name.length === 1) {
  15998. // export * from './other'
  15999. return [this.namespace];
  16000. }
  16001. // export * from 'external'
  16002. const module = this.graph.modulesById.get(name.slice(1));
  16003. return module.getVariableForExportName('*');
  16004. }
  16005. // export { foo } from './other'
  16006. const reexportDeclaration = this.reexportDescriptions.get(name);
  16007. if (reexportDeclaration) {
  16008. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  16009. if (!variable) {
  16010. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  16011. }
  16012. if (importerForSideEffects) {
  16013. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16014. if (this.info.moduleSideEffects) {
  16015. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16016. }
  16017. }
  16018. return [variable];
  16019. }
  16020. const exportDeclaration = this.exports.get(name);
  16021. if (exportDeclaration) {
  16022. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  16023. return [this.exportShimVariable];
  16024. }
  16025. const name = exportDeclaration.localName;
  16026. const variable = this.traceVariable(name, {
  16027. importerForSideEffects,
  16028. searchedNamesAndModules
  16029. });
  16030. if (importerForSideEffects) {
  16031. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16032. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16033. }
  16034. return [variable];
  16035. }
  16036. if (onlyExplicit) {
  16037. return [null];
  16038. }
  16039. if (name !== 'default') {
  16040. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  16041. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  16042. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  16043. if (foundNamespaceReexport[0]) {
  16044. return foundNamespaceReexport;
  16045. }
  16046. }
  16047. if (this.info.syntheticNamedExports) {
  16048. return [
  16049. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  16050. ];
  16051. }
  16052. // we don't want to create shims when we are just
  16053. // probing export * modules for exports
  16054. if (!isExportAllSearch && this.options.shimMissingExports) {
  16055. this.shimMissingExport(name);
  16056. return [this.exportShimVariable];
  16057. }
  16058. return [null];
  16059. }
  16060. hasEffects() {
  16061. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  16062. }
  16063. include() {
  16064. const context = createInclusionContext();
  16065. if (this.ast.shouldBeIncluded(context))
  16066. this.ast.include(context, false);
  16067. }
  16068. includeAllExports(includeNamespaceMembers) {
  16069. if (includeNamespaceMembers) {
  16070. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16071. }
  16072. if (this.allExportsIncluded)
  16073. return;
  16074. this.allExportsIncluded = true;
  16075. if (!this.isExecuted) {
  16076. markModuleAndImpureDependenciesAsExecuted(this);
  16077. this.graph.needsTreeshakingPass = true;
  16078. }
  16079. const inclusionContext = createInclusionContext();
  16080. for (const exportName of this.exports.keys()) {
  16081. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  16082. const variable = this.getVariableForExportName(exportName)[0];
  16083. if (!variable) {
  16084. return error(logMissingEntryExport(exportName, this.id));
  16085. }
  16086. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16087. variable.deoptimizePath(UNKNOWN_PATH);
  16088. }
  16089. }
  16090. for (const name of this.getReexports()) {
  16091. const [variable] = this.getVariableForExportName(name);
  16092. if (variable) {
  16093. variable.deoptimizePath(UNKNOWN_PATH);
  16094. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16095. if (variable instanceof ExternalVariable) {
  16096. variable.module.reexported = true;
  16097. }
  16098. }
  16099. }
  16100. }
  16101. includeAllInBundle() {
  16102. this.ast.include(createInclusionContext(), true);
  16103. this.includeAllExports(false);
  16104. }
  16105. includeExportsByNames(names) {
  16106. if (!this.isExecuted) {
  16107. markModuleAndImpureDependenciesAsExecuted(this);
  16108. this.graph.needsTreeshakingPass = true;
  16109. }
  16110. let includeNamespaceMembers = false;
  16111. const inclusionContext = createInclusionContext();
  16112. for (const name of names) {
  16113. const variable = this.getVariableForExportName(name)[0];
  16114. if (variable) {
  16115. variable.deoptimizePath(UNKNOWN_PATH);
  16116. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16117. }
  16118. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  16119. includeNamespaceMembers = true;
  16120. }
  16121. }
  16122. if (includeNamespaceMembers) {
  16123. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16124. }
  16125. }
  16126. isIncluded() {
  16127. // Modules where this.ast is missing have been loaded via this.load and are
  16128. // not yet fully processed, hence they cannot be included.
  16129. return (this.ast &&
  16130. (this.ast.included ||
  16131. this.namespace.included ||
  16132. this.importedFromNotTreeshaken ||
  16133. this.exportShimVariable.included));
  16134. }
  16135. linkImports() {
  16136. this.addModulesToImportDescriptions(this.importDescriptions);
  16137. this.addModulesToImportDescriptions(this.reexportDescriptions);
  16138. const externalExportAllModules = [];
  16139. for (const source of this.exportAllSources) {
  16140. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  16141. if (module instanceof ExternalModule) {
  16142. externalExportAllModules.push(module);
  16143. continue;
  16144. }
  16145. this.exportAllModules.push(module);
  16146. }
  16147. this.exportAllModules.push(...externalExportAllModules);
  16148. }
  16149. log(level, properties, pos) {
  16150. this.addLocationToLogProps(properties, pos);
  16151. this.options.onLog(level, properties);
  16152. }
  16153. render(options) {
  16154. const source = this.magicString.clone();
  16155. this.ast.render(source, options);
  16156. source.trim();
  16157. const { usesTopLevelAwait } = this.astContext;
  16158. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  16159. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  16160. }
  16161. return { source, usesTopLevelAwait };
  16162. }
  16163. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  16164. timeStart('generate ast', 3);
  16165. if (code.startsWith('#!')) {
  16166. const shebangEndPosition = code.indexOf('\n');
  16167. this.shebang = code.slice(2, shebangEndPosition);
  16168. }
  16169. this.info.code = code;
  16170. this.originalCode = originalCode;
  16171. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  16172. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  16173. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  16174. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  16175. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  16176. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  16177. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  16178. if (transformFiles) {
  16179. this.transformFiles = transformFiles;
  16180. }
  16181. this.transformDependencies = transformDependencies;
  16182. this.customTransformCache = customTransformCache;
  16183. this.updateOptions(moduleOptions);
  16184. this.resolvedIds = resolvedIds ?? Object.create(null);
  16185. // By default, `id` is the file name. Custom resolvers and loaders
  16186. // can change that, but it makes sense to use it for the source file name
  16187. const fileName = this.id;
  16188. this.magicString = new MagicString(code, {
  16189. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  16190. indentExclusionRanges: []
  16191. });
  16192. this.astContext = {
  16193. addDynamicImport: this.addDynamicImport.bind(this),
  16194. addExport: this.addExport.bind(this),
  16195. addImport: this.addImport.bind(this),
  16196. addImportMeta: this.addImportMeta.bind(this),
  16197. addImportSource: this.addImportSource.bind(this),
  16198. code, // Only needed for debugging
  16199. deoptimizationTracker: this.graph.deoptimizationTracker,
  16200. error: this.error.bind(this),
  16201. fileName, // Needed for warnings
  16202. getExports: this.getExports.bind(this),
  16203. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  16204. getModuleExecIndex: () => this.execIndex,
  16205. getModuleName: this.basename.bind(this),
  16206. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  16207. getReexports: this.getReexports.bind(this),
  16208. importDescriptions: this.importDescriptions,
  16209. includeAllExports: () => this.includeAllExports(true),
  16210. includeDynamicImport: this.includeDynamicImport.bind(this),
  16211. includeVariableInModule: this.includeVariableInModule.bind(this),
  16212. log: this.log.bind(this),
  16213. magicString: this.magicString,
  16214. manualPureFunctions: this.graph.pureFunctions,
  16215. module: this,
  16216. moduleContext: this.context,
  16217. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  16218. options: this.options,
  16219. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  16220. traceExport: (name) => this.getVariableForExportName(name)[0],
  16221. traceVariable: this.traceVariable.bind(this),
  16222. usesTopLevelAwait: false
  16223. };
  16224. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  16225. this.namespace = new NamespaceVariable(this.astContext);
  16226. const programParent = { context: this.astContext, type: 'Module' };
  16227. if (ast) {
  16228. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  16229. this.info.ast = ast;
  16230. }
  16231. else {
  16232. // Measuring asynchronous code does not provide reasonable results
  16233. timeEnd('generate ast', 3);
  16234. const astBuffer = await parseAsync(code, false, this.options.jsx !== false);
  16235. timeStart('generate ast', 3);
  16236. this.ast = convertProgram(astBuffer, programParent, this.scope);
  16237. // Make lazy and apply LRU cache to not hog the memory
  16238. Object.defineProperty(this.info, 'ast', {
  16239. get: () => {
  16240. if (this.graph.astLru.has(fileName)) {
  16241. return this.graph.astLru.get(fileName);
  16242. }
  16243. else {
  16244. const parsedAst = this.tryParse();
  16245. // If the cache is not disabled, we need to keep the AST in memory
  16246. // until the end when the cache is generated
  16247. if (this.options.cache !== false) {
  16248. Object.defineProperty(this.info, 'ast', {
  16249. value: parsedAst
  16250. });
  16251. return parsedAst;
  16252. }
  16253. // Otherwise, we keep it in a small LRU cache to not hog too much
  16254. // memory but allow the same AST to be requested several times.
  16255. this.graph.astLru.set(fileName, parsedAst);
  16256. return parsedAst;
  16257. }
  16258. }
  16259. });
  16260. }
  16261. timeEnd('generate ast', 3);
  16262. }
  16263. toJSON() {
  16264. return {
  16265. ast: this.info.ast,
  16266. attributes: this.info.attributes,
  16267. code: this.info.code,
  16268. customTransformCache: this.customTransformCache,
  16269. dependencies: Array.from(this.dependencies, getId),
  16270. id: this.id,
  16271. meta: this.info.meta,
  16272. moduleSideEffects: this.info.moduleSideEffects,
  16273. originalCode: this.originalCode,
  16274. originalSourcemap: this.originalSourcemap,
  16275. resolvedIds: this.resolvedIds,
  16276. sourcemapChain: this.sourcemapChain,
  16277. syntheticNamedExports: this.info.syntheticNamedExports,
  16278. transformDependencies: this.transformDependencies,
  16279. transformFiles: this.transformFiles
  16280. };
  16281. }
  16282. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  16283. const localVariable = this.scope.variables.get(name);
  16284. if (localVariable) {
  16285. return localVariable;
  16286. }
  16287. const importDescription = this.importDescriptions.get(name);
  16288. if (importDescription) {
  16289. const otherModule = importDescription.module;
  16290. if (otherModule instanceof Module && importDescription.name === '*') {
  16291. return otherModule.namespace;
  16292. }
  16293. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  16294. if (!declaration) {
  16295. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  16296. }
  16297. return declaration;
  16298. }
  16299. return null;
  16300. }
  16301. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  16302. if (moduleSideEffects != null) {
  16303. this.info.moduleSideEffects = moduleSideEffects;
  16304. }
  16305. if (syntheticNamedExports != null) {
  16306. this.info.syntheticNamedExports = syntheticNamedExports;
  16307. }
  16308. if (meta != null) {
  16309. Object.assign(this.info.meta, meta);
  16310. }
  16311. }
  16312. addDynamicImport(node) {
  16313. let argument = node.sourceAstNode;
  16314. if (argument.type === TemplateLiteral$1) {
  16315. if (argument.quasis.length === 1 &&
  16316. typeof argument.quasis[0].value.cooked === 'string') {
  16317. argument = argument.quasis[0].value.cooked;
  16318. }
  16319. }
  16320. else if (argument.type === Literal$1 &&
  16321. typeof argument.value === 'string') {
  16322. argument = argument.value;
  16323. }
  16324. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  16325. }
  16326. assertUniqueExportName(name, nodeStart) {
  16327. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  16328. this.error(logDuplicateExportError(name), nodeStart);
  16329. }
  16330. }
  16331. addExport(node) {
  16332. if (node instanceof ExportDefaultDeclaration) {
  16333. // export default foo;
  16334. this.assertUniqueExportName('default', node.start);
  16335. this.exports.set('default', {
  16336. identifier: node.variable.getAssignedVariableName(),
  16337. localName: 'default'
  16338. });
  16339. }
  16340. else if (node instanceof ExportAllDeclaration) {
  16341. const source = node.source.value;
  16342. this.addSource(source, node);
  16343. if (node.exported) {
  16344. // export * as name from './other'
  16345. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  16346. this.assertUniqueExportName(name, node.exported.start);
  16347. this.reexportDescriptions.set(name, {
  16348. localName: '*',
  16349. module: null, // filled in later,
  16350. source,
  16351. start: node.start
  16352. });
  16353. }
  16354. else {
  16355. // export * from './other'
  16356. this.exportAllSources.add(source);
  16357. }
  16358. }
  16359. else if (node.source instanceof Literal) {
  16360. // export { name } from './other'
  16361. const source = node.source.value;
  16362. this.addSource(source, node);
  16363. for (const { exported, local, start } of node.specifiers) {
  16364. const name = exported instanceof Literal ? exported.value : exported.name;
  16365. this.assertUniqueExportName(name, start);
  16366. this.reexportDescriptions.set(name, {
  16367. localName: local instanceof Literal ? local.value : local.name,
  16368. module: null, // filled in later,
  16369. source,
  16370. start
  16371. });
  16372. }
  16373. }
  16374. else if (node.declaration) {
  16375. const declaration = node.declaration;
  16376. if (declaration instanceof VariableDeclaration) {
  16377. // export var { foo, bar } = ...
  16378. // export var foo = 1, bar = 2;
  16379. for (const declarator of declaration.declarations) {
  16380. for (const localName of extractAssignedNames(declarator.id)) {
  16381. this.assertUniqueExportName(localName, declarator.id.start);
  16382. this.exports.set(localName, { identifier: null, localName });
  16383. }
  16384. }
  16385. }
  16386. else {
  16387. // export function foo () {}
  16388. const localName = declaration.id.name;
  16389. this.assertUniqueExportName(localName, declaration.id.start);
  16390. this.exports.set(localName, { identifier: null, localName });
  16391. }
  16392. }
  16393. else {
  16394. // export { foo, bar, baz }
  16395. for (const { local, exported } of node.specifiers) {
  16396. // except for reexports, local must be an Identifier
  16397. const localName = local.name;
  16398. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  16399. this.assertUniqueExportName(exportedName, exported.start);
  16400. this.exports.set(exportedName, { identifier: null, localName });
  16401. }
  16402. }
  16403. }
  16404. addImport(node) {
  16405. const source = node.source.value;
  16406. this.addSource(source, node);
  16407. for (const specifier of node.specifiers) {
  16408. const localName = specifier.local.name;
  16409. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  16410. this.error(logRedeclarationError(localName), specifier.local.start);
  16411. }
  16412. const name = specifier instanceof ImportDefaultSpecifier
  16413. ? 'default'
  16414. : specifier instanceof ImportNamespaceSpecifier
  16415. ? '*'
  16416. : specifier.imported instanceof Identifier
  16417. ? specifier.imported.name
  16418. : specifier.imported.value;
  16419. this.importDescriptions.set(localName, {
  16420. module: null, // filled in later
  16421. name,
  16422. source,
  16423. start: specifier.start
  16424. });
  16425. }
  16426. }
  16427. addImportSource(importSource) {
  16428. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  16429. this.sourcesWithAttributes.set(importSource, EMPTY_OBJECT);
  16430. }
  16431. }
  16432. addImportMeta(node) {
  16433. this.importMetas.push(node);
  16434. }
  16435. addLocationToLogProps(properties, pos) {
  16436. properties.id = this.id;
  16437. properties.pos = pos;
  16438. let code = this.info.code;
  16439. const location = locate(code, pos, { offsetLine: 1 });
  16440. if (location) {
  16441. let { column, line } = location;
  16442. try {
  16443. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  16444. code = this.originalCode;
  16445. }
  16446. catch (error_) {
  16447. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  16448. }
  16449. augmentCodeLocation(properties, { column, line }, code, this.id);
  16450. }
  16451. }
  16452. addModulesToImportDescriptions(importDescription) {
  16453. for (const specifier of importDescription.values()) {
  16454. const { id } = this.resolvedIds[specifier.source];
  16455. specifier.module = this.graph.modulesById.get(id);
  16456. }
  16457. }
  16458. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  16459. const handledDependencies = new Set();
  16460. const addSideEffectDependencies = (possibleDependencies) => {
  16461. for (const dependency of possibleDependencies) {
  16462. if (handledDependencies.has(dependency)) {
  16463. continue;
  16464. }
  16465. handledDependencies.add(dependency);
  16466. if (necessaryDependencies.has(dependency)) {
  16467. relevantDependencies.add(dependency);
  16468. continue;
  16469. }
  16470. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  16471. continue;
  16472. }
  16473. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  16474. relevantDependencies.add(dependency);
  16475. continue;
  16476. }
  16477. addSideEffectDependencies(dependency.dependencies);
  16478. }
  16479. };
  16480. addSideEffectDependencies(this.dependencies);
  16481. addSideEffectDependencies(alwaysCheckedDependencies);
  16482. }
  16483. addSource(source, declaration) {
  16484. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  16485. const existingAttributes = this.sourcesWithAttributes.get(source);
  16486. if (existingAttributes) {
  16487. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  16488. this.log(LOGLEVEL_WARN, logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  16489. }
  16490. }
  16491. else {
  16492. this.sourcesWithAttributes.set(source, parsedAttributes);
  16493. }
  16494. }
  16495. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  16496. const { id } = this.resolvedIds[importSource];
  16497. const module = this.graph.modulesById.get(id);
  16498. const [variable] = module.getVariableForExportName(baseName);
  16499. if (!variable) {
  16500. return this.error(logMissingJsxExport(baseName, id, this.id), nodeStart);
  16501. }
  16502. return variable;
  16503. }
  16504. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  16505. let foundSyntheticDeclaration = null;
  16506. const foundInternalDeclarations = new Map();
  16507. const foundExternalDeclarations = new Set();
  16508. for (const module of this.exportAllModules) {
  16509. // Synthetic namespaces should not hide "regular" exports of the same name
  16510. if (module.info.syntheticNamedExports === name) {
  16511. continue;
  16512. }
  16513. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  16514. // We are creating a copy to handle the case where the same binding is
  16515. // imported through different namespace reexports gracefully
  16516. copyNameToModulesMap(searchedNamesAndModules));
  16517. if (module instanceof ExternalModule || indirectExternal) {
  16518. foundExternalDeclarations.add(variable);
  16519. }
  16520. else if (variable instanceof SyntheticNamedExportVariable) {
  16521. if (!foundSyntheticDeclaration) {
  16522. foundSyntheticDeclaration = variable;
  16523. }
  16524. }
  16525. else if (variable) {
  16526. foundInternalDeclarations.set(variable, module);
  16527. }
  16528. }
  16529. if (foundInternalDeclarations.size > 0) {
  16530. const foundDeclarationList = [...foundInternalDeclarations];
  16531. const usedDeclaration = foundDeclarationList[0][0];
  16532. if (foundDeclarationList.length === 1) {
  16533. return [usedDeclaration];
  16534. }
  16535. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  16536. // TODO we are pretending it was not found while it should behave like "undefined"
  16537. return [null];
  16538. }
  16539. if (foundExternalDeclarations.size > 0) {
  16540. const foundDeclarationList = [...foundExternalDeclarations];
  16541. const usedDeclaration = foundDeclarationList[0];
  16542. if (foundDeclarationList.length > 1) {
  16543. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  16544. }
  16545. return [usedDeclaration, true];
  16546. }
  16547. if (foundSyntheticDeclaration) {
  16548. return [foundSyntheticDeclaration];
  16549. }
  16550. return [null];
  16551. }
  16552. includeAndGetAdditionalMergedNamespaces() {
  16553. const externalNamespaces = new Set();
  16554. const syntheticNamespaces = new Set();
  16555. for (const module of [this, ...this.exportAllModules]) {
  16556. if (module instanceof ExternalModule) {
  16557. const [externalVariable] = module.getVariableForExportName('*');
  16558. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  16559. this.includedImports.add(externalVariable);
  16560. externalNamespaces.add(externalVariable);
  16561. }
  16562. else if (module.info.syntheticNamedExports) {
  16563. const syntheticNamespace = module.getSyntheticNamespace();
  16564. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  16565. this.includedImports.add(syntheticNamespace);
  16566. syntheticNamespaces.add(syntheticNamespace);
  16567. }
  16568. }
  16569. return [...syntheticNamespaces, ...externalNamespaces];
  16570. }
  16571. includeDynamicImport(node) {
  16572. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  16573. if (resolution instanceof Module) {
  16574. if (!resolution.includedDynamicImporters.includes(this)) {
  16575. resolution.includedDynamicImporters.push(this);
  16576. if (node.withinTopLevelAwait) {
  16577. resolution.includedDirectTopLevelAwaitingDynamicImporters.add(this);
  16578. }
  16579. }
  16580. const importedNames = this.options.treeshake
  16581. ? node.getDeterministicImportedNames()
  16582. : undefined;
  16583. if (importedNames) {
  16584. resolution.includeExportsByNames(importedNames);
  16585. }
  16586. else {
  16587. resolution.includeAllExports(true);
  16588. }
  16589. }
  16590. }
  16591. includeVariable(variable, path, context) {
  16592. const { included, module: variableModule } = variable;
  16593. variable.includePath(path, context);
  16594. if (included) {
  16595. if (variableModule instanceof Module && variableModule !== this) {
  16596. getAndExtendSideEffectModules(variable, this);
  16597. }
  16598. }
  16599. else {
  16600. this.graph.needsTreeshakingPass = true;
  16601. if (variableModule instanceof Module) {
  16602. if (!variableModule.isExecuted) {
  16603. markModuleAndImpureDependenciesAsExecuted(variableModule);
  16604. }
  16605. if (variableModule !== this) {
  16606. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  16607. for (const module of sideEffectModules) {
  16608. if (!module.isExecuted) {
  16609. markModuleAndImpureDependenciesAsExecuted(module);
  16610. }
  16611. }
  16612. }
  16613. }
  16614. }
  16615. }
  16616. includeVariableInModule(variable, path, context) {
  16617. this.includeVariable(variable, path, context);
  16618. const variableModule = variable.module;
  16619. if (variableModule && variableModule !== this) {
  16620. this.includedImports.add(variable);
  16621. }
  16622. }
  16623. shimMissingExport(name) {
  16624. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  16625. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  16626. }
  16627. tryParse() {
  16628. try {
  16629. return parseAst(this.info.code, { jsx: this.options.jsx !== false });
  16630. }
  16631. catch (error_) {
  16632. return this.error(logModuleParseError(error_, this.id), error_.pos);
  16633. }
  16634. }
  16635. }
  16636. // if there is a cyclic import in the reexport chain, we should not
  16637. // import from the original module but from the cyclic module to not
  16638. // mess up execution order.
  16639. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  16640. if (variable.module instanceof Module && variable.module !== reexporter) {
  16641. const exporterCycles = variable.module.cycles;
  16642. if (exporterCycles.size > 0) {
  16643. const importerCycles = reexporter.cycles;
  16644. for (const cycleSymbol of importerCycles) {
  16645. if (exporterCycles.has(cycleSymbol)) {
  16646. importer.alternativeReexportModules.set(variable, reexporter);
  16647. break;
  16648. }
  16649. }
  16650. }
  16651. }
  16652. }
  16653. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  16654. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  16655. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  16656. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  16657. async function createAddons(options, outputPluginDriver, chunk) {
  16658. try {
  16659. let [banner, footer, intro, outro] = await Promise.all([
  16660. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  16661. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  16662. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  16663. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  16664. ]);
  16665. if (intro)
  16666. intro += '\n\n';
  16667. if (outro)
  16668. outro = `\n\n${outro}`;
  16669. if (banner)
  16670. banner += '\n';
  16671. if (footer)
  16672. footer = '\n' + footer;
  16673. return { banner, footer, intro, outro };
  16674. }
  16675. catch (error_) {
  16676. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  16677. }
  16678. }
  16679. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  16680. amd: deconflictImportsOther,
  16681. cjs: deconflictImportsOther,
  16682. es: deconflictImportsEsmOrSystem,
  16683. iife: deconflictImportsOther,
  16684. system: deconflictImportsEsmOrSystem,
  16685. umd: deconflictImportsOther
  16686. };
  16687. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  16688. const reversedModules = [...modules].reverse();
  16689. for (const module of reversedModules) {
  16690. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  16691. }
  16692. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  16693. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  16694. for (const module of reversedModules) {
  16695. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  16696. }
  16697. }
  16698. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  16699. // This is needed for namespace reexports
  16700. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  16701. if (preserveModules || dependency instanceof ExternalChunk) {
  16702. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  16703. }
  16704. }
  16705. for (const variable of imports) {
  16706. const module = variable.module;
  16707. const name = variable.name;
  16708. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  16709. variable.setRenderNames(null, (module instanceof ExternalModule
  16710. ? externalChunkByModule.get(module)
  16711. : chunkByModule.get(module)).variableName);
  16712. }
  16713. else if (module instanceof ExternalModule && name === 'default') {
  16714. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  16715. ? module.suggestedVariableName + '__default'
  16716. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  16717. }
  16718. else {
  16719. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  16720. }
  16721. }
  16722. for (const variable of syntheticExports) {
  16723. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16724. }
  16725. }
  16726. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  16727. for (const chunk of dependencies) {
  16728. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  16729. }
  16730. for (const chunk of deconflictedNamespace) {
  16731. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  16732. }
  16733. for (const externalModule of deconflictedDefault) {
  16734. externalModule.defaultVariableName =
  16735. deconflictedNamespace.has(externalModule) &&
  16736. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  16737. ? externalModule.namespaceVariableName
  16738. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  16739. }
  16740. for (const variable of imports) {
  16741. const module = variable.module;
  16742. if (module instanceof ExternalModule) {
  16743. const chunk = externalChunkByModule.get(module);
  16744. const name = variable.name;
  16745. if (name === 'default') {
  16746. const moduleInterop = interop(module.id);
  16747. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  16748. ? chunk.defaultVariableName
  16749. : chunk.variableName;
  16750. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  16751. variable.setRenderNames(variableName, 'default');
  16752. }
  16753. else {
  16754. variable.setRenderNames(null, variableName);
  16755. }
  16756. }
  16757. else if (name === '*') {
  16758. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  16759. ? chunk.namespaceVariableName
  16760. : chunk.variableName);
  16761. }
  16762. else {
  16763. // if the second parameter is `null`, it uses its "name" for the property name
  16764. variable.setRenderNames(chunk.variableName, null);
  16765. }
  16766. }
  16767. else {
  16768. const chunk = chunkByModule.get(module);
  16769. if (preserveModules && variable.isNamespace) {
  16770. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  16771. }
  16772. else if (chunk.exportMode === 'default') {
  16773. variable.setRenderNames(null, chunk.variableName);
  16774. }
  16775. else {
  16776. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  16777. }
  16778. }
  16779. }
  16780. }
  16781. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  16782. for (const module of modules) {
  16783. for (const variable of module.scope.variables.values()) {
  16784. if (variable.included &&
  16785. // this will only happen for exports in some formats
  16786. !(variable.renderBaseName ||
  16787. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  16788. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16789. }
  16790. }
  16791. if (includedNamespaces.has(module)) {
  16792. const namespace = module.namespace;
  16793. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  16794. }
  16795. }
  16796. }
  16797. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  16798. let nameIndex = 0;
  16799. for (const variable of exports) {
  16800. let [exportName] = variable.name;
  16801. if (exportsByName.has(exportName)) {
  16802. do {
  16803. exportName = toBase64(++nameIndex);
  16804. // skip past leading number identifiers
  16805. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  16806. nameIndex += 9 * 64 ** (exportName.length - 1);
  16807. exportName = toBase64(nameIndex);
  16808. }
  16809. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  16810. }
  16811. exportsByName.set(exportName, variable);
  16812. exportNamesByVariable.set(variable, [exportName]);
  16813. }
  16814. }
  16815. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  16816. for (const variable of exports) {
  16817. let nameIndex = 0;
  16818. let exportName = variable.name;
  16819. while (exportsByName.has(exportName)) {
  16820. exportName = variable.name + '$' + ++nameIndex;
  16821. }
  16822. exportsByName.set(exportName, variable);
  16823. exportNamesByVariable.set(variable, [exportName]);
  16824. }
  16825. }
  16826. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  16827. const exportKeys = chunk.getExportNames();
  16828. if (exportMode === 'default') {
  16829. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  16830. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  16831. }
  16832. }
  16833. else if (exportMode === 'none' && exportKeys.length > 0) {
  16834. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  16835. }
  16836. if (exportMode === 'auto') {
  16837. if (exportKeys.length === 0) {
  16838. exportMode = 'none';
  16839. }
  16840. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  16841. exportMode = 'default';
  16842. }
  16843. else {
  16844. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  16845. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  16846. }
  16847. exportMode = 'named';
  16848. }
  16849. }
  16850. return exportMode;
  16851. }
  16852. function guessIndentString(code) {
  16853. const lines = code.split('\n');
  16854. const tabbed = lines.filter(line => /^\t+/.test(line));
  16855. const spaced = lines.filter(line => /^ {2,}/.test(line));
  16856. if (tabbed.length === 0 && spaced.length === 0) {
  16857. return null;
  16858. }
  16859. // More lines tabbed than spaced? Assume tabs, and
  16860. // default to tabs in the case of a tie (or nothing
  16861. // to go on)
  16862. if (tabbed.length >= spaced.length) {
  16863. return '\t';
  16864. }
  16865. // Otherwise, we need to guess the multiple
  16866. const min = spaced.reduce((previous, current) => {
  16867. const numberSpaces = /^ +/.exec(current)[0].length;
  16868. return Math.min(numberSpaces, previous);
  16869. }, Infinity);
  16870. return ' '.repeat(min);
  16871. }
  16872. function getIndentString(modules, options) {
  16873. if (options.indent !== true)
  16874. return options.indent;
  16875. for (const module of modules) {
  16876. const indent = guessIndentString(module.originalCode);
  16877. if (indent !== null)
  16878. return indent;
  16879. }
  16880. return '\t';
  16881. }
  16882. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  16883. const staticDependencyBlocks = [];
  16884. const handledDependencies = new Set();
  16885. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  16886. const module = orderedModules[modulePos];
  16887. if (!handledDependencies.has(module)) {
  16888. const staticDependencies = [];
  16889. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  16890. staticDependencyBlocks.unshift(staticDependencies);
  16891. }
  16892. }
  16893. const dependencies = new Set();
  16894. for (const block of staticDependencyBlocks) {
  16895. for (const dependency of block) {
  16896. dependencies.add(dependency);
  16897. }
  16898. }
  16899. return dependencies;
  16900. }
  16901. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  16902. const dependencies = module.getDependenciesToBeIncluded();
  16903. for (const dependency of dependencies) {
  16904. if (dependency instanceof ExternalModule) {
  16905. staticDependencies.push(externalChunkByModule.get(dependency));
  16906. continue;
  16907. }
  16908. const dependencyChunk = chunkByModule.get(dependency);
  16909. if (dependencyChunk !== chunk) {
  16910. staticDependencies.push(dependencyChunk);
  16911. continue;
  16912. }
  16913. if (!handledModules.has(dependency)) {
  16914. handledModules.add(dependency);
  16915. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  16916. }
  16917. }
  16918. }
  16919. // Four random characters from the private use area to minimize risk of
  16920. // conflicts
  16921. const hashPlaceholderLeft = '!~{';
  16922. const hashPlaceholderRight = '}~';
  16923. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  16924. // This is the size of a 128-bits xxhash with base64url encoding
  16925. const MAX_HASH_SIZE = 21;
  16926. const DEFAULT_HASH_SIZE = 8;
  16927. const getHashPlaceholderGenerator = () => {
  16928. let nextIndex = 0;
  16929. return (optionName, hashSize) => {
  16930. if (hashSize > MAX_HASH_SIZE) {
  16931. return error(logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  16932. }
  16933. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  16934. if (placeholder.length > hashSize) {
  16935. return error(logFailedValidation(`To generate hashes for this number of chunks (currently ${nextIndex}), you need a minimum hash size of ${placeholder.length}, received ${hashSize}. Check the "${optionName}" option.`));
  16936. }
  16937. return placeholder;
  16938. };
  16939. };
  16940. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  16941. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  16942. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  16943. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  16944. const containedPlaceholders = new Set();
  16945. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  16946. if (placeholders.has(placeholder)) {
  16947. containedPlaceholders.add(placeholder);
  16948. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  16949. }
  16950. return placeholder;
  16951. });
  16952. return { containedPlaceholders, transformedCode };
  16953. };
  16954. const lowercaseBundleKeys = Symbol('bundleKeys');
  16955. const FILE_PLACEHOLDER = {
  16956. type: 'placeholder'
  16957. };
  16958. const getOutputBundle = (outputBundleBase) => {
  16959. const reservedLowercaseBundleKeys = new Set();
  16960. return new Proxy(outputBundleBase, {
  16961. deleteProperty(target, key) {
  16962. if (typeof key === 'string') {
  16963. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  16964. }
  16965. return Reflect.deleteProperty(target, key);
  16966. },
  16967. get(target, key) {
  16968. if (key === lowercaseBundleKeys) {
  16969. return reservedLowercaseBundleKeys;
  16970. }
  16971. return Reflect.get(target, key);
  16972. },
  16973. set(target, key, value) {
  16974. if (typeof key === 'string') {
  16975. reservedLowercaseBundleKeys.add(key.toLowerCase());
  16976. }
  16977. return Reflect.set(target, key, value);
  16978. }
  16979. });
  16980. };
  16981. const removeUnreferencedAssets = (outputBundle) => {
  16982. const unreferencedAssets = new Set();
  16983. const bundleEntries = Object.values(outputBundle);
  16984. for (const asset of bundleEntries) {
  16985. if (asset.type === 'asset' && asset.needsCodeReference) {
  16986. unreferencedAssets.add(asset.fileName);
  16987. }
  16988. }
  16989. for (const chunk of bundleEntries) {
  16990. if (chunk.type === 'chunk') {
  16991. for (const referencedFile of chunk.referencedFiles) {
  16992. if (unreferencedAssets.has(referencedFile)) {
  16993. unreferencedAssets.delete(referencedFile);
  16994. }
  16995. }
  16996. }
  16997. }
  16998. for (const file of unreferencedAssets) {
  16999. delete outputBundle[file];
  17000. }
  17001. };
  17002. function renderNamePattern(pattern, patternName, replacements) {
  17003. if (isPathFragment(pattern))
  17004. return error(logFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
  17005. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  17006. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  17007. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  17008. }
  17009. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  17010. if (isPathFragment(replacement))
  17011. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  17012. return replacement;
  17013. });
  17014. }
  17015. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  17016. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  17017. return name;
  17018. const extension = extname(name);
  17019. name = name.slice(0, Math.max(0, name.length - extension.length));
  17020. let uniqueName, uniqueIndex = 1;
  17021. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  17022. ;
  17023. return uniqueName;
  17024. }
  17025. const NON_ASSET_EXTENSIONS = new Set([
  17026. '.js',
  17027. '.jsx',
  17028. '.ts',
  17029. '.tsx',
  17030. '.mjs',
  17031. '.mts',
  17032. '.cjs',
  17033. '.cts'
  17034. ]);
  17035. function getGlobalName(chunk, globals, hasExports, log) {
  17036. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  17037. if (globalName) {
  17038. return globalName;
  17039. }
  17040. if (hasExports) {
  17041. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  17042. return chunk.variableName;
  17043. }
  17044. }
  17045. class Chunk {
  17046. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  17047. this.orderedModules = orderedModules;
  17048. this.inputOptions = inputOptions;
  17049. this.outputOptions = outputOptions;
  17050. this.unsetOptions = unsetOptions;
  17051. this.pluginDriver = pluginDriver;
  17052. this.modulesById = modulesById;
  17053. this.chunkByModule = chunkByModule;
  17054. this.externalChunkByModule = externalChunkByModule;
  17055. this.facadeChunkByModule = facadeChunkByModule;
  17056. this.includedNamespaces = includedNamespaces;
  17057. this.manualChunkAlias = manualChunkAlias;
  17058. this.getPlaceholder = getPlaceholder;
  17059. this.bundle = bundle;
  17060. this.inputBase = inputBase;
  17061. this.snippets = snippets;
  17062. this.dependencies = new Set();
  17063. this.entryModules = [];
  17064. this.exportMode = 'named';
  17065. this.facadeModule = null;
  17066. this.namespaceVariableName = '';
  17067. this.variableName = '';
  17068. this.accessedGlobalsByScope = new Map();
  17069. this.dynamicEntryModules = [];
  17070. this.dynamicName = null;
  17071. this.exportNamesByVariable = new Map();
  17072. this.exports = new Set();
  17073. this.exportsByName = new Map();
  17074. this.fileName = null;
  17075. this.implicitEntryModules = [];
  17076. this.implicitlyLoadedBefore = new Set();
  17077. this.imports = new Set();
  17078. this.includedDynamicImports = null;
  17079. this.includedReexportsByModule = new Map();
  17080. // This may be updated in the constructor
  17081. this.isEmpty = true;
  17082. this.name = null;
  17083. this.needsExportsShim = false;
  17084. this.preRenderedChunkInfo = null;
  17085. this.preliminaryFileName = null;
  17086. this.preliminarySourcemapFileName = null;
  17087. this.renderedChunkInfo = null;
  17088. this.renderedDependencies = null;
  17089. this.renderedModules = Object.create(null);
  17090. this.sortedExportNames = null;
  17091. this.strictFacade = false;
  17092. /** Modules with 'allow-extension' that should have preserved exports within the chunk */
  17093. this.allowExtensionModules = new Set();
  17094. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  17095. const chunkModules = new Set(orderedModules);
  17096. for (const module of orderedModules) {
  17097. chunkByModule.set(module, this);
  17098. if (module.namespace.included && !outputOptions.preserveModules) {
  17099. includedNamespaces.add(module);
  17100. }
  17101. if (this.isEmpty && module.isIncluded()) {
  17102. this.isEmpty = false;
  17103. }
  17104. if (module.info.isEntry || outputOptions.preserveModules) {
  17105. this.entryModules.push(module);
  17106. }
  17107. for (const importer of module.includedDynamicImporters) {
  17108. if (!chunkModules.has(importer)) {
  17109. this.dynamicEntryModules.push(module);
  17110. // Modules with synthetic exports need an artificial namespace for dynamic imports
  17111. if (module.info.syntheticNamedExports) {
  17112. includedNamespaces.add(module);
  17113. this.exports.add(module.namespace);
  17114. }
  17115. }
  17116. }
  17117. if (module.implicitlyLoadedAfter.size > 0) {
  17118. this.implicitEntryModules.push(module);
  17119. }
  17120. }
  17121. this.suggestedVariableName = makeLegal(this.generateVariableName());
  17122. }
  17123. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  17124. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  17125. chunk.assignFacadeName(facadeName, facadedModule);
  17126. if (!facadeChunkByModule.has(facadedModule)) {
  17127. facadeChunkByModule.set(facadedModule, chunk);
  17128. }
  17129. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  17130. chunk.dependencies.add(dependency instanceof Module
  17131. ? chunkByModule.get(dependency)
  17132. : externalChunkByModule.get(dependency));
  17133. }
  17134. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  17135. facadedModule.info.moduleSideEffects &&
  17136. facadedModule.hasEffects()) {
  17137. chunk.dependencies.add(chunkByModule.get(facadedModule));
  17138. }
  17139. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  17140. chunk.facadeModule = facadedModule;
  17141. chunk.strictFacade = true;
  17142. return chunk;
  17143. }
  17144. canModuleBeFacade(module, exposedVariables) {
  17145. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  17146. // All exports of this chunk need to be exposed by the candidate module
  17147. for (const exposedVariable of this.exports) {
  17148. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  17149. return false;
  17150. }
  17151. }
  17152. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  17153. for (const exposedVariable of exposedVariables) {
  17154. if (!(exposedVariable.module === module ||
  17155. moduleExportNamesByVariable.has(exposedVariable) ||
  17156. (exposedVariable instanceof SyntheticNamedExportVariable &&
  17157. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  17158. return false;
  17159. }
  17160. }
  17161. return true;
  17162. }
  17163. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  17164. const renderedChunkInfo = this.getRenderedChunkInfo();
  17165. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  17166. const preliminaryFileName = renderedChunkInfo.fileName;
  17167. const fileName = (this.fileName = finalize(preliminaryFileName));
  17168. return {
  17169. ...renderedChunkInfo,
  17170. code,
  17171. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  17172. fileName,
  17173. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  17174. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  17175. finalize(fileName),
  17176. bindings
  17177. ])),
  17178. imports: renderedChunkInfo.imports.map(finalize),
  17179. map,
  17180. preliminaryFileName,
  17181. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  17182. sourcemapFileName
  17183. };
  17184. }
  17185. generateExports() {
  17186. this.sortedExportNames = null;
  17187. const remainingExports = new Set(this.exports);
  17188. if (this.facadeModule !== null &&
  17189. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  17190. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  17191. for (const [variable, exportNames] of exportNamesByVariable) {
  17192. this.exportNamesByVariable.set(variable, [...exportNames]);
  17193. for (const exportName of exportNames) {
  17194. this.exportsByName.set(exportName, variable);
  17195. }
  17196. remainingExports.delete(variable);
  17197. }
  17198. }
  17199. for (const module of this.allowExtensionModules) {
  17200. const exportNamesByVariable = module.getExportNamesByVariable();
  17201. for (const [variable, exportNames] of exportNamesByVariable) {
  17202. this.exportNamesByVariable.set(variable, [...exportNames]);
  17203. for (const exportName of exportNames) {
  17204. this.exportsByName.set(exportName, variable);
  17205. }
  17206. remainingExports.delete(variable);
  17207. }
  17208. }
  17209. if (this.outputOptions.minifyInternalExports) {
  17210. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17211. }
  17212. else {
  17213. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17214. }
  17215. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  17216. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  17217. }
  17218. generateFacades() {
  17219. const facades = [];
  17220. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  17221. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  17222. for (const module of entryModules) {
  17223. if (module.preserveSignature === 'allow-extension') {
  17224. const canPreserveExports = this.canPreserveModuleExports(module);
  17225. if (canPreserveExports) {
  17226. this.allowExtensionModules.add(module);
  17227. if (!this.facadeModule) {
  17228. this.facadeModule = module;
  17229. this.strictFacade = false;
  17230. this.assignFacadeName({}, module, this.outputOptions.preserveModules);
  17231. }
  17232. this.facadeChunkByModule.set(module, this);
  17233. continue;
  17234. }
  17235. }
  17236. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  17237. // mapping must run after Set 'name' dedupe
  17238. name => ({
  17239. name
  17240. }));
  17241. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  17242. requiredFacades.push({});
  17243. }
  17244. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  17245. if (requiredFacades.length === 0) {
  17246. requiredFacades.push({});
  17247. }
  17248. if (!this.facadeModule) {
  17249. const needsStrictFacade = !this.outputOptions.preserveModules &&
  17250. (module.preserveSignature === 'strict' ||
  17251. (module.preserveSignature === 'exports-only' &&
  17252. module.getExportNamesByVariable().size > 0));
  17253. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  17254. this.facadeModule = module;
  17255. this.facadeChunkByModule.set(module, this);
  17256. if (module.preserveSignature) {
  17257. this.strictFacade = needsStrictFacade;
  17258. }
  17259. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  17260. }
  17261. }
  17262. for (const facadeName of requiredFacades) {
  17263. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName, this.getPlaceholder, this.bundle, this.inputBase, this.snippets));
  17264. }
  17265. }
  17266. for (const module of this.dynamicEntryModules) {
  17267. if (module.info.syntheticNamedExports)
  17268. continue;
  17269. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  17270. this.facadeModule = module;
  17271. this.facadeChunkByModule.set(module, this);
  17272. this.strictFacade = true;
  17273. this.dynamicName = getChunkNameFromModule(module);
  17274. }
  17275. else if (this.facadeModule === module &&
  17276. !this.strictFacade &&
  17277. this.canModuleBeFacade(module, exposedVariables)) {
  17278. this.strictFacade = true;
  17279. }
  17280. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  17281. this.includedNamespaces.add(module);
  17282. this.exports.add(module.namespace);
  17283. }
  17284. }
  17285. if (!this.outputOptions.preserveModules) {
  17286. this.addNecessaryImportsForFacades();
  17287. }
  17288. return facades;
  17289. }
  17290. canPreserveModuleExports(module) {
  17291. const exportNamesByVariable = module.getExportNamesByVariable();
  17292. // Check for conflicts - an export name is a conflict if it points to a different module or definition
  17293. for (const [variable, exportNames] of exportNamesByVariable) {
  17294. for (const exportName of exportNames) {
  17295. const existingVariable = this.exportsByName.get(exportName);
  17296. // It's ok if the same export name in two modules references the exact same variable
  17297. if (existingVariable && existingVariable !== variable) {
  17298. return false;
  17299. }
  17300. }
  17301. }
  17302. // No actual conflicts found, add export names for future conflict checks
  17303. for (const [variable, exportNames] of exportNamesByVariable) {
  17304. for (const exportName of exportNames) {
  17305. this.exportsByName.set(exportName, variable);
  17306. }
  17307. }
  17308. return true;
  17309. }
  17310. getChunkName() {
  17311. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  17312. }
  17313. getExportNames() {
  17314. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  17315. }
  17316. getFileName() {
  17317. return this.fileName || this.getPreliminaryFileName().fileName;
  17318. }
  17319. getImportPath(importer) {
  17320. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  17321. }
  17322. getPreliminaryFileName() {
  17323. if (this.preliminaryFileName) {
  17324. return this.preliminaryFileName;
  17325. }
  17326. let fileName;
  17327. let hashPlaceholder = null;
  17328. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  17329. if (file) {
  17330. fileName = basename(file);
  17331. }
  17332. else if (this.fileName === null) {
  17333. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  17334. ? [entryFileNames, 'output.entryFileNames']
  17335. : [chunkFileNames, 'output.chunkFileNames'];
  17336. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17337. format: () => format,
  17338. hash: size => hashPlaceholder ||
  17339. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17340. name: () => this.getChunkName()
  17341. });
  17342. if (!hashPlaceholder) {
  17343. fileName = makeUnique(fileName, this.bundle);
  17344. }
  17345. }
  17346. else {
  17347. fileName = this.fileName;
  17348. }
  17349. if (!hashPlaceholder) {
  17350. this.bundle[fileName] = FILE_PLACEHOLDER;
  17351. }
  17352. // Caching is essential to not conflict with the file name reservation above
  17353. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  17354. }
  17355. getPreliminarySourcemapFileName() {
  17356. if (this.preliminarySourcemapFileName) {
  17357. return this.preliminarySourcemapFileName;
  17358. }
  17359. let sourcemapFileName = null;
  17360. let hashPlaceholder = null;
  17361. const { sourcemapFileNames, format } = this.outputOptions;
  17362. if (sourcemapFileNames) {
  17363. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  17364. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17365. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  17366. format: () => format,
  17367. hash: size => hashPlaceholder ||
  17368. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17369. name: () => this.getChunkName()
  17370. });
  17371. if (!hashPlaceholder) {
  17372. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  17373. }
  17374. }
  17375. else {
  17376. return null;
  17377. }
  17378. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  17379. }
  17380. getRenderedChunkInfo() {
  17381. if (this.renderedChunkInfo) {
  17382. return this.renderedChunkInfo;
  17383. }
  17384. return (this.renderedChunkInfo = {
  17385. ...this.getPreRenderedChunkInfo(),
  17386. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  17387. fileName: this.getFileName(),
  17388. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  17389. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  17390. imports: Array.from(this.dependencies, resolveFileName),
  17391. modules: this.renderedModules,
  17392. referencedFiles: this.getReferencedFiles()
  17393. });
  17394. }
  17395. getVariableExportName(variable) {
  17396. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  17397. return '*';
  17398. }
  17399. return this.exportNamesByVariable.get(variable)[0];
  17400. }
  17401. link() {
  17402. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  17403. for (const module of this.orderedModules) {
  17404. this.addImplicitlyLoadedBeforeFromModule(module);
  17405. this.setUpChunkImportsAndExportsForModule(module);
  17406. }
  17407. }
  17408. inlineTransitiveImports() {
  17409. const { facadeModule, dependencies, outputOptions } = this;
  17410. const { hoistTransitiveImports, preserveModules } = outputOptions;
  17411. // for static and dynamic entry points, add transitive dependencies to this
  17412. // chunk's dependencies to avoid loading latency
  17413. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  17414. for (const dep of dependencies) {
  17415. if (dep instanceof Chunk)
  17416. this.inlineChunkDependencies(dep);
  17417. }
  17418. }
  17419. }
  17420. async render() {
  17421. const { exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  17422. const { format, preserveModules } = outputOptions;
  17423. const preliminaryFileName = this.getPreliminaryFileName();
  17424. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  17425. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  17426. const renderedDependencies = [...this.getRenderedDependencies().values()];
  17427. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  17428. let hasExports = renderedExports.length > 0;
  17429. let hasDefaultExport = false;
  17430. for (const renderedDependency of renderedDependencies) {
  17431. const { reexports } = renderedDependency;
  17432. if (reexports?.length) {
  17433. hasExports = true;
  17434. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  17435. hasDefaultExport = true;
  17436. }
  17437. if (format === 'es') {
  17438. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  17439. }
  17440. }
  17441. }
  17442. if (!hasDefaultExport) {
  17443. for (const { exported } of renderedExports) {
  17444. if (exported === 'default') {
  17445. hasDefaultExport = true;
  17446. break;
  17447. }
  17448. }
  17449. }
  17450. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  17451. finalisers[format](renderedSource, {
  17452. accessedGlobals,
  17453. dependencies: renderedDependencies,
  17454. exports: renderedExports,
  17455. hasDefaultExport,
  17456. hasExports,
  17457. id: preliminaryFileName.fileName,
  17458. indent,
  17459. intro,
  17460. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  17461. isModuleFacade: facadeModule !== null,
  17462. log: onLog,
  17463. namedExportsMode: exportMode !== 'default',
  17464. outro,
  17465. snippets,
  17466. usesTopLevelAwait
  17467. }, outputOptions);
  17468. if (banner)
  17469. magicString.prepend(banner);
  17470. if (format === 'es' || format === 'cjs') {
  17471. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  17472. if (shebang) {
  17473. magicString.prepend(`#!${shebang}\n`);
  17474. }
  17475. }
  17476. if (footer)
  17477. magicString.append(footer);
  17478. return {
  17479. chunk: this,
  17480. magicString,
  17481. preliminaryFileName,
  17482. preliminarySourcemapFileName,
  17483. usedModules
  17484. };
  17485. }
  17486. addImplicitlyLoadedBeforeFromModule(baseModule) {
  17487. const { chunkByModule, implicitlyLoadedBefore } = this;
  17488. for (const module of baseModule.implicitlyLoadedBefore) {
  17489. const chunk = chunkByModule.get(module);
  17490. if (chunk && chunk !== this) {
  17491. implicitlyLoadedBefore.add(chunk);
  17492. }
  17493. }
  17494. }
  17495. addNecessaryImportsForFacades() {
  17496. for (const [module, variables] of this.includedReexportsByModule) {
  17497. if (this.includedNamespaces.has(module)) {
  17498. for (const variable of variables) {
  17499. this.imports.add(variable);
  17500. }
  17501. }
  17502. }
  17503. }
  17504. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  17505. if (fileName) {
  17506. this.fileName = fileName;
  17507. }
  17508. else {
  17509. this.name = this.outputOptions.sanitizeFileName(name ||
  17510. (preservePath
  17511. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  17512. : getChunkNameFromModule(facadedModule)));
  17513. }
  17514. }
  17515. checkCircularDependencyImport(variable, importingModule) {
  17516. const variableModule = variable.module;
  17517. if (variableModule instanceof Module) {
  17518. const exportChunk = this.chunkByModule.get(variableModule);
  17519. let alternativeReexportModule;
  17520. do {
  17521. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  17522. if (alternativeReexportModule) {
  17523. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  17524. if (exportingChunk !== exportChunk) {
  17525. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  17526. // Namespaces do not have an export name
  17527. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  17528. }
  17529. importingModule = alternativeReexportModule;
  17530. }
  17531. } while (alternativeReexportModule);
  17532. }
  17533. }
  17534. ensureReexportsAreAvailableForModule(module) {
  17535. const includedReexports = [];
  17536. const map = module.getExportNamesByVariable();
  17537. for (const exportedVariable of map.keys()) {
  17538. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  17539. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  17540. this.checkCircularDependencyImport(importedVariable, module);
  17541. // When preserving modules, we do not create namespace objects but directly
  17542. // use the actual namespaces, which would be broken by this logic.
  17543. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  17544. const exportingModule = importedVariable.module;
  17545. if (exportingModule instanceof Module) {
  17546. const chunk = this.chunkByModule.get(exportingModule);
  17547. if (chunk && chunk !== this) {
  17548. chunk.exports.add(importedVariable);
  17549. includedReexports.push(importedVariable);
  17550. if (isSynthetic) {
  17551. this.imports.add(importedVariable);
  17552. }
  17553. }
  17554. }
  17555. }
  17556. }
  17557. if (includedReexports.length > 0) {
  17558. this.includedReexportsByModule.set(module, includedReexports);
  17559. }
  17560. }
  17561. generateVariableName() {
  17562. if (this.manualChunkAlias) {
  17563. return this.manualChunkAlias;
  17564. }
  17565. const moduleForNaming = this.entryModules[0] ||
  17566. this.implicitEntryModules[0] ||
  17567. this.dynamicEntryModules[0] ||
  17568. this.orderedModules[this.orderedModules.length - 1];
  17569. if (moduleForNaming) {
  17570. return getChunkNameFromModule(moduleForNaming);
  17571. }
  17572. return 'chunk';
  17573. }
  17574. getChunkExportDeclarations(format) {
  17575. const exports = [];
  17576. for (const exportName of this.getExportNames()) {
  17577. if (exportName[0] === '*')
  17578. continue;
  17579. const variable = this.exportsByName.get(exportName);
  17580. if (!(variable instanceof SyntheticNamedExportVariable)) {
  17581. const module = variable.module;
  17582. if (module) {
  17583. const chunk = this.chunkByModule.get(module);
  17584. if (chunk !== this) {
  17585. if (!chunk || format !== 'es') {
  17586. continue;
  17587. }
  17588. const chunkDep = this.renderedDependencies.get(chunk);
  17589. if (!chunkDep) {
  17590. continue;
  17591. }
  17592. const { imports, reexports } = chunkDep;
  17593. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  17594. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  17595. if (!isImported) {
  17596. continue;
  17597. }
  17598. }
  17599. }
  17600. }
  17601. let expression = null;
  17602. let hoisted = false;
  17603. let local = variable.getName(this.snippets.getPropertyAccess);
  17604. if (variable instanceof LocalVariable) {
  17605. for (const declaration of variable.declarations) {
  17606. if (declaration.parent instanceof FunctionDeclaration ||
  17607. (declaration instanceof ExportDefaultDeclaration &&
  17608. declaration.declaration instanceof FunctionDeclaration)) {
  17609. hoisted = true;
  17610. break;
  17611. }
  17612. }
  17613. }
  17614. else if (variable instanceof SyntheticNamedExportVariable) {
  17615. expression = local;
  17616. if (format === 'es') {
  17617. local = variable.renderName;
  17618. }
  17619. }
  17620. exports.push({
  17621. exported: exportName,
  17622. expression,
  17623. hoisted,
  17624. local
  17625. });
  17626. }
  17627. return exports;
  17628. }
  17629. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  17630. const dependencies = new Set();
  17631. const deconflictedDefault = new Set();
  17632. const deconflictedNamespace = new Set();
  17633. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  17634. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  17635. const module = variable.module;
  17636. if (module instanceof ExternalModule) {
  17637. const chunk = this.externalChunkByModule.get(module);
  17638. dependencies.add(chunk);
  17639. if (addNonNamespacesAndInteropHelpers) {
  17640. if (variable.name === 'default') {
  17641. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  17642. deconflictedDefault.add(chunk);
  17643. }
  17644. }
  17645. else if (variable.isNamespace &&
  17646. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  17647. (this.imports.has(variable) ||
  17648. !this.exportNamesByVariable.get(variable)?.every(name => name.startsWith('*')))) {
  17649. // We only need to deconflict it if the namespace is actually
  17650. // created as a variable, i.e. because it is used internally or
  17651. // because it is reexported as an object
  17652. deconflictedNamespace.add(chunk);
  17653. }
  17654. }
  17655. }
  17656. else {
  17657. const chunk = this.chunkByModule.get(module);
  17658. if (chunk !== this) {
  17659. dependencies.add(chunk);
  17660. if (addNonNamespacesAndInteropHelpers &&
  17661. chunk.exportMode === 'default' &&
  17662. variable.isNamespace) {
  17663. deconflictedNamespace.add(chunk);
  17664. }
  17665. }
  17666. }
  17667. }
  17668. }
  17669. if (addDependenciesWithoutBindings) {
  17670. for (const dependency of this.dependencies) {
  17671. dependencies.add(dependency);
  17672. }
  17673. }
  17674. return { deconflictedDefault, deconflictedNamespace, dependencies };
  17675. }
  17676. getDynamicDependencies() {
  17677. return this.getIncludedDynamicImports()
  17678. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  17679. resolvedDynamicImport.chunk ||
  17680. resolvedDynamicImport.externalChunk ||
  17681. resolvedDynamicImport.resolution)
  17682. .filter((resolution) => resolution !== this &&
  17683. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  17684. }
  17685. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  17686. if (resolution instanceof ExternalModule) {
  17687. const chunk = this.externalChunkByModule.get(resolution);
  17688. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAttributes(this.snippets)];
  17689. }
  17690. let attributes = null;
  17691. if (['es', 'cjs'].includes(this.outputOptions.format) &&
  17692. this.outputOptions.externalImportAttributes) {
  17693. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  17694. attributes =
  17695. attributesFromImportAttributes === EMPTY_OBJECT
  17696. ? true
  17697. : formatAttributes(attributesFromImportAttributes, this.snippets);
  17698. }
  17699. return [resolution || '', attributes];
  17700. }
  17701. getFallbackChunkName() {
  17702. if (this.manualChunkAlias) {
  17703. return this.manualChunkAlias;
  17704. }
  17705. if (this.dynamicName) {
  17706. return this.dynamicName;
  17707. }
  17708. if (this.fileName) {
  17709. return getAliasName(this.fileName);
  17710. }
  17711. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  17712. }
  17713. getImportSpecifiers() {
  17714. const { interop } = this.outputOptions;
  17715. const importsByDependency = new Map();
  17716. for (const variable of this.imports) {
  17717. const module = variable.module;
  17718. let dependency;
  17719. let imported;
  17720. if (module instanceof ExternalModule) {
  17721. dependency = this.externalChunkByModule.get(module);
  17722. imported = variable.name;
  17723. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  17724. return error(logUnexpectedNamedImport(module.id, imported, false));
  17725. }
  17726. }
  17727. else {
  17728. dependency = this.chunkByModule.get(module);
  17729. imported = dependency.getVariableExportName(variable);
  17730. }
  17731. getOrCreate(importsByDependency, dependency, getNewArray).push({
  17732. imported,
  17733. local: variable.getName(this.snippets.getPropertyAccess)
  17734. });
  17735. }
  17736. return importsByDependency;
  17737. }
  17738. getIncludedDynamicImports() {
  17739. if (this.includedDynamicImports) {
  17740. return this.includedDynamicImports;
  17741. }
  17742. const includedDynamicImports = [];
  17743. for (const module of this.orderedModules) {
  17744. for (const { node, resolution } of module.dynamicImports) {
  17745. if (!node.included) {
  17746. continue;
  17747. }
  17748. includedDynamicImports.push(resolution instanceof Module
  17749. ? {
  17750. chunk: this.chunkByModule.get(resolution),
  17751. externalChunk: null,
  17752. facadeChunk: this.facadeChunkByModule.get(resolution),
  17753. node,
  17754. resolution
  17755. }
  17756. : resolution instanceof ExternalModule
  17757. ? {
  17758. chunk: null,
  17759. externalChunk: this.externalChunkByModule.get(resolution),
  17760. facadeChunk: null,
  17761. node,
  17762. resolution
  17763. }
  17764. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  17765. }
  17766. }
  17767. return (this.includedDynamicImports = includedDynamicImports);
  17768. }
  17769. getPreRenderedChunkInfo() {
  17770. if (this.preRenderedChunkInfo) {
  17771. return this.preRenderedChunkInfo;
  17772. }
  17773. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  17774. return (this.preRenderedChunkInfo = {
  17775. exports: this.getExportNames(),
  17776. facadeModuleId: facadeModule && facadeModule.id,
  17777. isDynamicEntry: dynamicEntryModules.length > 0,
  17778. isEntry: !!facadeModule?.info.isEntry,
  17779. isImplicitEntry: implicitEntryModules.length > 0,
  17780. moduleIds: orderedModules.map(({ id }) => id),
  17781. name: this.getChunkName(),
  17782. type: 'chunk'
  17783. });
  17784. }
  17785. getPreserveModulesChunkNameFromModule(module) {
  17786. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  17787. if (predefinedChunkName)
  17788. return predefinedChunkName;
  17789. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  17790. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  17791. const extensionName = extname(sanitizedId);
  17792. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  17793. ? sanitizedId.slice(0, -extensionName.length)
  17794. : sanitizedId;
  17795. if (isAbsolute$1(idWithoutExtension)) {
  17796. if (preserveModulesRoot && resolve$1(idWithoutExtension).startsWith(preserveModulesRoot)) {
  17797. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  17798. }
  17799. else {
  17800. // handle edge case in Windows
  17801. if (this.inputBase === '/' && !idWithoutExtension.startsWith('/')) {
  17802. return relative$1(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  17803. }
  17804. return relative$1(this.inputBase, idWithoutExtension);
  17805. }
  17806. }
  17807. else {
  17808. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + basename(idWithoutExtension));
  17809. }
  17810. }
  17811. getReexportSpecifiers() {
  17812. const { externalLiveBindings, interop } = this.outputOptions;
  17813. const reexportSpecifiers = new Map();
  17814. for (let exportName of this.getExportNames()) {
  17815. let dependency;
  17816. let imported;
  17817. let needsLiveBinding = false;
  17818. if (exportName[0] === '*') {
  17819. const id = exportName.slice(1);
  17820. if (interop(id) === 'defaultOnly') {
  17821. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  17822. }
  17823. needsLiveBinding = externalLiveBindings;
  17824. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  17825. imported = exportName = '*';
  17826. }
  17827. else {
  17828. const variable = this.exportsByName.get(exportName);
  17829. if (variable instanceof SyntheticNamedExportVariable)
  17830. continue;
  17831. const module = variable.module;
  17832. if (module instanceof Module) {
  17833. dependency = this.chunkByModule.get(module);
  17834. if (dependency === this)
  17835. continue;
  17836. imported = dependency.getVariableExportName(variable);
  17837. needsLiveBinding = variable.isReassigned;
  17838. }
  17839. else {
  17840. dependency = this.externalChunkByModule.get(module);
  17841. imported = variable.name;
  17842. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  17843. return error(logUnexpectedNamedImport(module.id, imported, true));
  17844. }
  17845. needsLiveBinding =
  17846. externalLiveBindings &&
  17847. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  17848. }
  17849. }
  17850. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  17851. imported,
  17852. needsLiveBinding,
  17853. reexported: exportName
  17854. });
  17855. }
  17856. return reexportSpecifiers;
  17857. }
  17858. getReferencedFiles() {
  17859. const referencedFiles = new Set();
  17860. for (const module of this.orderedModules) {
  17861. for (const meta of module.importMetas) {
  17862. const fileName = meta.getReferencedFileName(this.pluginDriver);
  17863. if (fileName) {
  17864. referencedFiles.add(fileName);
  17865. }
  17866. }
  17867. }
  17868. return [...referencedFiles];
  17869. }
  17870. getRenderedDependencies() {
  17871. if (this.renderedDependencies) {
  17872. return this.renderedDependencies;
  17873. }
  17874. const importSpecifiers = this.getImportSpecifiers();
  17875. const reexportSpecifiers = this.getReexportSpecifiers();
  17876. const renderedDependencies = new Map();
  17877. const fileName = this.getFileName();
  17878. for (const dependency of this.dependencies) {
  17879. const imports = importSpecifiers.get(dependency) || null;
  17880. const reexports = reexportSpecifiers.get(dependency) || null;
  17881. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  17882. const importPath = dependency.getImportPath(fileName);
  17883. renderedDependencies.set(dependency, {
  17884. attributes: dependency instanceof ExternalChunk
  17885. ? dependency.getImportAttributes(this.snippets)
  17886. : null,
  17887. defaultVariableName: dependency.defaultVariableName,
  17888. globalName: dependency instanceof ExternalChunk &&
  17889. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  17890. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  17891. importPath,
  17892. imports,
  17893. isChunk: dependency instanceof Chunk,
  17894. name: dependency.variableName,
  17895. namedExportsMode,
  17896. namespaceVariableName: dependency.namespaceVariableName,
  17897. reexports
  17898. });
  17899. }
  17900. return (this.renderedDependencies = renderedDependencies);
  17901. }
  17902. inlineChunkDependencies(chunk) {
  17903. for (const dep of chunk.dependencies) {
  17904. if (this.dependencies.has(dep))
  17905. continue;
  17906. this.dependencies.add(dep);
  17907. if (dep instanceof Chunk) {
  17908. this.inlineChunkDependencies(dep);
  17909. }
  17910. }
  17911. }
  17912. // This method changes properties on the AST before rendering and must not be async
  17913. renderModules(fileName) {
  17914. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  17915. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  17916. const { _, cnst, n } = snippets;
  17917. this.setDynamicImportResolutions(fileName);
  17918. this.setImportMetaResolutions(fileName);
  17919. this.setIdentifierRenderResolutions();
  17920. const magicString = new Bundle$1({ separator: `${n}${n}` });
  17921. const indent = getIndentString(orderedModules, outputOptions);
  17922. const usedModules = [];
  17923. let hoistedSource = '';
  17924. const accessedGlobals = new Set();
  17925. const renderedModuleSources = new Map();
  17926. const renderOptions = {
  17927. accessedDocumentCurrentScript: false,
  17928. exportNamesByVariable,
  17929. format,
  17930. freeze,
  17931. importAttributesKey,
  17932. indent,
  17933. pluginDriver,
  17934. snippets,
  17935. symbols,
  17936. useOriginalName: null
  17937. };
  17938. let usesTopLevelAwait = false;
  17939. for (const module of orderedModules) {
  17940. let renderedLength = 0;
  17941. let source;
  17942. if (module.isIncluded() || includedNamespaces.has(module)) {
  17943. const rendered = module.render(renderOptions);
  17944. if (!renderOptions.accessedDocumentCurrentScript &&
  17945. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  17946. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  17947. }
  17948. renderOptions.accessedDocumentCurrentScript = false;
  17949. ({ source } = rendered);
  17950. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  17951. renderedLength = source.length();
  17952. if (renderedLength) {
  17953. if (compact && source.lastLine().includes('//'))
  17954. source.append('\n');
  17955. renderedModuleSources.set(module, source);
  17956. magicString.addSource(source);
  17957. usedModules.push(module);
  17958. }
  17959. const namespace = module.namespace;
  17960. if (includedNamespaces.has(module)) {
  17961. const rendered = namespace.renderBlock(renderOptions);
  17962. if (namespace.renderFirst())
  17963. hoistedSource += n + rendered;
  17964. else
  17965. magicString.addSource(new MagicString(rendered));
  17966. }
  17967. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  17968. if (accessedGlobalVariables) {
  17969. for (const name of accessedGlobalVariables) {
  17970. accessedGlobals.add(name);
  17971. }
  17972. }
  17973. }
  17974. const { renderedExports, removedExports } = module.getRenderedExports();
  17975. renderedModules[module.id] = {
  17976. get code() {
  17977. return source?.toString() ?? null;
  17978. },
  17979. originalLength: module.originalCode.length,
  17980. removedExports,
  17981. renderedExports,
  17982. renderedLength
  17983. };
  17984. }
  17985. if (hoistedSource)
  17986. magicString.prepend(hoistedSource + n + n);
  17987. if (this.needsExportsShim) {
  17988. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  17989. }
  17990. const renderedSource = compact ? magicString : magicString.trim();
  17991. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  17992. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  17993. }
  17994. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  17995. }
  17996. setDynamicImportResolutions(fileName) {
  17997. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  17998. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  17999. if (resolvedDynamicImport.chunk) {
  18000. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  18001. if (chunk === this) {
  18002. node.setInternalResolution(resolution.namespace);
  18003. }
  18004. else {
  18005. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null, this, facadeChunk || chunk);
  18006. }
  18007. }
  18008. else {
  18009. const { node, resolution } = resolvedDynamicImport;
  18010. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  18011. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes, this, null);
  18012. }
  18013. }
  18014. }
  18015. setIdentifierRenderResolutions() {
  18016. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  18017. const syntheticExports = new Set();
  18018. for (const exportName of this.getExportNames()) {
  18019. const exportVariable = this.exportsByName.get(exportName);
  18020. if (format !== 'es' &&
  18021. format !== 'system' &&
  18022. exportVariable.isReassigned &&
  18023. !exportVariable.isId) {
  18024. exportVariable.setRenderNames('exports', exportName);
  18025. }
  18026. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  18027. syntheticExports.add(exportVariable);
  18028. }
  18029. else {
  18030. exportVariable.setRenderNames(null, null);
  18031. }
  18032. }
  18033. for (const module of this.orderedModules) {
  18034. if (module.needsExportShim) {
  18035. this.needsExportsShim = true;
  18036. break;
  18037. }
  18038. }
  18039. const usedNames = new Set(['Object', 'Promise']);
  18040. if (this.needsExportsShim) {
  18041. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  18042. }
  18043. if (symbols) {
  18044. usedNames.add('Symbol');
  18045. }
  18046. switch (format) {
  18047. case 'system': {
  18048. usedNames.add('module').add('exports');
  18049. break;
  18050. }
  18051. case 'es': {
  18052. break;
  18053. }
  18054. case 'cjs': {
  18055. usedNames.add('module').add('require').add('__filename').add('__dirname');
  18056. }
  18057. // fallthrough
  18058. default: {
  18059. usedNames.add('exports');
  18060. for (const helper of HELPER_NAMES) {
  18061. usedNames.add(helper);
  18062. }
  18063. }
  18064. }
  18065. deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, preserveModules, externalLiveBindings, this.chunkByModule, this.externalChunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
  18066. }
  18067. setImportMetaResolutions(fileName) {
  18068. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  18069. for (const module of orderedModules) {
  18070. for (const importMeta of module.importMetas) {
  18071. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  18072. }
  18073. if (includedNamespaces.has(module)) {
  18074. module.namespace.prepare(accessedGlobalsByScope);
  18075. }
  18076. }
  18077. }
  18078. setUpChunkImportsAndExportsForModule(module) {
  18079. const moduleImports = new Set(module.includedImports);
  18080. // when we are not preserving modules, we need to make all namespace variables available for
  18081. // rendering the namespace object
  18082. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  18083. const memberVariables = module.namespace.getMemberVariables();
  18084. for (const variable of Object.values(memberVariables)) {
  18085. if (variable.included) {
  18086. moduleImports.add(variable);
  18087. }
  18088. }
  18089. }
  18090. for (let variable of moduleImports) {
  18091. if (variable instanceof ExportDefaultVariable) {
  18092. variable = variable.getOriginalVariable();
  18093. }
  18094. if (variable instanceof SyntheticNamedExportVariable) {
  18095. variable = variable.getBaseVariable();
  18096. }
  18097. const chunk = this.chunkByModule.get(variable.module);
  18098. if (chunk !== this) {
  18099. this.imports.add(variable);
  18100. if (variable.module instanceof Module) {
  18101. this.checkCircularDependencyImport(variable, module);
  18102. // When preserving modules, we do not create namespace objects but directly
  18103. // use the actual namespaces, which would be broken by this logic.
  18104. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  18105. chunk.exports.add(variable);
  18106. }
  18107. }
  18108. }
  18109. }
  18110. if (this.includedNamespaces.has(module) ||
  18111. (module.info.isEntry && module.preserveSignature !== false) ||
  18112. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  18113. this.ensureReexportsAreAvailableForModule(module);
  18114. }
  18115. for (const { node, resolution } of module.dynamicImports) {
  18116. if (node.included &&
  18117. resolution instanceof Module &&
  18118. this.chunkByModule.get(resolution) === this &&
  18119. !this.includedNamespaces.has(resolution)) {
  18120. this.includedNamespaces.add(resolution);
  18121. this.ensureReexportsAreAvailableForModule(resolution);
  18122. }
  18123. }
  18124. }
  18125. }
  18126. function getChunkNameFromModule(module) {
  18127. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  18128. }
  18129. function getPredefinedChunkNameFromModule(module) {
  18130. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  18131. }
  18132. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  18133. const importedBindingsPerDependency = {};
  18134. for (const [dependency, declaration] of renderedDependencies) {
  18135. const specifiers = new Set();
  18136. if (declaration.imports) {
  18137. for (const { imported } of declaration.imports) {
  18138. specifiers.add(imported);
  18139. }
  18140. }
  18141. if (declaration.reexports) {
  18142. for (const { imported } of declaration.reexports) {
  18143. specifiers.add(imported);
  18144. }
  18145. }
  18146. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  18147. }
  18148. return importedBindingsPerDependency;
  18149. }
  18150. const QUERY_HASH_REGEX = /[#?]/;
  18151. const resolveFileName = (dependency) => dependency.getFileName();
  18152. /**
  18153. * Concatenate a number of iterables to a new iterable without fully evaluating
  18154. * their iterators. Useful when e.g. working with large sets or lists and when
  18155. * there is a chance that the iterators will not be fully exhausted.
  18156. */
  18157. function* concatLazy(iterables) {
  18158. for (const iterable of iterables) {
  18159. yield* iterable;
  18160. }
  18161. }
  18162. /**
  18163. * At its core, the algorithm first starts from each static or dynamic entry
  18164. * point and then assigns that entry point to all modules than can be reached
  18165. * via static imports. We call this the *dependent entry points* of that
  18166. * module.
  18167. *
  18168. * Then we group all modules with the same dependent entry points into chunks
  18169. * as those modules will always be loaded together.
  18170. *
  18171. * One non-trivial optimization we can apply is that dynamic entries are
  18172. * different from static entries in so far as when a dynamic import occurs,
  18173. * some modules are already in memory. If some of these modules are also
  18174. * dependencies of the dynamic entry, then it does not make sense to create a
  18175. * separate chunk for them. Instead, the dynamic import target can load them
  18176. * from the importing chunk.
  18177. *
  18178. * With regard to chunking, if B is implicitly loaded after A, then this can be
  18179. * handled the same way as if there was a dynamic import A => B.
  18180. *
  18181. * Example:
  18182. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  18183. * Then the initial algorithm would assign A into the A chunk, C into the C
  18184. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  18185. * points A and C.
  18186. * However we know that C can only be loaded from A, so A and its dependency B
  18187. * must already be in memory when C is loaded. So it is enough to create only
  18188. * two chunks A containing [AB] and C containing [C].
  18189. *
  18190. * So we do not assign the dynamic entry C as dependent entry point to modules
  18191. * that are already loaded.
  18192. *
  18193. * In a more complex example, let us assume that we have entry points X and Y.
  18194. * Further, let us assume
  18195. * X -> A, X -> B, X -> C,
  18196. * Y -> A, Y -> B,
  18197. * A => D,
  18198. * D -> B, D -> C
  18199. * So without dynamic import optimization, the dependent entry points are
  18200. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  18201. * chunks.
  18202. *
  18203. * Now D is loaded only after A is loaded. But A is loaded if either X is
  18204. * loaded or Y is loaded. So the modules that are already in memory when D is
  18205. * loaded are the intersection of all modules that X depends on with all
  18206. * modules that Y depends on, which in this case are the modules A and B.
  18207. * We could also say they are all modules that have both X and Y as dependent
  18208. * entry points.
  18209. *
  18210. * So we can remove D as dependent entry point from A and B, which means they
  18211. * both now have only XY as dependent entry points and can be merged into the
  18212. * same chunk.
  18213. *
  18214. * Now let us extend this to the most general case where we have several
  18215. * dynamic importers for one dynamic entry point.
  18216. *
  18217. * In the most general form, it works like this:
  18218. * For each dynamic entry point, we have a number of dynamic importers, which
  18219. * are the modules importing it. Using the previous ideas, we can determine
  18220. * the modules already in memory for each dynamic importer by looking for all
  18221. * modules that have all the dependent entry points of the dynamic importer as
  18222. * dependent entry points.
  18223. * So the modules that are guaranteed to be in memory when the dynamic entry
  18224. * point is loaded are the intersection of the modules already in memory for
  18225. * each dynamic importer.
  18226. *
  18227. * Assuming that A => D and B => D and A has dependent entry points XY and B
  18228. * has dependent entry points YZ, then the modules guaranteed to be in memory
  18229. * are all modules that have at least XYZ as dependent entry points.
  18230. * We call XYZ the *dynamically dependent entry points* of D.
  18231. *
  18232. * Now there is one last case to consider: If one of the dynamically dependent
  18233. * entries is itself a dynamic entry, then any module is in memory that either
  18234. * is a dependency of that dynamic entry or again has the dynamic dependent
  18235. * entries of that dynamic entry as dependent entry points.
  18236. *
  18237. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  18238. * complexity with regard to dynamic entries that blew up for very large
  18239. * projects.
  18240. *
  18241. * If we have an efficient way to do Set operations, an alternative approach
  18242. * would be to instead collect already loaded modules per dynamic entry. And as
  18243. * all chunks from the initial grouping would behave the same, we can instead
  18244. * collect already loaded chunks for a performance improvement.
  18245. *
  18246. * To do that efficiently, need
  18247. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  18248. * imports that can be triggered by a dynamic entry
  18249. * - a Map of static dependencies per entry
  18250. * - a Map of already loaded chunks per entry that we initially populate with
  18251. * empty Sets for static entries and Sets containing all entries for dynamic
  18252. * entries
  18253. *
  18254. * For efficient operations, we assign each entry a numerical index and
  18255. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  18256. * bit index. Then the last two maps can be represented as arrays of BigInt
  18257. * values.
  18258. *
  18259. * Then we iterate through each dynamic entry. We set the already loaded modules
  18260. * to the intersection of the previously already loaded modules with the union
  18261. * of the already loaded modules of that chunk with its static dependencies.
  18262. *
  18263. * If the already loaded modules changed, then we use the Map of dynamic imports
  18264. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  18265. * them back into the iteration. As an additional optimization, we note for
  18266. * each dynamic entry which dynamic dependent entries have changed and only
  18267. * intersect those entries again on subsequent interations.
  18268. *
  18269. * Then we remove the dynamic entries from the list of dependent entries for
  18270. * those chunks that are already loaded for that dynamic entry and create
  18271. * another round of chunks.
  18272. */
  18273. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  18274. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  18275. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries);
  18276. // Each chunk is identified by its position in this array
  18277. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  18278. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  18279. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18280. // If we no longer want this, we should make a copy here.
  18281. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  18282. const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntries);
  18283. // This mutates the dependentEntries in chunkAtoms
  18284. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
  18285. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  18286. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  18287. alias: null,
  18288. modules
  18289. })));
  18290. return chunkDefinitions;
  18291. }
  18292. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  18293. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  18294. const manualChunkModulesByAlias = Object.create(null);
  18295. for (const [entry, alias] of manualChunkAliasByEntry) {
  18296. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  18297. }
  18298. const manualChunks = Object.entries(manualChunkModulesByAlias);
  18299. const chunkDefinitions = new Array(manualChunks.length);
  18300. let index = 0;
  18301. for (const [alias, modules] of manualChunks) {
  18302. chunkDefinitions[index++] = { alias, modules };
  18303. }
  18304. return { chunkDefinitions, modulesInManualChunks };
  18305. }
  18306. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  18307. const modulesToHandle = new Set([entry]);
  18308. for (const module of modulesToHandle) {
  18309. modulesInManualChunks.add(module);
  18310. manualChunkModules.push(module);
  18311. for (const dependency of module.dependencies) {
  18312. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  18313. modulesToHandle.add(dependency);
  18314. }
  18315. }
  18316. }
  18317. }
  18318. function analyzeModuleGraph(entries) {
  18319. const dynamicEntryModules = new Set();
  18320. const awaitedDynamicEntryModules = new Set();
  18321. const dependentEntriesByModule = new Map();
  18322. const allEntriesSet = new Set(entries);
  18323. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18324. const awaitedDynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18325. let entryIndex = 0;
  18326. for (const currentEntry of allEntriesSet) {
  18327. const dynamicImportsForCurrentEntry = new Set();
  18328. const awaitedDynamicImportsForCurrentEntry = new Set();
  18329. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  18330. awaitedDynamicImportModulesByEntry[entryIndex] = awaitedDynamicImportsForCurrentEntry;
  18331. const modulesToHandle = new Set([currentEntry]);
  18332. for (const module of modulesToHandle) {
  18333. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  18334. for (const dependency of module.getDependenciesToBeIncluded()) {
  18335. if (!(dependency instanceof ExternalModule)) {
  18336. modulesToHandle.add(dependency);
  18337. }
  18338. }
  18339. for (const { resolution } of module.dynamicImports) {
  18340. if (resolution instanceof Module &&
  18341. resolution.includedDynamicImporters.length > 0 &&
  18342. !allEntriesSet.has(resolution)) {
  18343. dynamicEntryModules.add(resolution);
  18344. allEntriesSet.add(resolution);
  18345. dynamicImportsForCurrentEntry.add(resolution);
  18346. if (resolution.includedDirectTopLevelAwaitingDynamicImporters.has(currentEntry)) {
  18347. awaitedDynamicEntryModules.add(resolution);
  18348. awaitedDynamicImportsForCurrentEntry.add(resolution);
  18349. }
  18350. }
  18351. }
  18352. for (const dependency of module.implicitlyLoadedBefore) {
  18353. if (!allEntriesSet.has(dependency)) {
  18354. dynamicEntryModules.add(dependency);
  18355. allEntriesSet.add(dependency);
  18356. }
  18357. }
  18358. }
  18359. entryIndex++;
  18360. }
  18361. const allEntries = [...allEntriesSet];
  18362. const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
  18363. return {
  18364. allEntries,
  18365. awaitedDynamicImportsByEntry,
  18366. dependentEntriesByModule,
  18367. dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDirectTopLevelAwaitingDynamicImporters),
  18368. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDynamicImporters),
  18369. dynamicImportsByEntry
  18370. };
  18371. }
  18372. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
  18373. const entryIndexByModule = new Map();
  18374. const dynamicEntries = new Set();
  18375. const awaitedDynamicEntries = new Set();
  18376. for (const [entryIndex, entry] of allEntries.entries()) {
  18377. entryIndexByModule.set(entry, entryIndex);
  18378. if (dynamicEntryModules.has(entry)) {
  18379. dynamicEntries.add(entryIndex);
  18380. }
  18381. if (awaitedDynamicEntryModules.has(entry)) {
  18382. awaitedDynamicEntries.add(entryIndex);
  18383. }
  18384. }
  18385. const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
  18386. const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
  18387. return {
  18388. awaitedDynamicEntries,
  18389. awaitedDynamicImportsByEntry,
  18390. dynamicEntries,
  18391. dynamicImportsByEntry
  18392. };
  18393. }
  18394. function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule) {
  18395. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  18396. let index = 0;
  18397. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  18398. const dynamicImports = new Set();
  18399. for (const dynamicEntry of dynamicImportModules) {
  18400. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  18401. }
  18402. dynamicImportsByEntry[index++] = dynamicImports;
  18403. }
  18404. return dynamicImportsByEntry;
  18405. }
  18406. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, getDynamicImporters) {
  18407. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  18408. for (const dynamicEntryIndex of dynamicEntries) {
  18409. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  18410. const dynamicEntry = allEntries[dynamicEntryIndex];
  18411. for (const importer of concatLazy([
  18412. getDynamicImporters(dynamicEntry),
  18413. dynamicEntry.implicitlyLoadedAfter
  18414. ])) {
  18415. for (const entry of dependentEntriesByModule.get(importer)) {
  18416. dynamicallyDependentEntries.add(entry);
  18417. }
  18418. }
  18419. }
  18420. return dynamicallyDependentEntriesByDynamicEntry;
  18421. }
  18422. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  18423. const chunkModules = Object.create(null);
  18424. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  18425. let chunkSignature = 0n;
  18426. for (const entryIndex of dependentEntries) {
  18427. chunkSignature |= 1n << BigInt(entryIndex);
  18428. }
  18429. (chunkModules[String(chunkSignature)] ||= {
  18430. dependentEntries: new Set(dependentEntries),
  18431. modules: []
  18432. }).modules.push(...modules);
  18433. }
  18434. return Object.values(chunkModules);
  18435. }
  18436. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  18437. for (const [module, dependentEntries] of dependentEntriesByModule) {
  18438. if (!modulesInManualChunks.has(module)) {
  18439. yield { dependentEntries, modules: [module] };
  18440. }
  18441. }
  18442. }
  18443. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  18444. // The indices correspond to the indices in allEntries. The atoms correspond
  18445. // to bits in the bigint values where chunk 0 is the lowest bit.
  18446. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  18447. // This toggles the bits for each atom that is a dependency of an entry
  18448. let atomMask = 1n;
  18449. for (const { dependentEntries } of chunkAtoms) {
  18450. for (const entryIndex of dependentEntries) {
  18451. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  18452. }
  18453. atomMask <<= 1n;
  18454. }
  18455. return staticDependencyAtomsByEntry;
  18456. }
  18457. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18458. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  18459. // Dynamic entries have all atoms as already loaded initially because we then
  18460. // intersect with the static dependency atoms of all dynamic importers.
  18461. // Static entries cannot have already loaded atoms.
  18462. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  18463. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  18464. // We delete here so that they can be added again if necessary to be handled
  18465. // again by the loop
  18466. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  18467. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  18468. let updatedLoadedAtoms = knownLoadedAtoms;
  18469. for (const entryIndex of dynamicallyDependentEntries) {
  18470. updatedLoadedAtoms &=
  18471. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18472. }
  18473. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  18474. // updated again
  18475. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  18476. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  18477. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  18478. // If this adds an entry that was deleted before, it will be handled
  18479. // again. This is the reason why we delete every entry from this map
  18480. // that we processed.
  18481. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  18482. }
  18483. }
  18484. }
  18485. return alreadyLoadedAtomsByEntry;
  18486. }
  18487. /**
  18488. * This removes all unnecessary dynamic entries from the dependentEntries in its
  18489. * first argument if a chunk is already loaded without that entry.
  18490. */
  18491. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry) {
  18492. // Remove entries from dependent entries if a chunk is already loaded without
  18493. // that entry. Do not remove already loaded atoms where all dynamic imports
  18494. // are awaited to avoid cycles in the output.
  18495. let chunkMask = 1n;
  18496. for (const { dependentEntries } of chunkAtoms) {
  18497. for (const entryIndex of dependentEntries) {
  18498. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask &&
  18499. (awaitedAlreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === 0n) {
  18500. dependentEntries.delete(entryIndex);
  18501. }
  18502. }
  18503. chunkMask <<= 1n;
  18504. }
  18505. }
  18506. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  18507. const chunksBySignature = Object.create(null);
  18508. const chunkByModule = new Map();
  18509. const sizeByAtom = new Array(chunkAtoms.length);
  18510. let sideEffectAtoms = 0n;
  18511. let atomMask = 1n;
  18512. let index = 0;
  18513. for (const { dependentEntries, modules } of chunkAtoms) {
  18514. let chunkSignature = 0n;
  18515. let correlatedAtoms = -1n;
  18516. for (const entryIndex of dependentEntries) {
  18517. chunkSignature |= 1n << BigInt(entryIndex);
  18518. // Correlated atoms are the atoms that are guaranteed to be loaded as
  18519. // well when a given atom is loaded. It is the intersection of the already
  18520. // loaded modules of each chunk merged with its static dependencies.
  18521. correlatedAtoms &=
  18522. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18523. }
  18524. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  18525. containedAtoms: 0n,
  18526. correlatedAtoms,
  18527. dependencies: new Set(),
  18528. dependentChunks: new Set(),
  18529. dependentEntries: new Set(dependentEntries),
  18530. modules: [],
  18531. pure: true,
  18532. size: 0
  18533. });
  18534. let atomSize = 0;
  18535. let pure = true;
  18536. for (const module of modules) {
  18537. chunkByModule.set(module, chunk);
  18538. // Unfortunately, we cannot take tree-shaking into account here because
  18539. // rendering did not happen yet, but we can detect empty modules
  18540. if (module.isIncluded()) {
  18541. pure &&= !module.hasEffects();
  18542. // we use a trivial size for the default minChunkSize to improve
  18543. // performance
  18544. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  18545. }
  18546. }
  18547. if (!pure) {
  18548. sideEffectAtoms |= atomMask;
  18549. }
  18550. sizeByAtom[index++] = atomSize;
  18551. chunk.containedAtoms |= atomMask;
  18552. chunk.modules.push(...modules);
  18553. chunk.pure &&= pure;
  18554. chunk.size += atomSize;
  18555. atomMask <<= 1n;
  18556. }
  18557. const chunks = Object.values(chunksBySignature);
  18558. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  18559. return { chunks, sideEffectAtoms, sizeByAtom };
  18560. }
  18561. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  18562. const signatureByExternalModule = new Map();
  18563. let externalSideEffectAtoms = 0n;
  18564. for (const chunk of chunks) {
  18565. const { dependencies, modules } = chunk;
  18566. for (const module of modules) {
  18567. for (const dependency of module.getDependenciesToBeIncluded()) {
  18568. if (dependency instanceof ExternalModule) {
  18569. if (dependency.info.moduleSideEffects) {
  18570. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  18571. const signature = nextAvailableAtomMask;
  18572. nextAvailableAtomMask <<= 1n;
  18573. externalSideEffectAtoms |= signature;
  18574. return signature;
  18575. });
  18576. chunk.containedAtoms |= signature;
  18577. chunk.correlatedAtoms |= signature;
  18578. }
  18579. }
  18580. else {
  18581. const dependencyChunk = chunkByModule.get(dependency);
  18582. if (dependencyChunk && dependencyChunk !== chunk) {
  18583. dependencies.add(dependencyChunk);
  18584. dependencyChunk.dependentChunks.add(chunk);
  18585. }
  18586. }
  18587. }
  18588. }
  18589. }
  18590. return externalSideEffectAtoms;
  18591. }
  18592. /**
  18593. * This function tries to get rid of small chunks by merging them with other
  18594. * chunks.
  18595. *
  18596. * We can only merge chunks safely if after the merge, loading any entry point
  18597. * in any allowed order will not trigger side effects that should not have been
  18598. * triggered. While side effects are usually things like global function calls,
  18599. * global variable mutations or potentially thrown errors, details do not
  18600. * matter here, and we just discern chunks without side effects (pure chunks)
  18601. * from other chunks.
  18602. *
  18603. * As a first step, we assign each pre-generated chunk with side effects a
  18604. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  18605. *
  18606. * Now to determine the side effects of loading a chunk, one also has to take
  18607. * the side effects of its dependencies into account. So if A depends on B
  18608. * (A -> B) and both have side effects, loading A triggers effects AB.
  18609. *
  18610. * Now from the previous step we know that each chunk is uniquely determine by
  18611. * the entry points that depend on it and cause it to load, which we will call
  18612. * its dependent entry points.
  18613. *
  18614. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  18615. * Starting from that idea, we can determine a set of chunksand thus a set
  18616. * of side effectsthat must have been triggered if a certain chunk has been
  18617. * loaded. Basically, it is the intersection of all chunks loaded by the
  18618. * dependent entry points of a given chunk. We call the corresponding side
  18619. * effects the correlated side effects of that chunk.
  18620. *
  18621. * Example:
  18622. * X -> ABC, Y -> ADE, A-> F, B -> D
  18623. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  18624. * The intersection is ADF. So we know that when A is loaded, D and F must also
  18625. * be in memory even though neither D nor A is a dependency of the other.
  18626. * If all have side effects, we call ADF the correlated side effects of A. The
  18627. * correlated side effects need to remain constant when merging chunks.
  18628. *
  18629. * In contrast, we have the dependency side effects of A, which represents
  18630. * the side effects we trigger if we directly load A. In this example, the
  18631. * dependency side effects are AF.
  18632. * For entry chunks, dependency and correlated side effects are the same.
  18633. *
  18634. * With these concepts, merging chunks is allowed if the correlated side
  18635. * effects of each entry do not change. Thus, we are allowed to merge two
  18636. * chunks if
  18637. *
  18638. * a) the dependency side effects of each chunk are a subset of the correlated
  18639. * side effects of the other chunk, so no additional side effects are
  18640. * triggered for any entry, or
  18641. * b) The dependent entry points of chunk A are a subset of the dependent entry
  18642. * points of chunk B while the dependency side effects of A are a subset of
  18643. * the correlated side effects of B. Because in that scenario, whenever A is
  18644. * loaded, B is loaded as well. But there are cases when B is loaded where A
  18645. * is not loaded. So if we merge the chunks, all dependency side effects of
  18646. * A will be added to the correlated side effects of B, and as the latter is
  18647. * not allowed to change, the former need to be a subset of the latter.
  18648. *
  18649. * Another consideration when merging small chunks into other chunks is to
  18650. * avoid
  18651. * that too much additional code is loaded. This is achieved when the dependent
  18652. * entries of the small chunk are a subset of the dependent entries of the
  18653. * other
  18654. * chunk. Because then when the small chunk is loaded, the other chunk was
  18655. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  18656. * additional size of the small chunk is loaded unnecessarily.
  18657. *
  18658. * So the algorithm performs merges in two passes:
  18659. *
  18660. * 1. First we try to merge small chunks A only into other chunks B if the
  18661. * dependent entries of A are a subset of the dependent entries of B and the
  18662. * dependency side effects of A are a subset of the correlated side effects
  18663. * of B.
  18664. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  18665. * following the rule (a), starting with the smallest chunks to look for
  18666. * possible merge targets.
  18667. */
  18668. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  18669. timeStart('optimize chunks', 3);
  18670. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  18671. if (!chunkPartition) {
  18672. timeEnd('optimize chunks', 3);
  18673. return chunks; // the actual modules
  18674. }
  18675. if (minChunkSize > 1) {
  18676. log('info', logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  18677. }
  18678. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  18679. if (minChunkSize > 1) {
  18680. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  18681. }
  18682. timeEnd('optimize chunks', 3);
  18683. return [...chunkPartition.small, ...chunkPartition.big];
  18684. }
  18685. function getPartitionedChunks(chunks, minChunkSize) {
  18686. const smallChunks = [];
  18687. const bigChunks = [];
  18688. for (const chunk of chunks) {
  18689. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  18690. }
  18691. if (smallChunks.length === 0) {
  18692. return null;
  18693. }
  18694. smallChunks.sort(compareChunkSize);
  18695. bigChunks.sort(compareChunkSize);
  18696. return {
  18697. big: new Set(bigChunks),
  18698. small: new Set(smallChunks)
  18699. };
  18700. }
  18701. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  18702. return sizeA - sizeB;
  18703. }
  18704. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  18705. const { small } = chunkPartition;
  18706. for (const mergedChunk of small) {
  18707. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  18708. // In the default case, we do not accept size increases
  18709. minChunkSize <= 1 ? 1 : Infinity);
  18710. if (bestTargetChunk) {
  18711. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  18712. small.delete(mergedChunk);
  18713. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  18714. bestTargetChunk.modules.push(...modules);
  18715. bestTargetChunk.size += size;
  18716. bestTargetChunk.pure &&= pure;
  18717. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  18718. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  18719. bestTargetChunk.containedAtoms |= containedAtoms;
  18720. for (const entry of mergedChunk.dependentEntries) {
  18721. dependentEntries.add(entry);
  18722. }
  18723. for (const dependency of mergedChunk.dependencies) {
  18724. dependencies.add(dependency);
  18725. dependency.dependentChunks.delete(mergedChunk);
  18726. dependency.dependentChunks.add(bestTargetChunk);
  18727. }
  18728. for (const dependentChunk of mergedChunk.dependentChunks) {
  18729. dependentChunks.add(dependentChunk);
  18730. dependentChunk.dependencies.delete(mergedChunk);
  18731. dependentChunk.dependencies.add(bestTargetChunk);
  18732. }
  18733. dependencies.delete(bestTargetChunk);
  18734. dependentChunks.delete(bestTargetChunk);
  18735. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  18736. }
  18737. }
  18738. }
  18739. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  18740. let bestTargetChunk = null;
  18741. // In the default case, we do not accept size increases
  18742. for (const targetChunk of concatLazy([small, big])) {
  18743. if (mergedChunk === targetChunk)
  18744. continue;
  18745. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  18746. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  18747. bestTargetChunk = targetChunk;
  18748. if (additionalSizeAfterMerge === 0)
  18749. break;
  18750. smallestAdditionalSize = additionalSizeAfterMerge;
  18751. }
  18752. }
  18753. return bestTargetChunk;
  18754. }
  18755. /**
  18756. * Determine the additional unused code size that would be added by merging the
  18757. * two chunks. This is not an exact measurement but rather an upper bound. If
  18758. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  18759. * is returned.
  18760. * Merging will not produce cycles if none of the direct non-merged
  18761. * dependencies of a chunk have the other chunk as a transitive dependency.
  18762. */
  18763. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  18764. // The maximum additional unused code size allowed to be added by the merge,
  18765. // taking dependencies into account, needs to be below this number
  18766. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18767. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  18768. return firstSize < currentAdditionalSize
  18769. ? firstSize +
  18770. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  18771. : Infinity;
  18772. }
  18773. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18774. const { correlatedAtoms } = dependencyChunk;
  18775. let dependencyAtoms = dependentChunk.containedAtoms;
  18776. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  18777. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  18778. return Infinity;
  18779. }
  18780. const chunksToCheck = new Set(dependentChunk.dependencies);
  18781. for (const { dependencies, containedAtoms } of chunksToCheck) {
  18782. dependencyAtoms |= containedAtoms;
  18783. const containedSideEffects = containedAtoms & sideEffectAtoms;
  18784. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  18785. return Infinity;
  18786. }
  18787. for (const dependency of dependencies) {
  18788. if (dependency === dependencyChunk) {
  18789. return Infinity;
  18790. }
  18791. chunksToCheck.add(dependency);
  18792. }
  18793. }
  18794. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  18795. }
  18796. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  18797. let size = 0;
  18798. let atomIndex = 0;
  18799. let atomSignature = 1n;
  18800. const { length } = sizeByAtom;
  18801. for (; atomIndex < length; atomIndex++) {
  18802. if ((atoms & atomSignature) === atomSignature) {
  18803. size += sizeByAtom[atomIndex];
  18804. }
  18805. atomSignature <<= 1n;
  18806. if (size >= currentAdditionalSize) {
  18807. return Infinity;
  18808. }
  18809. }
  18810. return size;
  18811. }
  18812. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  18813. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  18814. }
  18815. // ported from https://github.com/substack/node-commondir
  18816. function commondir(files) {
  18817. if (files.length === 0)
  18818. return '/';
  18819. if (files.length === 1)
  18820. return dirname(files[0]);
  18821. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  18822. const pathSegments = file.split(/\/+|\\+/);
  18823. let index;
  18824. for (index = 0; commonSegments[index] === pathSegments[index] &&
  18825. index < Math.min(commonSegments.length, pathSegments.length); index++)
  18826. ;
  18827. return commonSegments.slice(0, index);
  18828. }, files[0].split(/\/+|\\+/));
  18829. // Windows correctly handles paths with forward-slashes
  18830. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  18831. }
  18832. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  18833. function sortByExecutionOrder(units) {
  18834. units.sort(compareExecIndex);
  18835. }
  18836. // This process is currently faulty in so far as it only takes the first entry
  18837. // module into account and assumes that dynamic imports are imported in a
  18838. // certain order.
  18839. // A better algorithm would follow every possible execution path and mark which
  18840. // modules are executed before or after which other modules. THen the chunking
  18841. // would need to take care that in each chunk, all modules are always executed
  18842. // in the same sequence.
  18843. function analyseModuleExecution(entryModules) {
  18844. let nextExecIndex = 0;
  18845. const cyclePaths = [];
  18846. const analysedModules = new Set();
  18847. const dynamicImports = new Set();
  18848. const parents = new Map();
  18849. const orderedModules = [];
  18850. const analyseModule = (module) => {
  18851. if (module instanceof Module) {
  18852. for (const dependency of module.dependencies) {
  18853. if (parents.has(dependency)) {
  18854. if (!analysedModules.has(dependency)) {
  18855. cyclePaths.push(getCyclePath(dependency, module, parents));
  18856. }
  18857. continue;
  18858. }
  18859. parents.set(dependency, module);
  18860. analyseModule(dependency);
  18861. }
  18862. for (const dependency of module.implicitlyLoadedBefore) {
  18863. dynamicImports.add(dependency);
  18864. }
  18865. for (const { resolution } of module.dynamicImports) {
  18866. if (resolution instanceof Module) {
  18867. dynamicImports.add(resolution);
  18868. }
  18869. }
  18870. orderedModules.push(module);
  18871. }
  18872. module.execIndex = nextExecIndex++;
  18873. analysedModules.add(module);
  18874. };
  18875. for (const currentEntry of entryModules) {
  18876. if (!parents.has(currentEntry)) {
  18877. parents.set(currentEntry, null);
  18878. analyseModule(currentEntry);
  18879. }
  18880. }
  18881. for (const currentEntry of dynamicImports) {
  18882. if (!parents.has(currentEntry)) {
  18883. parents.set(currentEntry, null);
  18884. analyseModule(currentEntry);
  18885. }
  18886. }
  18887. return { cyclePaths, orderedModules };
  18888. }
  18889. function getCyclePath(module, parent, parents) {
  18890. const cycleSymbol = Symbol(module.id);
  18891. const path = [module.id];
  18892. let nextModule = parent;
  18893. module.cycles.add(cycleSymbol);
  18894. while (nextModule !== module) {
  18895. nextModule.cycles.add(cycleSymbol);
  18896. path.push(nextModule.id);
  18897. nextModule = parents.get(nextModule);
  18898. }
  18899. path.push(path[0]);
  18900. path.reverse();
  18901. return path;
  18902. }
  18903. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  18904. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  18905. const cnst = constBindings ? 'const' : 'var';
  18906. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  18907. const getFunctionIntro = arrowFunctions
  18908. ? (parameters, { isAsync, name }) => {
  18909. const singleParameter = parameters.length === 1;
  18910. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  18911. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  18912. }
  18913. : getNonArrowFunctionIntro;
  18914. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  18915. `${getFunctionIntro(parameters, {
  18916. isAsync: false,
  18917. name
  18918. })}${arrowFunctions
  18919. ? lineBreakIndent
  18920. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  18921. : ''
  18922. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  18923. arrowFunctions
  18924. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  18925. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  18926. ];
  18927. const isValidPropertyName = reservedNamesAsProps
  18928. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  18929. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  18930. return {
  18931. _,
  18932. cnst,
  18933. getDirectReturnFunction,
  18934. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  18935. const [left, right] = getDirectReturnFunction(parameters, {
  18936. functionReturn: true,
  18937. lineBreakIndent: null,
  18938. name: null
  18939. });
  18940. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  18941. },
  18942. getFunctionIntro,
  18943. getNonArrowFunctionIntro,
  18944. getObject(fields, { lineBreakIndent }) {
  18945. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  18946. return `{${fields
  18947. .map(([key, value]) => {
  18948. if (key === null)
  18949. return `${prefix}${value}`;
  18950. const keyInObject = stringifyObjectKeyIfNeeded(key);
  18951. return key === value && objectShorthand && key === keyInObject
  18952. ? prefix + key
  18953. : `${prefix}${keyInObject}:${_}${value}`;
  18954. })
  18955. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  18956. },
  18957. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  18958. n,
  18959. s
  18960. };
  18961. }
  18962. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  18963. class Source {
  18964. constructor(filename, content) {
  18965. this.isOriginal = true;
  18966. this.filename = filename;
  18967. this.content = content;
  18968. }
  18969. traceSegment(line, column, name) {
  18970. return { column, line, name, source: this };
  18971. }
  18972. }
  18973. class Link {
  18974. constructor(map, sources) {
  18975. this.sources = sources;
  18976. this.names = map.names;
  18977. this.mappings = map.mappings;
  18978. }
  18979. traceMappings() {
  18980. const sources = [];
  18981. const sourceIndexMap = new Map();
  18982. const sourcesContent = [];
  18983. const names = [];
  18984. const nameIndexMap = new Map();
  18985. const mappings = [];
  18986. for (const line of this.mappings) {
  18987. const tracedLine = [];
  18988. for (const segment of line) {
  18989. if (segment.length === 1)
  18990. continue;
  18991. const source = this.sources[segment[1]];
  18992. if (!source)
  18993. continue;
  18994. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  18995. if (traced) {
  18996. const { column, line, name, source: { content, filename } } = traced;
  18997. let sourceIndex = sourceIndexMap.get(filename);
  18998. if (sourceIndex === undefined) {
  18999. sourceIndex = sources.length;
  19000. sources.push(filename);
  19001. sourceIndexMap.set(filename, sourceIndex);
  19002. sourcesContent[sourceIndex] = content;
  19003. }
  19004. else if (sourcesContent[sourceIndex] == null) {
  19005. sourcesContent[sourceIndex] = content;
  19006. }
  19007. else if (content != null && sourcesContent[sourceIndex] !== content) {
  19008. return error(logConflictingSourcemapSources(filename));
  19009. }
  19010. const tracedSegment = [segment[0], sourceIndex, line, column];
  19011. if (name) {
  19012. let nameIndex = nameIndexMap.get(name);
  19013. if (nameIndex === undefined) {
  19014. nameIndex = names.length;
  19015. names.push(name);
  19016. nameIndexMap.set(name, nameIndex);
  19017. }
  19018. tracedSegment[4] = nameIndex;
  19019. }
  19020. tracedLine.push(tracedSegment);
  19021. }
  19022. }
  19023. mappings.push(tracedLine);
  19024. }
  19025. return { mappings, names, sources, sourcesContent };
  19026. }
  19027. traceSegment(line, column, name) {
  19028. const segments = this.mappings[line];
  19029. if (!segments)
  19030. return null;
  19031. // binary search through segments for the given column
  19032. let searchStart = 0;
  19033. let searchEnd = segments.length - 1;
  19034. while (searchStart <= searchEnd) {
  19035. const m = (searchStart + searchEnd) >> 1;
  19036. const segment = segments[m];
  19037. // If a sourcemap does not have sufficient resolution to contain a
  19038. // necessary mapping, e.g. because it only contains line information, we
  19039. // use the best approximation we could find
  19040. if (segment[0] === column || searchStart === searchEnd) {
  19041. if (segment.length == 1)
  19042. return null;
  19043. const source = this.sources[segment[1]];
  19044. if (!source)
  19045. return null;
  19046. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  19047. }
  19048. if (segment[0] > column) {
  19049. searchEnd = m - 1;
  19050. }
  19051. else {
  19052. searchStart = m + 1;
  19053. }
  19054. }
  19055. return null;
  19056. }
  19057. }
  19058. function getLinkMap(log) {
  19059. return function linkMap(source, map) {
  19060. if (!map.missing) {
  19061. return new Link(map, [source]);
  19062. }
  19063. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  19064. return new Link({
  19065. mappings: [],
  19066. names: []
  19067. }, [source]);
  19068. };
  19069. }
  19070. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  19071. let source;
  19072. if (originalSourcemap) {
  19073. const sources = originalSourcemap.sources;
  19074. const sourcesContent = originalSourcemap.sourcesContent || [];
  19075. const directory = dirname(id) || '.';
  19076. const sourceRoot = originalSourcemap.sourceRoot || '.';
  19077. const baseSources = sources.map((source, index) => new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
  19078. source = new Link(originalSourcemap, baseSources);
  19079. }
  19080. else {
  19081. source = new Source(id, originalCode);
  19082. }
  19083. return sourcemapChain.reduce(linkMap, source);
  19084. }
  19085. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  19086. const linkMap = getLinkMap(log);
  19087. const moduleSources = modules
  19088. .filter(module => !module.excludeFromSourcemap)
  19089. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  19090. const link = new Link(map, moduleSources);
  19091. const source = bundleSourcemapChain.reduce(linkMap, link);
  19092. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  19093. if (file) {
  19094. const directory = dirname(file);
  19095. sources = sources.map((source) => relative(directory, source));
  19096. file = basename(file);
  19097. }
  19098. sourcesContent = (excludeContent ? null : sourcesContent);
  19099. for (const module of modules) {
  19100. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  19101. }
  19102. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  19103. }
  19104. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  19105. if (sourcemapChain.length === 0) {
  19106. return originalSourcemap;
  19107. }
  19108. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  19109. const map = source.traceMappings();
  19110. return decodedSourcemap({ version: 3, ...map });
  19111. }
  19112. let textEncoder;
  19113. const getHash64 = input => xxhashBase64Url(ensureBuffer(input));
  19114. const getHash36 = input => xxhashBase36(ensureBuffer(input));
  19115. const getHash16 = input => xxhashBase16(ensureBuffer(input));
  19116. const hasherByType = {
  19117. base36: getHash36,
  19118. base64: getHash64,
  19119. hex: getHash16
  19120. };
  19121. function ensureBuffer(input) {
  19122. if (typeof input === 'string') {
  19123. if (typeof Buffer === 'undefined') {
  19124. textEncoder ??= new TextEncoder();
  19125. return textEncoder.encode(input);
  19126. }
  19127. return Buffer.from(input);
  19128. }
  19129. return input;
  19130. }
  19131. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  19132. // this for an actual sourceMappingURL
  19133. let SOURCEMAPPING_URL = 'sourceMa';
  19134. SOURCEMAPPING_URL += 'ppingURL';
  19135. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  19136. timeStart('render chunks', 2);
  19137. reserveEntryChunksInBundle(chunks);
  19138. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  19139. timeEnd('render chunks', 2);
  19140. timeStart('transform chunks', 2);
  19141. const getHash = hasherByType[outputOptions.hashCharacters];
  19142. const chunkGraph = getChunkGraph(chunks);
  19143. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  19144. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  19145. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  19146. timeEnd('transform chunks', 2);
  19147. }
  19148. function reserveEntryChunksInBundle(chunks) {
  19149. for (const chunk of chunks) {
  19150. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  19151. // reserves name in bundle as side effect if it does not contain a hash
  19152. chunk.getPreliminaryFileName();
  19153. }
  19154. }
  19155. }
  19156. function getChunkGraph(chunks) {
  19157. return Object.fromEntries(chunks.map(chunk => {
  19158. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  19159. return [renderedChunkInfo.fileName, renderedChunkInfo];
  19160. }));
  19161. }
  19162. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  19163. let map = null;
  19164. const sourcemapChain = [];
  19165. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  19166. if (result == null)
  19167. return code;
  19168. if (typeof result === 'string')
  19169. result = {
  19170. code: result,
  19171. map: undefined
  19172. };
  19173. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  19174. if (result.map !== null) {
  19175. const map = decodedSourcemap(result.map);
  19176. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  19177. }
  19178. return result.code;
  19179. });
  19180. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  19181. if (!compact && code[code.length - 1] !== '\n')
  19182. code += '\n';
  19183. if (sourcemap) {
  19184. timeStart('sourcemaps', 3);
  19185. let resultingFile;
  19186. if (file)
  19187. resultingFile = resolve$1(sourcemapFile || file);
  19188. else if (dir)
  19189. resultingFile = resolve$1(dir, fileName);
  19190. else
  19191. resultingFile = resolve$1(fileName);
  19192. const decodedMap = magicString.generateDecodedMap({});
  19193. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  19194. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  19195. let sourcePath = map.sources[sourcesIndex];
  19196. const sourcemapPath = `${resultingFile}.map`;
  19197. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  19198. if (typeof ignoreList !== 'boolean') {
  19199. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  19200. }
  19201. if (ignoreList) {
  19202. if (map.x_google_ignoreList === undefined) {
  19203. map.x_google_ignoreList = [];
  19204. }
  19205. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  19206. map.x_google_ignoreList.push(sourcesIndex);
  19207. }
  19208. }
  19209. if (sourcemapPathTransform) {
  19210. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  19211. if (typeof sourcePath !== 'string') {
  19212. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  19213. }
  19214. }
  19215. map.sources[sourcesIndex] = normalize(sourcePath);
  19216. }
  19217. timeEnd('sourcemaps', 3);
  19218. }
  19219. return {
  19220. code,
  19221. map
  19222. };
  19223. }
  19224. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  19225. const nonHashedChunksWithPlaceholders = [];
  19226. const renderedChunksByPlaceholder = new Map();
  19227. const hashDependenciesByPlaceholder = new Map();
  19228. const initialHashesByPlaceholder = new Map();
  19229. const placeholders = new Set();
  19230. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  19231. if (hashPlaceholder)
  19232. placeholders.add(hashPlaceholder);
  19233. }
  19234. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  19235. const transformedChunk = {
  19236. chunk,
  19237. fileName,
  19238. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  19239. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  19240. };
  19241. const { code, map } = transformedChunk;
  19242. if (hashPlaceholder) {
  19243. // To create a reproducible content-only hash, all placeholders are
  19244. // replaced with the same value before hashing
  19245. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  19246. let contentToHash = transformedCode;
  19247. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  19248. if (pluginHash) {
  19249. augmentation += pluginHash;
  19250. }
  19251. return augmentation;
  19252. });
  19253. if (hashAugmentation) {
  19254. contentToHash += hashAugmentation;
  19255. }
  19256. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  19257. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  19258. containedPlaceholders,
  19259. contentHash: getHash(contentToHash)
  19260. });
  19261. }
  19262. else {
  19263. nonHashedChunksWithPlaceholders.push(transformedChunk);
  19264. }
  19265. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  19266. if (map && sourcemapHashPlaceholder) {
  19267. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  19268. }
  19269. }));
  19270. return {
  19271. hashDependenciesByPlaceholder,
  19272. initialHashesByPlaceholder,
  19273. nonHashedChunksWithPlaceholders,
  19274. placeholders,
  19275. renderedChunksByPlaceholder
  19276. };
  19277. }
  19278. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  19279. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  19280. for (const placeholder of placeholders) {
  19281. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  19282. let contentToHash = '';
  19283. const hashDependencyPlaceholders = new Set([placeholder]);
  19284. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  19285. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  19286. contentToHash += contentHash;
  19287. for (const containedPlaceholder of containedPlaceholders) {
  19288. // When looping over a map, setting an entry only causes a new iteration if the key is new
  19289. hashDependencyPlaceholders.add(containedPlaceholder);
  19290. }
  19291. }
  19292. let finalFileName;
  19293. let finalHash;
  19294. do {
  19295. // In case of a hash collision, create a hash of the hash
  19296. if (finalHash) {
  19297. contentToHash = finalHash;
  19298. }
  19299. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  19300. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  19301. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  19302. bundle[finalFileName] = FILE_PLACEHOLDER;
  19303. hashesByPlaceholder.set(placeholder, finalHash);
  19304. }
  19305. return hashesByPlaceholder;
  19306. }
  19307. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  19308. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  19309. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  19310. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  19311. let finalSourcemapFileName = null;
  19312. if (map) {
  19313. if (options.sourcemapDebugIds) {
  19314. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19315. }
  19316. finalSourcemapFileName = sourcemapFileName
  19317. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19318. : `${finalFileName}.map`;
  19319. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  19320. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19321. }
  19322. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19323. }
  19324. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  19325. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  19326. let finalSourcemapFileName = null;
  19327. if (map) {
  19328. if (options.sourcemapDebugIds) {
  19329. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19330. }
  19331. finalSourcemapFileName = sourcemapFileName
  19332. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19333. : `${fileName}.map`;
  19334. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19335. }
  19336. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19337. }
  19338. }
  19339. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  19340. let url;
  19341. if (sourcemap === 'inline') {
  19342. url = map.toUrl();
  19343. }
  19344. else {
  19345. const sourcemapFileName = basename(fileName);
  19346. url = sourcemapBaseUrl
  19347. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  19348. : sourcemapFileName;
  19349. pluginDriver.emitFile({
  19350. fileName,
  19351. originalFileName: null,
  19352. source: map.toString(),
  19353. type: 'asset'
  19354. });
  19355. }
  19356. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19357. }
  19358. function calculateDebugIdAndGetComment(code, map) {
  19359. const hash = hasherByType.hex(code);
  19360. const debugId = [
  19361. hash.slice(0, 8),
  19362. hash.slice(8, 12),
  19363. '4' + hash.slice(12, 15),
  19364. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  19365. hash.slice(20, 32)
  19366. ].join('-');
  19367. map.debugId = debugId;
  19368. return '//# debugId=' + debugId + '\n';
  19369. }
  19370. class Bundle {
  19371. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  19372. this.outputOptions = outputOptions;
  19373. this.unsetOptions = unsetOptions;
  19374. this.inputOptions = inputOptions;
  19375. this.pluginDriver = pluginDriver;
  19376. this.graph = graph;
  19377. this.facadeChunkByModule = new Map();
  19378. this.includedNamespaces = new Set();
  19379. }
  19380. async generate(isWrite) {
  19381. timeStart('GENERATE', 1);
  19382. const outputBundleBase = Object.create(null);
  19383. const outputBundle = getOutputBundle(outputBundleBase);
  19384. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  19385. try {
  19386. timeStart('initialize render', 2);
  19387. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  19388. timeEnd('initialize render', 2);
  19389. timeStart('generate chunks', 2);
  19390. const getHashPlaceholder = getHashPlaceholderGenerator();
  19391. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  19392. if (chunks.length > 1) {
  19393. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  19394. }
  19395. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  19396. for (const chunk of chunks) {
  19397. chunk.generateExports();
  19398. chunk.inlineTransitiveImports();
  19399. }
  19400. timeEnd('generate chunks', 2);
  19401. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  19402. }
  19403. catch (error_) {
  19404. await this.pluginDriver.hookParallel('renderError', [error_]);
  19405. throw error_;
  19406. }
  19407. removeUnreferencedAssets(outputBundle);
  19408. timeStart('generate bundle', 2);
  19409. await this.pluginDriver.hookSeq('generateBundle', [
  19410. this.outputOptions,
  19411. outputBundle,
  19412. isWrite
  19413. ]);
  19414. this.finaliseAssets(outputBundle);
  19415. timeEnd('generate bundle', 2);
  19416. timeEnd('GENERATE', 1);
  19417. return outputBundleBase;
  19418. }
  19419. async addManualChunks(manualChunks) {
  19420. const manualChunkAliasByEntry = new Map();
  19421. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  19422. alias,
  19423. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  19424. })));
  19425. for (const { alias, entries } of chunkEntries) {
  19426. for (const entry of entries) {
  19427. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  19428. }
  19429. }
  19430. return manualChunkAliasByEntry;
  19431. }
  19432. assignManualChunks(getManualChunk) {
  19433. const manualChunkAliasesWithEntry = [];
  19434. const manualChunksApi = {
  19435. getModuleIds: () => this.graph.modulesById.keys(),
  19436. getModuleInfo: this.graph.getModuleInfo
  19437. };
  19438. for (const module of this.graph.modulesById.values()) {
  19439. if (module instanceof Module) {
  19440. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  19441. if (typeof manualChunkAlias === 'string') {
  19442. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  19443. }
  19444. }
  19445. }
  19446. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  19447. const manualChunkAliasByEntry = new Map();
  19448. for (const [alias, module] of manualChunkAliasesWithEntry) {
  19449. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  19450. }
  19451. return manualChunkAliasByEntry;
  19452. }
  19453. finaliseAssets(bundle) {
  19454. if (this.outputOptions.validate) {
  19455. for (const file of Object.values(bundle)) {
  19456. if ('code' in file) {
  19457. try {
  19458. parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  19459. }
  19460. catch (error_) {
  19461. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  19462. }
  19463. }
  19464. }
  19465. }
  19466. this.pluginDriver.finaliseAssets();
  19467. }
  19468. async generateChunks(bundle, getHashPlaceholder) {
  19469. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  19470. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  19471. ? await this.addManualChunks(manualChunks)
  19472. : this.assignManualChunks(manualChunks);
  19473. const snippets = getGenerateCodeSnippets(this.outputOptions);
  19474. const includedModules = getIncludedModules(this.graph.modulesById);
  19475. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  19476. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  19477. const executableModule = inlineDynamicImports
  19478. ? [{ alias: null, modules: includedModules }]
  19479. : preserveModules
  19480. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  19481. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog);
  19482. const chunks = new Array(executableModule.length);
  19483. const chunkByModule = new Map();
  19484. let index = 0;
  19485. for (const { alias, modules } of executableModule) {
  19486. sortByExecutionOrder(modules);
  19487. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias, getHashPlaceholder, bundle, inputBase, snippets);
  19488. chunks[index++] = chunk;
  19489. }
  19490. for (const chunk of chunks) {
  19491. chunk.link();
  19492. }
  19493. const facades = [];
  19494. for (const chunk of chunks) {
  19495. facades.push(...chunk.generateFacades());
  19496. }
  19497. return [...chunks, ...facades];
  19498. }
  19499. }
  19500. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  19501. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  19502. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  19503. if (typeof outputOptions.file === 'string')
  19504. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
  19505. if (outputOptions.sourcemapFile)
  19506. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  19507. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  19508. log(LOGLEVEL_WARN, logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
  19509. }
  19510. function getIncludedModules(modulesById) {
  19511. const includedModules = [];
  19512. for (const module of modulesById.values()) {
  19513. if (module instanceof Module &&
  19514. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  19515. includedModules.push(module);
  19516. }
  19517. }
  19518. return includedModules;
  19519. }
  19520. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  19521. const absoluteEntryModulePaths = [];
  19522. for (const module of includedModules) {
  19523. if ((module.info.isEntry || preserveModules) && isAbsolute$1(module.id)) {
  19524. absoluteEntryModulePaths.push(module.id);
  19525. }
  19526. }
  19527. return absoluteEntryModulePaths;
  19528. }
  19529. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  19530. const externalChunkByModule = new Map();
  19531. for (const module of modulesById.values()) {
  19532. if (module instanceof ExternalModule) {
  19533. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  19534. }
  19535. }
  19536. return externalChunkByModule;
  19537. }
  19538. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  19539. const existingAlias = manualChunkAliasByEntry.get(module);
  19540. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  19541. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  19542. }
  19543. manualChunkAliasByEntry.set(module, alias);
  19544. }
  19545. function flru (max) {
  19546. var num, curr, prev;
  19547. var limit = max;
  19548. function keep(key, value) {
  19549. if (++num > limit) {
  19550. prev = curr;
  19551. reset(1);
  19552. ++num;
  19553. }
  19554. curr[key] = value;
  19555. }
  19556. function reset(isPartial) {
  19557. num = 0;
  19558. curr = Object.create(null);
  19559. isPartial || (prev=Object.create(null));
  19560. }
  19561. reset();
  19562. return {
  19563. clear: reset,
  19564. has: function (key) {
  19565. return curr[key] !== void 0 || prev[key] !== void 0;
  19566. },
  19567. get: function (key) {
  19568. var val = curr[key];
  19569. if (val !== void 0) return val;
  19570. if ((val=prev[key]) !== void 0) {
  19571. keep(key, val);
  19572. return val;
  19573. }
  19574. },
  19575. set: function (key, value) {
  19576. if (curr[key] !== void 0) {
  19577. curr[key] = value;
  19578. } else {
  19579. keep(key, value);
  19580. }
  19581. }
  19582. };
  19583. }
  19584. class GlobalScope extends Scope {
  19585. constructor() {
  19586. super();
  19587. this.parent = null;
  19588. this.variables.set('undefined', new UndefinedVariable());
  19589. }
  19590. findVariable(name) {
  19591. let variable = this.variables.get(name);
  19592. if (!variable) {
  19593. variable = new GlobalVariable(name);
  19594. this.variables.set(name, variable);
  19595. }
  19596. return variable;
  19597. }
  19598. }
  19599. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  19600. let skipped = null;
  19601. let replaceContext = null;
  19602. if (skip) {
  19603. skipped = new Set();
  19604. for (const skippedCall of skip) {
  19605. if (source === skippedCall.source && importer === skippedCall.importer) {
  19606. skipped.add(skippedCall.plugin);
  19607. }
  19608. }
  19609. replaceContext = (pluginContext, plugin) => ({
  19610. ...pluginContext,
  19611. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) => {
  19612. skipSelf ??= true;
  19613. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  19614. }
  19615. });
  19616. }
  19617. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  19618. }
  19619. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  19620. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  19621. if (pluginResult != null) {
  19622. const [resolveIdResult, plugin] = pluginResult;
  19623. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  19624. return {
  19625. ...resolveIdResult,
  19626. resolvedBy: plugin.name
  19627. };
  19628. }
  19629. if (typeof resolveIdResult === 'string') {
  19630. return {
  19631. id: resolveIdResult,
  19632. resolvedBy: plugin.name
  19633. };
  19634. }
  19635. return resolveIdResult;
  19636. }
  19637. // external modules (non-entry modules that start with neither '.' or '/')
  19638. // are skipped at this stage.
  19639. if (importer !== undefined && !isAbsolute$1(source) && source[0] !== '.')
  19640. return null;
  19641. // `resolve` processes paths from right to left, prepending them until an
  19642. // absolute path is created. Absolute importees therefore shortcircuit the
  19643. // resolve call and require no special handing on our part.
  19644. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  19645. return addJsExtensionIfNecessary(importer ? resolve$1(dirname(importer), source) : resolve$1(source), preserveSymlinks);
  19646. }
  19647. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  19648. return ((await findFile(file, preserveSymlinks)) ??
  19649. (await findFile(file + '.mjs', preserveSymlinks)) ??
  19650. (await findFile(file + '.js', preserveSymlinks)));
  19651. }
  19652. async function findFile(file, preserveSymlinks) {
  19653. try {
  19654. const stats = await lstat(file);
  19655. if (!preserveSymlinks && stats.isSymbolicLink())
  19656. return await findFile(await realpath(file), preserveSymlinks);
  19657. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  19658. // check case
  19659. const name = basename(file);
  19660. const files = await readdir(dirname(file));
  19661. if (files.includes(name))
  19662. return file;
  19663. }
  19664. }
  19665. catch {
  19666. // suppress
  19667. }
  19668. }
  19669. function stripBom(content) {
  19670. if (content.charCodeAt(0) === 0xfe_ff) {
  19671. return stripBom(content.slice(1));
  19672. }
  19673. return content;
  19674. }
  19675. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  19676. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  19677. function createPluginCache(cache) {
  19678. return {
  19679. delete(id) {
  19680. return delete cache[id];
  19681. },
  19682. get(id) {
  19683. const item = cache[id];
  19684. if (!item)
  19685. return;
  19686. item[0] = 0;
  19687. return item[1];
  19688. },
  19689. has(id) {
  19690. const item = cache[id];
  19691. if (!item)
  19692. return false;
  19693. item[0] = 0;
  19694. return true;
  19695. },
  19696. set(id, value) {
  19697. cache[id] = [0, value];
  19698. }
  19699. };
  19700. }
  19701. function getTrackedPluginCache(pluginCache, onUse) {
  19702. return {
  19703. delete(id) {
  19704. onUse();
  19705. return pluginCache.delete(id);
  19706. },
  19707. get(id) {
  19708. onUse();
  19709. return pluginCache.get(id);
  19710. },
  19711. has(id) {
  19712. onUse();
  19713. return pluginCache.has(id);
  19714. },
  19715. set(id, value) {
  19716. onUse();
  19717. return pluginCache.set(id, value);
  19718. }
  19719. };
  19720. }
  19721. const NO_CACHE = {
  19722. delete() {
  19723. return false;
  19724. },
  19725. get() {
  19726. return undefined;
  19727. },
  19728. has() {
  19729. return false;
  19730. },
  19731. set() { }
  19732. };
  19733. function uncacheablePluginError(pluginName) {
  19734. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  19735. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  19736. return error(logAnonymousPluginCache());
  19737. }
  19738. return error(logDuplicatePluginName(pluginName));
  19739. }
  19740. function getCacheForUncacheablePlugin(pluginName) {
  19741. return {
  19742. delete() {
  19743. return uncacheablePluginError(pluginName);
  19744. },
  19745. get() {
  19746. return uncacheablePluginError(pluginName);
  19747. },
  19748. has() {
  19749. return uncacheablePluginError(pluginName);
  19750. },
  19751. set() {
  19752. return uncacheablePluginError(pluginName);
  19753. }
  19754. };
  19755. }
  19756. async function asyncFlatten(array) {
  19757. do {
  19758. array = (await Promise.all(array)).flat(Infinity);
  19759. } while (array.some((v) => v?.then));
  19760. return array;
  19761. }
  19762. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  19763. const { onwarn, onLog } = config;
  19764. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  19765. if (onLog) {
  19766. const minimalPriority = logLevelPriority[logLevel];
  19767. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  19768. if (level === LOGLEVEL_ERROR) {
  19769. return error(normalizeLog(handledLog));
  19770. }
  19771. if (logLevelPriority[level] >= minimalPriority) {
  19772. defaultOnLog(level, normalizeLog(handledLog));
  19773. }
  19774. });
  19775. }
  19776. return defaultOnLog;
  19777. };
  19778. const getDefaultOnLog = (printLog, onwarn) => onwarn
  19779. ? (level, log) => {
  19780. if (level === LOGLEVEL_WARN) {
  19781. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  19782. }
  19783. else {
  19784. printLog(level, log);
  19785. }
  19786. }
  19787. : printLog;
  19788. const addLogToString = (log) => {
  19789. Object.defineProperty(log, 'toString', {
  19790. value: () => log.message,
  19791. writable: true
  19792. });
  19793. return log;
  19794. };
  19795. const normalizeLog = (log) => typeof log === 'string'
  19796. ? { message: log }
  19797. : typeof log === 'function'
  19798. ? normalizeLog(log())
  19799. : log;
  19800. const defaultPrintLog = (level, { message }) => {
  19801. switch (level) {
  19802. case LOGLEVEL_WARN: {
  19803. return console.warn(message);
  19804. }
  19805. case LOGLEVEL_DEBUG: {
  19806. return console.debug(message);
  19807. }
  19808. default: {
  19809. return console.info(message);
  19810. }
  19811. }
  19812. };
  19813. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  19814. const validOptionSet = new Set(validOptions);
  19815. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  19816. if (unknownOptions.length > 0) {
  19817. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  19818. }
  19819. }
  19820. const treeshakePresets = {
  19821. recommended: {
  19822. annotations: true,
  19823. correctVarValueBeforeDeclaration: false,
  19824. manualPureFunctions: EMPTY_ARRAY,
  19825. moduleSideEffects: () => true,
  19826. propertyReadSideEffects: true,
  19827. tryCatchDeoptimization: true,
  19828. unknownGlobalSideEffects: false
  19829. },
  19830. safest: {
  19831. annotations: true,
  19832. correctVarValueBeforeDeclaration: true,
  19833. manualPureFunctions: EMPTY_ARRAY,
  19834. moduleSideEffects: () => true,
  19835. propertyReadSideEffects: true,
  19836. tryCatchDeoptimization: true,
  19837. unknownGlobalSideEffects: true
  19838. },
  19839. smallest: {
  19840. annotations: true,
  19841. correctVarValueBeforeDeclaration: false,
  19842. manualPureFunctions: EMPTY_ARRAY,
  19843. moduleSideEffects: () => false,
  19844. propertyReadSideEffects: false,
  19845. tryCatchDeoptimization: false,
  19846. unknownGlobalSideEffects: false
  19847. }
  19848. };
  19849. const jsxPresets = {
  19850. preserve: {
  19851. factory: null,
  19852. fragment: null,
  19853. importSource: null,
  19854. mode: 'preserve'
  19855. },
  19856. 'preserve-react': {
  19857. factory: 'React.createElement',
  19858. fragment: 'React.Fragment',
  19859. importSource: 'react',
  19860. mode: 'preserve'
  19861. },
  19862. react: {
  19863. factory: 'React.createElement',
  19864. fragment: 'React.Fragment',
  19865. importSource: 'react',
  19866. mode: 'classic'
  19867. },
  19868. 'react-jsx': {
  19869. factory: 'React.createElement',
  19870. importSource: 'react',
  19871. jsxImportSource: 'react/jsx-runtime',
  19872. mode: 'automatic'
  19873. }
  19874. };
  19875. const generatedCodePresets = {
  19876. es2015: {
  19877. arrowFunctions: true,
  19878. constBindings: true,
  19879. objectShorthand: true,
  19880. reservedNamesAsProps: true,
  19881. symbols: true
  19882. },
  19883. es5: {
  19884. arrowFunctions: false,
  19885. constBindings: false,
  19886. objectShorthand: false,
  19887. reservedNamesAsProps: true,
  19888. symbols: false
  19889. }
  19890. };
  19891. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  19892. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  19893. if (typeof value === 'string') {
  19894. const preset = presets[value];
  19895. if (preset) {
  19896. return preset;
  19897. }
  19898. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  19899. }
  19900. return objectifyOption(value);
  19901. };
  19902. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  19903. const presetName = value?.preset;
  19904. if (presetName) {
  19905. const preset = presets[presetName];
  19906. if (preset) {
  19907. return { ...preset, ...value };
  19908. }
  19909. else {
  19910. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  19911. }
  19912. }
  19913. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  19914. };
  19915. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  19916. async function transform(source, module, pluginDriver, log) {
  19917. const id = module.id;
  19918. const sourcemapChain = [];
  19919. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  19920. const originalCode = source.code;
  19921. let ast = source.ast;
  19922. const transformDependencies = [];
  19923. const emittedFiles = [];
  19924. let customTransformCache = false;
  19925. const useCustomTransformCache = () => (customTransformCache = true);
  19926. let pluginName = '';
  19927. let currentSource = source.code;
  19928. function transformReducer(previousCode, result, plugin) {
  19929. let code;
  19930. let map;
  19931. if (typeof result === 'string') {
  19932. code = result;
  19933. }
  19934. else if (result && typeof result === 'object') {
  19935. module.updateOptions(result);
  19936. if (result.code == null) {
  19937. if (result.map || result.ast) {
  19938. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  19939. }
  19940. return previousCode;
  19941. }
  19942. ({ code, map, ast } = result);
  19943. }
  19944. else {
  19945. return previousCode;
  19946. }
  19947. // strict null check allows 'null' maps to not be pushed to the chain,
  19948. // while 'undefined' gets the missing map warning
  19949. if (map !== null) {
  19950. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  19951. missing: true,
  19952. plugin: plugin.name
  19953. });
  19954. }
  19955. currentSource = code;
  19956. return code;
  19957. }
  19958. const getLogHandler = (handler) => (log, pos) => {
  19959. log = normalizeLog(log);
  19960. if (pos)
  19961. augmentCodeLocation(log, pos, currentSource, id);
  19962. log.id = id;
  19963. log.hook = 'transform';
  19964. handler(log);
  19965. };
  19966. let code;
  19967. try {
  19968. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  19969. pluginName = plugin.name;
  19970. return {
  19971. ...pluginContext,
  19972. addWatchFile(id) {
  19973. transformDependencies.push(id);
  19974. pluginContext.addWatchFile(id);
  19975. },
  19976. cache: customTransformCache
  19977. ? pluginContext.cache
  19978. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  19979. debug: getLogHandler(pluginContext.debug),
  19980. emitFile(emittedFile) {
  19981. emittedFiles.push(emittedFile);
  19982. return pluginDriver.emitFile(emittedFile);
  19983. },
  19984. error(error_, pos) {
  19985. if (typeof error_ === 'string')
  19986. error_ = { message: error_ };
  19987. if (pos)
  19988. augmentCodeLocation(error_, pos, currentSource, id);
  19989. error_.id = id;
  19990. error_.hook = 'transform';
  19991. return pluginContext.error(error_);
  19992. },
  19993. getCombinedSourcemap() {
  19994. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  19995. if (!combinedMap) {
  19996. const magicString = new MagicString(originalCode);
  19997. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  19998. }
  19999. if (originalSourcemap !== combinedMap) {
  20000. originalSourcemap = combinedMap;
  20001. sourcemapChain.length = 0;
  20002. }
  20003. return new SourceMap({
  20004. ...combinedMap,
  20005. file: null,
  20006. sourcesContent: combinedMap.sourcesContent
  20007. });
  20008. },
  20009. info: getLogHandler(pluginContext.info),
  20010. setAssetSource() {
  20011. return this.error(logInvalidSetAssetSourceCall());
  20012. },
  20013. warn: getLogHandler(pluginContext.warn)
  20014. };
  20015. });
  20016. }
  20017. catch (error_) {
  20018. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  20019. }
  20020. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  20021. emittedFiles.length > 0)
  20022. module.transformFiles = emittedFiles;
  20023. return {
  20024. ast,
  20025. code,
  20026. customTransformCache,
  20027. originalCode,
  20028. originalSourcemap,
  20029. sourcemapChain,
  20030. transformDependencies
  20031. };
  20032. }
  20033. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20034. class ModuleLoader {
  20035. constructor(graph, modulesById, options, pluginDriver) {
  20036. this.graph = graph;
  20037. this.modulesById = modulesById;
  20038. this.options = options;
  20039. this.pluginDriver = pluginDriver;
  20040. this.implicitEntryModules = new Set();
  20041. this.indexedEntryModules = [];
  20042. this.latestLoadModulesPromise = Promise.resolve();
  20043. this.moduleLoadPromises = new Map();
  20044. this.modulesWithLoadedDependencies = new Set();
  20045. this.nextChunkNamePriority = 0;
  20046. this.nextEntryModuleIndex = 0;
  20047. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20048. ? false
  20049. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes), importer, source), attributes);
  20050. this.hasModuleSideEffects = options.treeshake
  20051. ? options.treeshake.moduleSideEffects
  20052. : () => true;
  20053. }
  20054. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  20055. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  20056. await this.awaitLoadModulesPromise();
  20057. return result;
  20058. }
  20059. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20060. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20061. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20062. const firstChunkNamePriority = this.nextChunkNamePriority;
  20063. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20064. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20065. for (const [index, entryModule] of entryModules.entries()) {
  20066. entryModule.isUserDefinedEntryPoint =
  20067. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20068. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20069. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20070. if (existingIndexedModule) {
  20071. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20072. }
  20073. else {
  20074. this.indexedEntryModules.push({
  20075. index: firstEntryModuleIndex + index,
  20076. module: entryModule
  20077. });
  20078. }
  20079. }
  20080. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20081. return entryModules;
  20082. }));
  20083. await this.awaitLoadModulesPromise();
  20084. return {
  20085. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20086. implicitEntryModules: [...this.implicitEntryModules],
  20087. newEntryModules
  20088. };
  20089. }
  20090. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20091. const unresolvedModule = {
  20092. fileName: fileName || null,
  20093. id,
  20094. importer,
  20095. name: name || null
  20096. };
  20097. const module = implicitlyLoadedAfterOneOf
  20098. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20099. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20100. if (preserveSignature != null) {
  20101. module.preserveSignature = preserveSignature;
  20102. }
  20103. return module;
  20104. }
  20105. async preloadModule(resolvedId) {
  20106. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20107. return module.info;
  20108. }
  20109. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20110. const chunkNamePriority = this.nextChunkNamePriority++;
  20111. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20112. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20113. if (!entryModule.info.isEntry) {
  20114. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20115. // We need to check again if this is still an entry module as these
  20116. // changes need to be performed atomically to avoid race conditions
  20117. // if the same module is re-emitted as an entry module.
  20118. // The inverse changes happen in "handleExistingModule"
  20119. if (!entryModule.info.isEntry) {
  20120. this.implicitEntryModules.add(entryModule);
  20121. for (const module of implicitlyLoadedAfterModules) {
  20122. entryModule.implicitlyLoadedAfter.add(module);
  20123. }
  20124. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20125. dependant.implicitlyLoadedBefore.add(entryModule);
  20126. }
  20127. }
  20128. }
  20129. return entryModule;
  20130. }));
  20131. }
  20132. async addModuleSource(id, importer, module) {
  20133. let source;
  20134. try {
  20135. source = await this.graph.fileOperationQueue.run(async () => {
  20136. const content = await this.pluginDriver.hookFirst('load', [id]);
  20137. if (content !== null)
  20138. return content;
  20139. this.graph.watchFiles[id] = true;
  20140. return await readFile(id, 'utf8');
  20141. });
  20142. }
  20143. catch (error_) {
  20144. let message = `Could not load ${id}`;
  20145. if (importer)
  20146. message += ` (imported by ${relativeId(importer)})`;
  20147. message += `: ${error_.message}`;
  20148. error_.message = message;
  20149. throw error_;
  20150. }
  20151. const sourceDescription = typeof source === 'string'
  20152. ? { code: source }
  20153. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20154. ? source
  20155. : error(logBadLoader(id));
  20156. sourceDescription.code = stripBom(sourceDescription.code);
  20157. const cachedModule = this.graph.cachedModules.get(id);
  20158. if (cachedModule &&
  20159. !cachedModule.customTransformCache &&
  20160. cachedModule.originalCode === sourceDescription.code &&
  20161. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20162. {
  20163. ast: cachedModule.ast,
  20164. code: cachedModule.code,
  20165. id: cachedModule.id,
  20166. meta: cachedModule.meta,
  20167. moduleSideEffects: cachedModule.moduleSideEffects,
  20168. resolvedSources: cachedModule.resolvedIds,
  20169. syntheticNamedExports: cachedModule.syntheticNamedExports
  20170. }
  20171. ]))) {
  20172. if (cachedModule.transformFiles) {
  20173. for (const emittedFile of cachedModule.transformFiles)
  20174. this.pluginDriver.emitFile(emittedFile);
  20175. }
  20176. await module.setSource(cachedModule);
  20177. }
  20178. else {
  20179. module.updateOptions(sourceDescription);
  20180. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  20181. }
  20182. }
  20183. async awaitLoadModulesPromise() {
  20184. let startingPromise;
  20185. do {
  20186. startingPromise = this.latestLoadModulesPromise;
  20187. await startingPromise;
  20188. } while (startingPromise !== this.latestLoadModulesPromise);
  20189. }
  20190. extendLoadModulesPromise(loadNewModulesPromise) {
  20191. this.latestLoadModulesPromise = Promise.all([
  20192. loadNewModulesPromise,
  20193. this.latestLoadModulesPromise
  20194. ]);
  20195. this.latestLoadModulesPromise.catch(() => {
  20196. /* Avoid unhandled Promise rejections */
  20197. });
  20198. return loadNewModulesPromise;
  20199. }
  20200. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20201. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20202. if (resolvedId === null)
  20203. return null;
  20204. if (typeof resolvedId === 'string') {
  20205. dynamicImport.resolution = resolvedId;
  20206. return null;
  20207. }
  20208. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20209. })));
  20210. for (const dependency of dependencies) {
  20211. if (dependency) {
  20212. module.dynamicDependencies.add(dependency);
  20213. dependency.dynamicImporters.push(module.id);
  20214. }
  20215. }
  20216. }
  20217. // If this is a preload, then this method always waits for the dependencies of
  20218. // the module to be resolved.
  20219. // Otherwise, if the module does not exist, it waits for the module and all
  20220. // its dependencies to be loaded.
  20221. // Otherwise, it returns immediately.
  20222. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20223. const existingModule = this.modulesById.get(id);
  20224. if (existingModule instanceof Module) {
  20225. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  20226. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  20227. }
  20228. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20229. return existingModule;
  20230. }
  20231. if (existingModule instanceof ExternalModule) {
  20232. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  20233. }
  20234. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  20235. this.modulesById.set(id, module);
  20236. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20237. this.getResolveStaticDependencyPromises(module),
  20238. this.getResolveDynamicImportPromises(module),
  20239. loadAndResolveDependenciesPromise
  20240. ]);
  20241. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20242. loadAndResolveDependenciesPromise.catch(() => {
  20243. /* avoid unhandled promise rejections */
  20244. });
  20245. this.moduleLoadPromises.set(module, loadPromise);
  20246. const resolveDependencyPromises = await loadPromise;
  20247. if (!isPreload) {
  20248. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20249. }
  20250. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20251. await loadAndResolveDependenciesPromise;
  20252. }
  20253. return module;
  20254. }
  20255. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20256. if (this.modulesWithLoadedDependencies.has(module)) {
  20257. return;
  20258. }
  20259. this.modulesWithLoadedDependencies.add(module);
  20260. await Promise.all([
  20261. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20262. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20263. ]);
  20264. module.linkImports();
  20265. // To handle errors when resolving dependencies or in moduleParsed
  20266. await loadAndResolveDependenciesPromise;
  20267. }
  20268. fetchResolvedDependency(source, importer, resolvedId) {
  20269. if (resolvedId.external) {
  20270. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  20271. let externalModule = this.modulesById.get(id);
  20272. if (!externalModule) {
  20273. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute$1(id), attributes);
  20274. this.modulesById.set(id, externalModule);
  20275. }
  20276. else if (!(externalModule instanceof ExternalModule)) {
  20277. return error(logInternalIdCannotBeExternal(source, importer));
  20278. }
  20279. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  20280. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  20281. }
  20282. return Promise.resolve(externalModule);
  20283. }
  20284. return this.fetchModule(resolvedId, importer, false, false);
  20285. }
  20286. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20287. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20288. module.dependencies.add(dependency);
  20289. dependency.importers.push(module.id);
  20290. }
  20291. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20292. for (const dependency of module.dependencies) {
  20293. if (dependency instanceof Module) {
  20294. dependency.importedFromNotTreeshaken = true;
  20295. }
  20296. }
  20297. }
  20298. }
  20299. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20300. const { makeAbsoluteExternalsRelative } = this.options;
  20301. if (resolveIdResult) {
  20302. if (typeof resolveIdResult === 'object') {
  20303. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20304. return {
  20305. ...resolveIdResult,
  20306. external: external &&
  20307. (external === 'relative' ||
  20308. !isAbsolute$1(resolveIdResult.id) ||
  20309. (external === true &&
  20310. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20311. 'absolute')
  20312. };
  20313. }
  20314. const external = this.options.external(resolveIdResult, importer, true);
  20315. return {
  20316. external: external &&
  20317. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20318. 'absolute'),
  20319. id: external && makeAbsoluteExternalsRelative
  20320. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20321. : resolveIdResult
  20322. };
  20323. }
  20324. const id = makeAbsoluteExternalsRelative
  20325. ? normalizeRelativeExternalId(source, importer)
  20326. : source;
  20327. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20328. return null;
  20329. }
  20330. return {
  20331. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20332. id
  20333. };
  20334. }
  20335. getResolveDynamicImportPromises(module) {
  20336. return module.dynamicImports.map(async (dynamicImport) => {
  20337. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  20338. if (resolvedId && typeof resolvedId === 'object') {
  20339. dynamicImport.id = resolvedId.id;
  20340. }
  20341. return [dynamicImport, resolvedId];
  20342. });
  20343. }
  20344. getResolveStaticDependencyPromises(module) {
  20345. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  20346. source,
  20347. (module.resolvedIds[source] =
  20348. module.resolvedIds[source] ||
  20349. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  20350. ]);
  20351. }
  20352. getResolvedIdWithDefaults(resolvedId, attributes) {
  20353. if (!resolvedId) {
  20354. return null;
  20355. }
  20356. const external = resolvedId.external || false;
  20357. return {
  20358. attributes: resolvedId.attributes || attributes,
  20359. external,
  20360. id: resolvedId.id,
  20361. meta: resolvedId.meta || {},
  20362. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  20363. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  20364. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  20365. };
  20366. }
  20367. async handleExistingModule(module, isEntry, isPreload) {
  20368. const loadPromise = this.moduleLoadPromises.get(module);
  20369. if (isPreload) {
  20370. return isPreload === RESOLVE_DEPENDENCIES
  20371. ? waitForDependencyResolution(loadPromise)
  20372. : loadPromise;
  20373. }
  20374. if (isEntry) {
  20375. // This reverts the changes in addEntryWithImplicitDependants and needs to
  20376. // be performed atomically
  20377. module.info.isEntry = true;
  20378. this.implicitEntryModules.delete(module);
  20379. for (const dependant of module.implicitlyLoadedAfter) {
  20380. dependant.implicitlyLoadedBefore.delete(module);
  20381. }
  20382. module.implicitlyLoadedAfter.clear();
  20383. }
  20384. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20385. }
  20386. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  20387. if (resolvedId === null) {
  20388. if (isRelative(source)) {
  20389. return error(logUnresolvedImport(source, importer));
  20390. }
  20391. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  20392. return {
  20393. attributes,
  20394. external: true,
  20395. id: source,
  20396. meta: {},
  20397. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20398. resolvedBy: 'rollup',
  20399. syntheticNamedExports: false
  20400. };
  20401. }
  20402. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20403. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  20404. }
  20405. return resolvedId;
  20406. }
  20407. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  20408. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  20409. if (resolveIdResult == null) {
  20410. return error(implicitlyLoadedBefore === null
  20411. ? logUnresolvedEntry(unresolvedId)
  20412. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20413. }
  20414. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  20415. if (resolveIdResult === false || isExternalModules) {
  20416. return error(implicitlyLoadedBefore === null
  20417. ? isExternalModules && isLoadForManualChunks
  20418. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  20419. : logEntryCannotBeExternal(unresolvedId)
  20420. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20421. }
  20422. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20423. ? resolveIdResult
  20424. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  20425. }
  20426. async resolveDynamicImport(module, specifier, importer, attributes) {
  20427. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20428. specifier,
  20429. importer,
  20430. { attributes }
  20431. ]);
  20432. if (typeof specifier !== 'string') {
  20433. if (typeof resolution === 'string') {
  20434. return resolution;
  20435. }
  20436. if (!resolution) {
  20437. return null;
  20438. }
  20439. return this.getResolvedIdWithDefaults(resolution, attributes);
  20440. }
  20441. if (resolution == null) {
  20442. const existingResolution = module.resolvedIds[specifier];
  20443. if (existingResolution) {
  20444. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  20445. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  20446. }
  20447. return existingResolution;
  20448. }
  20449. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  20450. }
  20451. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  20452. }
  20453. }
  20454. function normalizeRelativeExternalId(source, importer) {
  20455. return isRelative(source)
  20456. ? importer
  20457. ? resolve$1(importer, '..', source)
  20458. : resolve$1(source)
  20459. : source;
  20460. }
  20461. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20462. if (fileName !== null) {
  20463. module.chunkFileNames.add(fileName);
  20464. }
  20465. else if (name !== null) {
  20466. // Always keep chunkNames sorted by priority
  20467. let namePosition = 0;
  20468. while (module.chunkNames[namePosition]?.priority < priority)
  20469. namePosition++;
  20470. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20471. }
  20472. }
  20473. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20474. return (makeAbsoluteExternalsRelative === true ||
  20475. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  20476. !isAbsolute$1(id));
  20477. }
  20478. async function waitForDependencyResolution(loadPromise) {
  20479. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20480. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20481. }
  20482. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  20483. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  20484. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  20485. ? outputOptions.assetFileNames({
  20486. // Additionally, this should be non-enumerable in the next major
  20487. get name() {
  20488. warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  20489. return name;
  20490. },
  20491. names,
  20492. // Additionally, this should be non-enumerable in the next major
  20493. get originalFileName() {
  20494. warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  20495. return originalFileName;
  20496. },
  20497. originalFileNames,
  20498. source,
  20499. type: 'asset'
  20500. })
  20501. : outputOptions.assetFileNames, 'output.assetFileNames', {
  20502. ext: () => extname(emittedName).slice(1),
  20503. extname: () => extname(emittedName),
  20504. hash: size => sourceHash.slice(0, Math.max(0, size || DEFAULT_HASH_SIZE)),
  20505. name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
  20506. }), bundle);
  20507. }
  20508. function reserveFileNameInBundle(fileName, { bundle }, log) {
  20509. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  20510. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  20511. }
  20512. else {
  20513. bundle[fileName] = FILE_PLACEHOLDER;
  20514. }
  20515. }
  20516. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  20517. function hasValidType(emittedFile) {
  20518. return Boolean(emittedFile &&
  20519. emittedFileTypes.has(emittedFile.type));
  20520. }
  20521. function hasValidName(emittedFile) {
  20522. const validatedName = emittedFile.fileName || emittedFile.name;
  20523. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  20524. }
  20525. function getValidSource(source, emittedFile, fileReferenceId) {
  20526. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  20527. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  20528. return error(logFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  20529. }
  20530. return source;
  20531. }
  20532. function getAssetFileName(file, referenceId) {
  20533. if (typeof file.fileName !== 'string') {
  20534. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  20535. }
  20536. return file.fileName;
  20537. }
  20538. function getChunkFileName(file, facadeChunkByModule) {
  20539. if (file.fileName) {
  20540. return file.fileName;
  20541. }
  20542. if (facadeChunkByModule) {
  20543. return facadeChunkByModule.get(file.module).getFileName();
  20544. }
  20545. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  20546. }
  20547. class FileEmitter {
  20548. constructor(graph, options, baseFileEmitter) {
  20549. this.graph = graph;
  20550. this.options = options;
  20551. this.facadeChunkByModule = null;
  20552. this.nextIdBase = 1;
  20553. this.output = null;
  20554. this.outputFileEmitters = [];
  20555. this.emitFile = (emittedFile) => {
  20556. if (!hasValidType(emittedFile)) {
  20557. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  20558. }
  20559. if (emittedFile.type === 'prebuilt-chunk') {
  20560. return this.emitPrebuiltChunk(emittedFile);
  20561. }
  20562. if (!hasValidName(emittedFile)) {
  20563. return error(logFailedValidation(`The "fileName" or "name" properties of emitted chunks and assets must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  20564. }
  20565. if (emittedFile.type === 'chunk') {
  20566. return this.emitChunk(emittedFile);
  20567. }
  20568. return this.emitAsset(emittedFile);
  20569. };
  20570. this.finaliseAssets = () => {
  20571. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  20572. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  20573. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  20574. }
  20575. };
  20576. this.getFileName = (fileReferenceId) => {
  20577. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  20578. if (!emittedFile)
  20579. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  20580. if (emittedFile.type === 'chunk') {
  20581. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  20582. }
  20583. if (emittedFile.type === 'prebuilt-chunk') {
  20584. return emittedFile.fileName;
  20585. }
  20586. return getAssetFileName(emittedFile, fileReferenceId);
  20587. };
  20588. this.setAssetSource = (referenceId, requestedSource) => {
  20589. const consumedFile = this.filesByReferenceId.get(referenceId);
  20590. if (!consumedFile)
  20591. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  20592. if (consumedFile.type !== 'asset') {
  20593. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  20594. }
  20595. if (consumedFile.source !== undefined) {
  20596. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  20597. }
  20598. const source = getValidSource(requestedSource, consumedFile, referenceId);
  20599. if (this.output) {
  20600. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  20601. }
  20602. else {
  20603. consumedFile.source = source;
  20604. for (const emitter of this.outputFileEmitters) {
  20605. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  20606. }
  20607. }
  20608. };
  20609. this.setChunkInformation = (facadeChunkByModule) => {
  20610. this.facadeChunkByModule = facadeChunkByModule;
  20611. };
  20612. this.setOutputBundle = (bundle, outputOptions) => {
  20613. const getHash = hasherByType[outputOptions.hashCharacters];
  20614. const output = (this.output = {
  20615. bundle,
  20616. fileNamesBySourceHash: new Map(),
  20617. getHash,
  20618. outputOptions
  20619. });
  20620. for (const emittedFile of this.filesByReferenceId.values()) {
  20621. if (emittedFile.fileName) {
  20622. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  20623. }
  20624. }
  20625. const consumedAssetsByHash = new Map();
  20626. for (const consumedFile of this.filesByReferenceId.values()) {
  20627. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  20628. if (consumedFile.fileName) {
  20629. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  20630. }
  20631. else {
  20632. const sourceHash = getHash(consumedFile.source);
  20633. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  20634. }
  20635. }
  20636. else if (consumedFile.type === 'prebuilt-chunk') {
  20637. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  20638. }
  20639. }
  20640. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  20641. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  20642. }
  20643. };
  20644. this.filesByReferenceId = baseFileEmitter
  20645. ? new Map(baseFileEmitter.filesByReferenceId)
  20646. : new Map();
  20647. baseFileEmitter?.addOutputFileEmitter(this);
  20648. }
  20649. addOutputFileEmitter(outputFileEmitter) {
  20650. this.outputFileEmitters.push(outputFileEmitter);
  20651. }
  20652. assignReferenceId(file, idBase) {
  20653. let referenceId = idBase;
  20654. do {
  20655. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  20656. } while (this.filesByReferenceId.has(referenceId) ||
  20657. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  20658. file.referenceId = referenceId;
  20659. this.filesByReferenceId.set(referenceId, file);
  20660. for (const { filesByReferenceId } of this.outputFileEmitters) {
  20661. filesByReferenceId.set(referenceId, file);
  20662. }
  20663. return referenceId;
  20664. }
  20665. createPrebuiltChunk(prebuiltChunk) {
  20666. return {
  20667. code: prebuiltChunk.code,
  20668. dynamicImports: [],
  20669. exports: prebuiltChunk.exports || [],
  20670. facadeModuleId: null,
  20671. fileName: prebuiltChunk.fileName,
  20672. implicitlyLoadedBefore: [],
  20673. importedBindings: {},
  20674. imports: [],
  20675. isDynamicEntry: false,
  20676. isEntry: false,
  20677. isImplicitEntry: false,
  20678. map: prebuiltChunk.map || null,
  20679. moduleIds: [],
  20680. modules: {},
  20681. name: prebuiltChunk.fileName,
  20682. preliminaryFileName: prebuiltChunk.fileName,
  20683. referencedFiles: [],
  20684. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  20685. type: 'chunk'
  20686. };
  20687. }
  20688. emitAsset(emittedAsset) {
  20689. const source = emittedAsset.source === undefined
  20690. ? undefined
  20691. : getValidSource(emittedAsset.source, emittedAsset, null);
  20692. const originalFileName = emittedAsset.originalFileName || null;
  20693. if (typeof originalFileName === 'string') {
  20694. this.graph.watchFiles[originalFileName] = true;
  20695. }
  20696. const consumedAsset = {
  20697. fileName: emittedAsset.fileName,
  20698. name: emittedAsset.name,
  20699. needsCodeReference: !!emittedAsset.needsCodeReference,
  20700. originalFileName,
  20701. referenceId: '',
  20702. source,
  20703. type: 'asset'
  20704. };
  20705. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  20706. if (this.output) {
  20707. this.emitAssetWithReferenceId(consumedAsset, this.output);
  20708. }
  20709. else {
  20710. for (const fileEmitter of this.outputFileEmitters) {
  20711. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  20712. }
  20713. }
  20714. return referenceId;
  20715. }
  20716. emitAssetWithReferenceId(consumedAsset, output) {
  20717. const { fileName, source } = consumedAsset;
  20718. if (fileName) {
  20719. reserveFileNameInBundle(fileName, output, this.options.onLog);
  20720. }
  20721. if (source !== undefined) {
  20722. this.finalizeAdditionalAsset(consumedAsset, source, output);
  20723. }
  20724. }
  20725. emitChunk(emittedChunk) {
  20726. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  20727. return error(logInvalidRollupPhaseForChunkEmission());
  20728. }
  20729. if (typeof emittedChunk.id !== 'string') {
  20730. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  20731. }
  20732. const consumedChunk = {
  20733. fileName: emittedChunk.fileName,
  20734. module: null,
  20735. name: emittedChunk.name || emittedChunk.id,
  20736. referenceId: '',
  20737. type: 'chunk'
  20738. };
  20739. this.graph.moduleLoader
  20740. .emitChunk(emittedChunk)
  20741. .then(module => (consumedChunk.module = module))
  20742. .catch(() => {
  20743. // Avoid unhandled Promise rejection as the error will be thrown later
  20744. // once module loading has finished
  20745. });
  20746. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  20747. }
  20748. emitPrebuiltChunk(emitPrebuiltChunk) {
  20749. if (typeof emitPrebuiltChunk.code !== 'string') {
  20750. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  20751. }
  20752. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  20753. isPathFragment(emitPrebuiltChunk.fileName)) {
  20754. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  20755. }
  20756. const consumedPrebuiltChunk = {
  20757. code: emitPrebuiltChunk.code,
  20758. exports: emitPrebuiltChunk.exports,
  20759. fileName: emitPrebuiltChunk.fileName,
  20760. map: emitPrebuiltChunk.map,
  20761. referenceId: '',
  20762. type: 'prebuilt-chunk'
  20763. };
  20764. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  20765. if (this.output) {
  20766. this.output.bundle[consumedPrebuiltChunk.fileName] =
  20767. this.createPrebuiltChunk(consumedPrebuiltChunk);
  20768. }
  20769. return referenceId;
  20770. }
  20771. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  20772. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  20773. // Deduplicate assets if an explicit fileName is not provided
  20774. if (!fileName) {
  20775. const sourceHash = getHash(source);
  20776. fileName = fileNamesBySourceHash.get(sourceHash);
  20777. if (!fileName) {
  20778. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  20779. fileNamesBySourceHash.set(sourceHash, fileName);
  20780. }
  20781. }
  20782. // We must not modify the original assets to avoid interaction between outputs
  20783. const assetWithFileName = { ...consumedFile, fileName, source };
  20784. this.filesByReferenceId.set(referenceId, assetWithFileName);
  20785. const existingAsset = bundle[fileName];
  20786. if (existingAsset?.type === 'asset') {
  20787. existingAsset.needsCodeReference &&= needsCodeReference;
  20788. if (name) {
  20789. existingAsset.names.push(name);
  20790. }
  20791. if (originalFileName) {
  20792. existingAsset.originalFileNames.push(originalFileName);
  20793. }
  20794. }
  20795. else {
  20796. const { options } = this;
  20797. bundle[fileName] = {
  20798. fileName,
  20799. get name() {
  20800. // Additionally, this should be non-enumerable in the next major
  20801. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  20802. return name;
  20803. },
  20804. names: name ? [name] : [],
  20805. needsCodeReference,
  20806. get originalFileName() {
  20807. // Additionally, this should be non-enumerable in the next major
  20808. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  20809. return originalFileName;
  20810. },
  20811. originalFileNames: originalFileName ? [originalFileName] : [],
  20812. source,
  20813. type: 'asset'
  20814. };
  20815. }
  20816. }
  20817. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  20818. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  20819. let fileName = '';
  20820. let usedConsumedFile;
  20821. let needsCodeReference = true;
  20822. for (const consumedFile of consumedFiles) {
  20823. needsCodeReference &&= consumedFile.needsCodeReference;
  20824. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  20825. if (!fileName ||
  20826. assetFileName.length < fileName.length ||
  20827. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  20828. fileName = assetFileName;
  20829. usedConsumedFile = consumedFile;
  20830. }
  20831. }
  20832. fileNamesBySourceHash.set(sourceHash, fileName);
  20833. for (const consumedFile of consumedFiles) {
  20834. // We must not modify the original assets to avoid interaction between outputs
  20835. const assetWithFileName = { ...consumedFile, fileName };
  20836. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  20837. }
  20838. const { options } = this;
  20839. bundle[fileName] = {
  20840. fileName,
  20841. get name() {
  20842. // Additionally, this should be non-enumerable in the next major
  20843. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  20844. return usedConsumedFile.name;
  20845. },
  20846. names,
  20847. needsCodeReference,
  20848. get originalFileName() {
  20849. // Additionally, this should be non-enumerable in the next major
  20850. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  20851. return usedConsumedFile.originalFileName;
  20852. },
  20853. originalFileNames,
  20854. source: usedConsumedFile.source,
  20855. type: 'asset'
  20856. };
  20857. }
  20858. }
  20859. function getNamesFromAssets(consumedFiles) {
  20860. const names = [];
  20861. const originalFileNames = [];
  20862. for (const { name, originalFileName } of consumedFiles) {
  20863. if (typeof name === 'string') {
  20864. names.push(name);
  20865. }
  20866. if (originalFileName) {
  20867. originalFileNames.push(originalFileName);
  20868. }
  20869. }
  20870. originalFileNames.sort();
  20871. // Sort by length first and then alphabetically so that the order is stable
  20872. // and the shortest names come first
  20873. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  20874. return { names, originalFileNames };
  20875. }
  20876. function getLogHandler(level, code, logger, pluginName, logLevel) {
  20877. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  20878. return doNothing;
  20879. }
  20880. return (log, pos) => {
  20881. if (pos != null) {
  20882. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  20883. }
  20884. log = normalizeLog(log);
  20885. if (log.code && !log.pluginCode) {
  20886. log.pluginCode = log.code;
  20887. }
  20888. log.code = code;
  20889. log.plugin = pluginName;
  20890. logger(level, log);
  20891. };
  20892. }
  20893. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  20894. const { logLevel, onLog } = options;
  20895. let cacheable = true;
  20896. if (typeof plugin.cacheKey !== 'string') {
  20897. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20898. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  20899. existingPluginNames.has(plugin.name)) {
  20900. cacheable = false;
  20901. }
  20902. else {
  20903. existingPluginNames.add(plugin.name);
  20904. }
  20905. }
  20906. let cacheInstance;
  20907. if (!pluginCache) {
  20908. cacheInstance = NO_CACHE;
  20909. }
  20910. else if (cacheable) {
  20911. const cacheKey = plugin.cacheKey || plugin.name;
  20912. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  20913. }
  20914. else {
  20915. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  20916. }
  20917. return {
  20918. addWatchFile(id) {
  20919. graph.watchFiles[id] = true;
  20920. },
  20921. cache: cacheInstance,
  20922. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  20923. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  20924. error(error_) {
  20925. return error(logPluginError(normalizeLog(error_), plugin.name));
  20926. },
  20927. getFileName: fileEmitter.getFileName,
  20928. getModuleIds: () => graph.modulesById.keys(),
  20929. getModuleInfo: graph.getModuleInfo,
  20930. getWatchFiles: () => Object.keys(graph.watchFiles),
  20931. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  20932. load(resolvedId) {
  20933. return graph.moduleLoader.preloadModule(resolvedId);
  20934. },
  20935. meta: {
  20936. rollupVersion: version,
  20937. watchMode: graph.watchMode
  20938. },
  20939. parse: parseAst,
  20940. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) {
  20941. skipSelf ??= true;
  20942. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  20943. },
  20944. setAssetSource: fileEmitter.setAssetSource,
  20945. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  20946. };
  20947. }
  20948. function ensureArray(items) {
  20949. if (Array.isArray(items)) {
  20950. return items.filter(Boolean);
  20951. }
  20952. if (items) {
  20953. return [items];
  20954. }
  20955. return [];
  20956. }
  20957. function getMatcherString(glob, cwd) {
  20958. if (glob.startsWith('**') || isAbsolute$1(glob)) {
  20959. return normalize(glob);
  20960. }
  20961. const resolved = resolve$1(cwd, glob);
  20962. return normalize(resolved);
  20963. }
  20964. function patternToIdFilter(pattern) {
  20965. if (pattern instanceof RegExp) {
  20966. return (id) => {
  20967. const normalizedId = normalize(id);
  20968. const result = pattern.test(normalizedId);
  20969. pattern.lastIndex = 0;
  20970. return result;
  20971. };
  20972. }
  20973. const cwd = process.cwd();
  20974. const glob = getMatcherString(pattern, cwd);
  20975. const matcher = picomatch(glob, { dot: true });
  20976. return (id) => {
  20977. const normalizedId = normalize(id);
  20978. return matcher(normalizedId);
  20979. };
  20980. }
  20981. function patternToCodeFilter(pattern) {
  20982. if (pattern instanceof RegExp) {
  20983. return (code) => {
  20984. const result = pattern.test(code);
  20985. pattern.lastIndex = 0;
  20986. return result;
  20987. };
  20988. }
  20989. return (code) => code.includes(pattern);
  20990. }
  20991. function createFilter(exclude, include) {
  20992. if (!exclude && !include) {
  20993. return;
  20994. }
  20995. return input => {
  20996. if (exclude?.some(filter => filter(input))) {
  20997. return false;
  20998. }
  20999. if (include?.some(filter => filter(input))) {
  21000. return true;
  21001. }
  21002. return !(include && include.length > 0);
  21003. };
  21004. }
  21005. function normalizeFilter(filter) {
  21006. if (typeof filter === 'string' || filter instanceof RegExp) {
  21007. return {
  21008. include: [filter]
  21009. };
  21010. }
  21011. if (Array.isArray(filter)) {
  21012. return {
  21013. include: filter
  21014. };
  21015. }
  21016. return {
  21017. exclude: filter.exclude ? ensureArray(filter.exclude) : undefined,
  21018. include: filter.include ? ensureArray(filter.include) : undefined
  21019. };
  21020. }
  21021. function createIdFilter(filter) {
  21022. if (!filter)
  21023. return;
  21024. const { exclude, include } = normalizeFilter(filter);
  21025. const excludeFilter = exclude?.map(patternToIdFilter);
  21026. const includeFilter = include?.map(patternToIdFilter);
  21027. return createFilter(excludeFilter, includeFilter);
  21028. }
  21029. function createCodeFilter(filter) {
  21030. if (!filter)
  21031. return;
  21032. const { exclude, include } = normalizeFilter(filter);
  21033. const excludeFilter = exclude?.map(patternToCodeFilter);
  21034. const includeFilter = include?.map(patternToCodeFilter);
  21035. return createFilter(excludeFilter, includeFilter);
  21036. }
  21037. function createFilterForId(filter) {
  21038. const filterFunction = createIdFilter(filter);
  21039. return filterFunction ? id => !!filterFunction(id) : undefined;
  21040. }
  21041. function createFilterForTransform(idFilter, codeFilter) {
  21042. if (!idFilter && !codeFilter)
  21043. return;
  21044. const idFilterFunction = createIdFilter(idFilter);
  21045. const codeFilterFunction = createCodeFilter(codeFilter);
  21046. return (id, code) => {
  21047. let fallback = true;
  21048. if (idFilterFunction) {
  21049. fallback &&= idFilterFunction(id);
  21050. }
  21051. if (!fallback) {
  21052. return false;
  21053. }
  21054. if (codeFilterFunction) {
  21055. fallback &&= codeFilterFunction(code);
  21056. }
  21057. return fallback;
  21058. };
  21059. }
  21060. // This will make sure no input hook is omitted
  21061. const inputHookNames = {
  21062. buildEnd: 1,
  21063. buildStart: 1,
  21064. closeBundle: 1,
  21065. closeWatcher: 1,
  21066. load: 1,
  21067. moduleParsed: 1,
  21068. onLog: 1,
  21069. options: 1,
  21070. resolveDynamicImport: 1,
  21071. resolveId: 1,
  21072. shouldTransformCachedModule: 1,
  21073. transform: 1,
  21074. watchChange: 1
  21075. };
  21076. const inputHooks = Object.keys(inputHookNames);
  21077. class PluginDriver {
  21078. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21079. this.graph = graph;
  21080. this.options = options;
  21081. this.pluginCache = pluginCache;
  21082. this.sortedPlugins = new Map();
  21083. this.unfulfilledActions = new Set();
  21084. this.compiledPluginFilters = {
  21085. idOnlyFilter: new WeakMap(),
  21086. transformFilter: new WeakMap()
  21087. };
  21088. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21089. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21090. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21091. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  21092. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  21093. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21094. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  21095. const existingPluginNames = new Set();
  21096. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21097. plugin,
  21098. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21099. ]));
  21100. if (basePluginDriver) {
  21101. for (const plugin of userPlugins) {
  21102. for (const hook of inputHooks) {
  21103. if (hook in plugin) {
  21104. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  21105. }
  21106. }
  21107. }
  21108. }
  21109. }
  21110. createOutputPluginDriver(plugins) {
  21111. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21112. }
  21113. getUnfulfilledHookActions() {
  21114. return this.unfulfilledActions;
  21115. }
  21116. // chains, first non-null result stops and returns
  21117. hookFirst(hookName, parameters, replaceContext, skipped) {
  21118. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  21119. }
  21120. // chains, first non-null result stops and returns result and last plugin
  21121. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  21122. for (const plugin of this.getSortedPlugins(hookName)) {
  21123. if (skipped?.has(plugin))
  21124. continue;
  21125. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  21126. if (result != null)
  21127. return [result, plugin];
  21128. }
  21129. return null;
  21130. }
  21131. // chains synchronously, first non-null result stops and returns
  21132. hookFirstSync(hookName, parameters, replaceContext) {
  21133. for (const plugin of this.getSortedPlugins(hookName)) {
  21134. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21135. if (result != null)
  21136. return result;
  21137. }
  21138. return null;
  21139. }
  21140. // parallel, ignores returns
  21141. async hookParallel(hookName, parameters, replaceContext) {
  21142. const parallelPromises = [];
  21143. for (const plugin of this.getSortedPlugins(hookName)) {
  21144. if (plugin[hookName].sequential) {
  21145. await Promise.all(parallelPromises);
  21146. parallelPromises.length = 0;
  21147. await this.runHook(hookName, parameters, plugin, replaceContext);
  21148. }
  21149. else {
  21150. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  21151. }
  21152. }
  21153. await Promise.all(parallelPromises);
  21154. }
  21155. // chains, reduces returned value, handling the reduced value as the first hook argument
  21156. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  21157. let promise = Promise.resolve(argument0);
  21158. for (const plugin of this.getSortedPlugins(hookName)) {
  21159. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  21160. }
  21161. return promise;
  21162. }
  21163. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21164. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  21165. for (const plugin of this.getSortedPlugins(hookName)) {
  21166. const parameters = [argument0, ...rest];
  21167. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21168. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  21169. }
  21170. return argument0;
  21171. }
  21172. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  21173. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  21174. const results = [];
  21175. const parallelResults = [];
  21176. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  21177. if (plugin[hookName].sequential) {
  21178. results.push(...(await Promise.all(parallelResults)));
  21179. parallelResults.length = 0;
  21180. results.push(await this.runHook(hookName, parameters, plugin));
  21181. }
  21182. else {
  21183. parallelResults.push(this.runHook(hookName, parameters, plugin));
  21184. }
  21185. }
  21186. results.push(...(await Promise.all(parallelResults)));
  21187. return results.reduce(reducer, await initialValue);
  21188. }
  21189. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21190. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  21191. let accumulator = initialValue;
  21192. for (const plugin of this.getSortedPlugins(hookName)) {
  21193. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21194. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  21195. }
  21196. return accumulator;
  21197. }
  21198. // chains, ignores returns
  21199. hookSeq(hookName, parameters, replaceContext) {
  21200. let promise = Promise.resolve();
  21201. for (const plugin of this.getSortedPlugins(hookName)) {
  21202. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  21203. }
  21204. return promise.then(noReturn);
  21205. }
  21206. getSortedPlugins(hookName, validateHandler) {
  21207. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  21208. }
  21209. // Implementation signature
  21210. runHook(hookName, parameters, plugin, replaceContext) {
  21211. // We always filter for plugins that support the hook before running it
  21212. const hook = plugin[hookName];
  21213. const handler = typeof hook === 'object' ? hook.handler : hook;
  21214. if (typeof hook === 'object' && 'filter' in hook && hook.filter) {
  21215. if (hookName === 'transform') {
  21216. const filter = hook.filter;
  21217. const hookParameters = parameters;
  21218. const compiledFilter = getOrCreate(this.compiledPluginFilters.transformFilter, filter, () => createFilterForTransform(filter.id, filter.code));
  21219. if (compiledFilter && !compiledFilter(hookParameters[1], hookParameters[0])) {
  21220. return Promise.resolve();
  21221. }
  21222. }
  21223. else if (hookName === 'resolveId' || hookName === 'load') {
  21224. const filter = hook.filter;
  21225. const hookParameters = parameters;
  21226. const compiledFilter = getOrCreate(this.compiledPluginFilters.idOnlyFilter, filter, () => createFilterForId(filter.id));
  21227. if (compiledFilter && !compiledFilter(hookParameters[0])) {
  21228. return Promise.resolve();
  21229. }
  21230. }
  21231. }
  21232. let context = this.pluginContexts.get(plugin);
  21233. if (replaceContext) {
  21234. context = replaceContext(context, plugin);
  21235. }
  21236. let action = null;
  21237. return Promise.resolve()
  21238. .then(() => {
  21239. if (typeof handler !== 'function') {
  21240. return handler;
  21241. }
  21242. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21243. const hookResult = handler.apply(context, parameters);
  21244. if (!hookResult?.then) {
  21245. // short circuit for non-thenables and non-Promises
  21246. return hookResult;
  21247. }
  21248. // Track pending hook actions to properly error out when
  21249. // unfulfilled promises cause rollup to abruptly and confusingly
  21250. // exit with a successful 0 return code but without producing any
  21251. // output, errors or warnings.
  21252. action = [plugin.name, hookName, parameters];
  21253. this.unfulfilledActions.add(action);
  21254. // Although it would be more elegant to just return hookResult here
  21255. // and put the .then() handler just above the .catch() handler below,
  21256. // doing so would subtly change the defacto async event dispatch order
  21257. // which at least one test and some plugins in the wild may depend on.
  21258. return Promise.resolve(hookResult).then(result => {
  21259. // action was fulfilled
  21260. this.unfulfilledActions.delete(action);
  21261. return result;
  21262. });
  21263. })
  21264. .catch(error_ => {
  21265. if (action !== null) {
  21266. // action considered to be fulfilled since error being handled
  21267. this.unfulfilledActions.delete(action);
  21268. }
  21269. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  21270. });
  21271. }
  21272. /**
  21273. * Run a sync plugin hook and return the result.
  21274. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21275. * @param args Arguments passed to the plugin hook.
  21276. * @param plugin The acutal plugin
  21277. * @param replaceContext When passed, the plugin context can be overridden.
  21278. */
  21279. runHookSync(hookName, parameters, plugin, replaceContext) {
  21280. const hook = plugin[hookName];
  21281. const handler = typeof hook === 'object' ? hook.handler : hook;
  21282. let context = this.pluginContexts.get(plugin);
  21283. if (replaceContext) {
  21284. context = replaceContext(context, plugin);
  21285. }
  21286. try {
  21287. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21288. return handler.apply(context, parameters);
  21289. }
  21290. catch (error_) {
  21291. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  21292. }
  21293. }
  21294. }
  21295. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  21296. const pre = [];
  21297. const normal = [];
  21298. const post = [];
  21299. for (const plugin of plugins) {
  21300. const hook = plugin[hookName];
  21301. if (hook) {
  21302. if (typeof hook === 'object') {
  21303. validateHandler(hook.handler, hookName, plugin);
  21304. if (hook.order === 'pre') {
  21305. pre.push(plugin);
  21306. continue;
  21307. }
  21308. if (hook.order === 'post') {
  21309. post.push(plugin);
  21310. continue;
  21311. }
  21312. }
  21313. else {
  21314. validateHandler(hook, hookName, plugin);
  21315. }
  21316. normal.push(plugin);
  21317. }
  21318. }
  21319. return [...pre, ...normal, ...post];
  21320. }
  21321. function validateFunctionPluginHandler(handler, hookName, plugin) {
  21322. if (typeof handler !== 'function') {
  21323. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  21324. }
  21325. }
  21326. function validateAddonPluginHandler(handler, hookName, plugin) {
  21327. if (typeof handler !== 'string' && typeof handler !== 'function') {
  21328. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  21329. }
  21330. }
  21331. function noReturn() { }
  21332. class Queue {
  21333. constructor(maxParallel) {
  21334. this.maxParallel = maxParallel;
  21335. this.queue = [];
  21336. this.workerCount = 0;
  21337. }
  21338. run(task) {
  21339. return new Promise((resolve, reject) => {
  21340. this.queue.push({ reject, resolve, task });
  21341. this.work();
  21342. });
  21343. }
  21344. async work() {
  21345. if (this.workerCount >= this.maxParallel)
  21346. return;
  21347. this.workerCount++;
  21348. let entry;
  21349. while ((entry = this.queue.shift())) {
  21350. const { reject, resolve, task } = entry;
  21351. try {
  21352. const result = await task();
  21353. resolve(result);
  21354. }
  21355. catch (error) {
  21356. reject(error);
  21357. }
  21358. }
  21359. this.workerCount--;
  21360. }
  21361. }
  21362. function normalizeEntryModules(entryModules) {
  21363. if (Array.isArray(entryModules)) {
  21364. return entryModules.map(id => ({
  21365. fileName: null,
  21366. id,
  21367. implicitlyLoadedAfter: [],
  21368. importer: undefined,
  21369. name: null
  21370. }));
  21371. }
  21372. return Object.entries(entryModules).map(([name, id]) => ({
  21373. fileName: null,
  21374. id,
  21375. implicitlyLoadedAfter: [],
  21376. importer: undefined,
  21377. name
  21378. }));
  21379. }
  21380. class Graph {
  21381. constructor(options, watcher) {
  21382. this.options = options;
  21383. this.astLru = flru(5);
  21384. this.cachedModules = new Map();
  21385. this.deoptimizationTracker = new EntityPathTracker();
  21386. this.entryModules = [];
  21387. this.modulesById = new Map();
  21388. this.needsTreeshakingPass = false;
  21389. this.newlyIncludedVariableInits = new Set();
  21390. this.phase = BuildPhase.LOAD_AND_PARSE;
  21391. this.scope = new GlobalScope();
  21392. this.watchFiles = Object.create(null);
  21393. this.watchMode = false;
  21394. this.externalModules = [];
  21395. this.implicitEntryModules = [];
  21396. this.modules = [];
  21397. this.getModuleInfo = (moduleId) => {
  21398. const foundModule = this.modulesById.get(moduleId);
  21399. if (!foundModule)
  21400. return null;
  21401. return foundModule.info;
  21402. };
  21403. if (options.cache !== false) {
  21404. if (options.cache?.modules) {
  21405. for (const module of options.cache.modules)
  21406. this.cachedModules.set(module.id, module);
  21407. }
  21408. this.pluginCache = options.cache?.plugins || Object.create(null);
  21409. // increment access counter
  21410. for (const name in this.pluginCache) {
  21411. const cache = this.pluginCache[name];
  21412. for (const value of Object.values(cache))
  21413. value[0]++;
  21414. }
  21415. }
  21416. if (watcher) {
  21417. this.watchMode = true;
  21418. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  21419. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21420. watcher.onCurrentRun('change', handleChange);
  21421. watcher.onCurrentRun('close', handleClose);
  21422. }
  21423. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21424. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21425. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21426. this.pureFunctions = getPureFunctions(options);
  21427. }
  21428. async build() {
  21429. timeStart('generate module graph', 2);
  21430. await this.generateModuleGraph();
  21431. timeEnd('generate module graph', 2);
  21432. timeStart('sort and bind modules', 2);
  21433. this.phase = BuildPhase.ANALYSE;
  21434. this.sortModules();
  21435. timeEnd('sort and bind modules', 2);
  21436. timeStart('mark included statements', 2);
  21437. this.includeStatements();
  21438. timeEnd('mark included statements', 2);
  21439. this.phase = BuildPhase.GENERATE;
  21440. }
  21441. getCache() {
  21442. // handle plugin cache eviction
  21443. for (const name in this.pluginCache) {
  21444. const cache = this.pluginCache[name];
  21445. let allDeleted = true;
  21446. for (const [key, value] of Object.entries(cache)) {
  21447. if (value[0] >= this.options.experimentalCacheExpiry)
  21448. delete cache[key];
  21449. else
  21450. allDeleted = false;
  21451. }
  21452. if (allDeleted)
  21453. delete this.pluginCache[name];
  21454. }
  21455. return {
  21456. modules: this.modules.map(module => module.toJSON()),
  21457. plugins: this.pluginCache
  21458. };
  21459. }
  21460. async generateModuleGraph() {
  21461. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21462. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21463. if (this.entryModules.length === 0) {
  21464. throw new Error('You must supply options.input to rollup');
  21465. }
  21466. for (const module of this.modulesById.values()) {
  21467. module.cacheInfoGetters();
  21468. if (module instanceof Module) {
  21469. this.modules.push(module);
  21470. }
  21471. else {
  21472. this.externalModules.push(module);
  21473. }
  21474. }
  21475. }
  21476. includeStatements() {
  21477. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  21478. for (const module of entryModules) {
  21479. markModuleAndImpureDependenciesAsExecuted(module);
  21480. }
  21481. if (this.options.treeshake) {
  21482. let treeshakingPass = 1;
  21483. this.newlyIncludedVariableInits.clear();
  21484. do {
  21485. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21486. this.needsTreeshakingPass = false;
  21487. for (const module of this.modules) {
  21488. if (module.isExecuted) {
  21489. module.hasTreeShakingPassStarted = true;
  21490. if (module.info.moduleSideEffects === 'no-treeshake') {
  21491. module.includeAllInBundle();
  21492. }
  21493. else {
  21494. module.include();
  21495. }
  21496. for (const entity of this.newlyIncludedVariableInits) {
  21497. this.newlyIncludedVariableInits.delete(entity);
  21498. entity.include(createInclusionContext(), false);
  21499. }
  21500. }
  21501. }
  21502. if (treeshakingPass === 1) {
  21503. // We only include exports after the first pass to avoid issues with
  21504. // the TDZ detection logic
  21505. for (const module of entryModules) {
  21506. if (module.preserveSignature !== false) {
  21507. module.includeAllExports(false);
  21508. this.needsTreeshakingPass = true;
  21509. }
  21510. }
  21511. }
  21512. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21513. } while (this.needsTreeshakingPass);
  21514. }
  21515. else {
  21516. for (const module of this.modules)
  21517. module.includeAllInBundle();
  21518. }
  21519. for (const externalModule of this.externalModules)
  21520. externalModule.warnUnusedImports();
  21521. for (const module of this.implicitEntryModules) {
  21522. for (const dependant of module.implicitlyLoadedAfter) {
  21523. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21524. error(logImplicitDependantIsNotIncluded(dependant));
  21525. }
  21526. }
  21527. }
  21528. }
  21529. sortModules() {
  21530. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21531. for (const cyclePath of cyclePaths) {
  21532. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  21533. }
  21534. this.modules = orderedModules;
  21535. for (const module of this.modules) {
  21536. module.bindReferences();
  21537. }
  21538. this.warnForMissingExports();
  21539. }
  21540. warnForMissingExports() {
  21541. for (const module of this.modules) {
  21542. for (const importDescription of module.importDescriptions.values()) {
  21543. if (importDescription.name !== '*' &&
  21544. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21545. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  21546. }
  21547. }
  21548. }
  21549. }
  21550. }
  21551. function formatAction([pluginName, hookName, parameters]) {
  21552. const action = `(${pluginName}) ${hookName}`;
  21553. const s = JSON.stringify;
  21554. switch (hookName) {
  21555. case 'resolveId': {
  21556. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  21557. }
  21558. case 'load': {
  21559. return `${action} ${s(parameters[0])}`;
  21560. }
  21561. case 'transform': {
  21562. return `${action} ${s(parameters[1])}`;
  21563. }
  21564. case 'shouldTransformCachedModule': {
  21565. return `${action} ${s(parameters[0].id)}`;
  21566. }
  21567. case 'moduleParsed': {
  21568. return `${action} ${s(parameters[0].id)}`;
  21569. }
  21570. }
  21571. return action;
  21572. }
  21573. let handleBeforeExit = null;
  21574. const rejectByPluginDriver = new Map();
  21575. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21576. const emptyEventLoopPromise = new Promise((_, reject) => {
  21577. rejectByPluginDriver.set(pluginDriver, reject);
  21578. if (!handleBeforeExit) {
  21579. // We only ever create a single event listener to avoid max listener and
  21580. // other issues
  21581. handleBeforeExit = () => {
  21582. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  21583. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21584. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21585. [...unfulfilledActions].map(formatAction).join('\n')));
  21586. }
  21587. };
  21588. process$1.once('beforeExit', handleBeforeExit);
  21589. }
  21590. });
  21591. try {
  21592. return await Promise.race([callback(), emptyEventLoopPromise]);
  21593. }
  21594. finally {
  21595. rejectByPluginDriver.delete(pluginDriver);
  21596. if (rejectByPluginDriver.size === 0) {
  21597. process$1.off('beforeExit', handleBeforeExit);
  21598. handleBeforeExit = null;
  21599. }
  21600. }
  21601. }
  21602. async function initWasm() { }
  21603. function getLogger(plugins, onLog, watchMode, logLevel) {
  21604. plugins = getSortedValidatedPlugins('onLog', plugins);
  21605. const minimalPriority = logLevelPriority[logLevel];
  21606. const logger = (level, log, skipped = EMPTY_SET) => {
  21607. augmentLogMessage(log);
  21608. const logPriority = logLevelPriority[level];
  21609. if (logPriority < minimalPriority) {
  21610. return;
  21611. }
  21612. for (const plugin of plugins) {
  21613. if (skipped.has(plugin))
  21614. continue;
  21615. const { onLog: pluginOnLog } = plugin;
  21616. const getLogHandler = (level) => {
  21617. if (logLevelPriority[level] < minimalPriority) {
  21618. return doNothing;
  21619. }
  21620. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  21621. };
  21622. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  21623. if (handler.call({
  21624. debug: getLogHandler(LOGLEVEL_DEBUG),
  21625. error: (log) => error(normalizeLog(log)),
  21626. info: getLogHandler(LOGLEVEL_INFO),
  21627. meta: { rollupVersion: version, watchMode },
  21628. warn: getLogHandler(LOGLEVEL_WARN)
  21629. }, level, log) === false) {
  21630. return;
  21631. }
  21632. }
  21633. onLog(level, log);
  21634. };
  21635. return logger;
  21636. }
  21637. async function normalizeInputOptions(config, watchMode) {
  21638. // These are options that may trigger special warnings or behaviour later
  21639. // if the user did not select an explicit value
  21640. const unsetOptions = new Set();
  21641. const context = config.context ?? 'undefined';
  21642. const plugins = await normalizePluginOption(config.plugins);
  21643. const logLevel = config.logLevel || LOGLEVEL_INFO;
  21644. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  21645. const strictDeprecations = config.strictDeprecations || false;
  21646. const maxParallelFileOps = getMaxParallelFileOps(config);
  21647. const options = {
  21648. cache: getCache(config),
  21649. context,
  21650. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  21651. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  21652. external: getIdMatcher(config.external),
  21653. input: getInput(config),
  21654. jsx: getJsx(config),
  21655. logLevel,
  21656. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  21657. maxParallelFileOps,
  21658. moduleContext: getModuleContext(config, context),
  21659. onLog,
  21660. perf: config.perf || false,
  21661. plugins,
  21662. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  21663. preserveSymlinks: config.preserveSymlinks || false,
  21664. shimMissingExports: config.shimMissingExports || false,
  21665. strictDeprecations,
  21666. treeshake: getTreeshake(config)
  21667. };
  21668. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  21669. return { options, unsetOptions };
  21670. }
  21671. const getCache = (config) => config.cache === true // `true` is the default
  21672. ? undefined
  21673. : config.cache?.cache || config.cache;
  21674. const getIdMatcher = (option) => {
  21675. if (option === true) {
  21676. return () => true;
  21677. }
  21678. if (typeof option === 'function') {
  21679. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  21680. }
  21681. if (option) {
  21682. const ids = new Set();
  21683. const matchers = [];
  21684. for (const value of ensureArray(option)) {
  21685. if (value instanceof RegExp) {
  21686. matchers.push(value);
  21687. }
  21688. else {
  21689. ids.add(value);
  21690. }
  21691. }
  21692. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21693. }
  21694. return () => false;
  21695. };
  21696. const getInput = (config) => {
  21697. const configInput = config.input;
  21698. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21699. };
  21700. const getJsx = (config) => {
  21701. const configJsx = config.jsx;
  21702. if (!configJsx)
  21703. return false;
  21704. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', URL_JSX, 'false, ');
  21705. const { factory, importSource, mode } = configWithPreset;
  21706. switch (mode) {
  21707. case 'automatic': {
  21708. return {
  21709. factory: factory || 'React.createElement',
  21710. importSource: importSource || 'react',
  21711. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  21712. mode: 'automatic'
  21713. };
  21714. }
  21715. case 'preserve': {
  21716. if (importSource && !(factory || configWithPreset.fragment)) {
  21717. error(logInvalidOption('jsx', URL_JSX, 'when preserving JSX and specifying an importSource, you also need to specify a factory or fragment'));
  21718. }
  21719. return {
  21720. factory: factory || null,
  21721. fragment: configWithPreset.fragment || null,
  21722. importSource: importSource || null,
  21723. mode: 'preserve'
  21724. };
  21725. }
  21726. // case 'classic':
  21727. default: {
  21728. if (mode && mode !== 'classic') {
  21729. error(logInvalidOption('jsx.mode', URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  21730. }
  21731. return {
  21732. factory: factory || 'React.createElement',
  21733. fragment: configWithPreset.fragment || 'React.Fragment',
  21734. importSource: importSource || null,
  21735. mode: 'classic'
  21736. };
  21737. }
  21738. }
  21739. };
  21740. const getMaxParallelFileOps = (config) => {
  21741. const maxParallelFileOps = config.maxParallelFileOps;
  21742. if (typeof maxParallelFileOps === 'number') {
  21743. if (maxParallelFileOps <= 0)
  21744. return Infinity;
  21745. return maxParallelFileOps;
  21746. }
  21747. return 20;
  21748. };
  21749. const getModuleContext = (config, context) => {
  21750. const configModuleContext = config.moduleContext;
  21751. if (typeof configModuleContext === 'function') {
  21752. return id => configModuleContext(id) ?? context;
  21753. }
  21754. if (configModuleContext) {
  21755. const contextByModuleId = Object.create(null);
  21756. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21757. contextByModuleId[resolve$1(key)] = moduleContext;
  21758. }
  21759. return id => contextByModuleId[id] ?? context;
  21760. }
  21761. return () => context;
  21762. };
  21763. const getTreeshake = (config) => {
  21764. const configTreeshake = config.treeshake;
  21765. if (configTreeshake === false) {
  21766. return false;
  21767. }
  21768. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  21769. return {
  21770. annotations: configWithPreset.annotations !== false,
  21771. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21772. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  21773. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  21774. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21775. ? 'always'
  21776. : configWithPreset.propertyReadSideEffects !== false,
  21777. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21778. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21779. };
  21780. };
  21781. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  21782. if (typeof moduleSideEffectsOption === 'boolean') {
  21783. return () => moduleSideEffectsOption;
  21784. }
  21785. if (moduleSideEffectsOption === 'no-external') {
  21786. return (_id, external) => !external;
  21787. }
  21788. if (typeof moduleSideEffectsOption === 'function') {
  21789. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  21790. }
  21791. if (Array.isArray(moduleSideEffectsOption)) {
  21792. const ids = new Set(moduleSideEffectsOption);
  21793. return id => ids.has(id);
  21794. }
  21795. if (moduleSideEffectsOption) {
  21796. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  21797. }
  21798. return () => true;
  21799. };
  21800. // https://datatracker.ietf.org/doc/html/rfc2396
  21801. // eslint-disable-next-line no-control-regex
  21802. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  21803. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21804. function sanitizeFileName(name) {
  21805. const match = DRIVE_LETTER_REGEX.exec(name);
  21806. const driveLetter = match ? match[0] : '';
  21807. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21808. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21809. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21810. }
  21811. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21812. // These are options that may trigger special warnings or behaviour later
  21813. // if the user did not select an explicit value
  21814. const unsetOptions = new Set(unsetInputOptions);
  21815. const compact = config.compact || false;
  21816. const format = getFormat(config);
  21817. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21818. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21819. const file = getFile(config, preserveModules, inputOptions);
  21820. const generatedCode = getGeneratedCode(config);
  21821. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  21822. const outputOptions = {
  21823. amd: getAmd(config),
  21824. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  21825. banner: getAddon(config, 'banner'),
  21826. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  21827. compact,
  21828. dir: getDir(config, file),
  21829. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  21830. entryFileNames: getEntryFileNames(config, unsetOptions),
  21831. esModule: config.esModule ?? 'if-default-prop',
  21832. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  21833. exports: getExports(config, unsetOptions),
  21834. extend: config.extend || false,
  21835. externalImportAssertions: externalImportAttributes,
  21836. externalImportAttributes,
  21837. externalLiveBindings: config.externalLiveBindings ?? true,
  21838. file,
  21839. footer: getAddon(config, 'footer'),
  21840. format,
  21841. freeze: config.freeze ?? true,
  21842. generatedCode,
  21843. globals: config.globals || {},
  21844. hashCharacters: config.hashCharacters ?? 'base64',
  21845. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  21846. importAttributesKey: config.importAttributesKey ?? 'assert',
  21847. indent: getIndent(config, compact),
  21848. inlineDynamicImports,
  21849. interop: getInterop(config),
  21850. intro: getAddon(config, 'intro'),
  21851. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  21852. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21853. name: config.name,
  21854. noConflict: config.noConflict || false,
  21855. outro: getAddon(config, 'outro'),
  21856. paths: config.paths || {},
  21857. plugins: await normalizePluginOption(config.plugins),
  21858. preserveModules,
  21859. preserveModulesRoot: getPreserveModulesRoot(config),
  21860. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  21861. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21862. ? config.sanitizeFileName
  21863. : config.sanitizeFileName === false
  21864. ? id => id
  21865. : sanitizeFileName,
  21866. sourcemap: config.sourcemap || false,
  21867. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21868. sourcemapDebugIds: config.sourcemapDebugIds || false,
  21869. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21870. sourcemapFile: config.sourcemapFile,
  21871. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  21872. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  21873. ? config.sourcemapIgnoreList
  21874. : config.sourcemapIgnoreList === false
  21875. ? () => false
  21876. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  21877. sourcemapPathTransform: config.sourcemapPathTransform,
  21878. strict: config.strict ?? true,
  21879. systemNullSetters: config.systemNullSetters ?? true,
  21880. validate: config.validate || false,
  21881. virtualDirname: config.virtualDirname || '_virtual'
  21882. };
  21883. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  21884. return { options: outputOptions, unsetOptions };
  21885. }
  21886. const getFile = (config, preserveModules, inputOptions) => {
  21887. const { file } = config;
  21888. if (typeof file === 'string') {
  21889. if (preserveModules) {
  21890. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  21891. }
  21892. if (!Array.isArray(inputOptions.input))
  21893. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  21894. }
  21895. return file;
  21896. };
  21897. const getFormat = (config) => {
  21898. const configFormat = config.format;
  21899. switch (configFormat) {
  21900. case undefined:
  21901. case 'es':
  21902. case 'esm':
  21903. case 'module': {
  21904. return 'es';
  21905. }
  21906. case 'cjs':
  21907. case 'commonjs': {
  21908. return 'cjs';
  21909. }
  21910. case 'system':
  21911. case 'systemjs': {
  21912. return 'system';
  21913. }
  21914. case 'amd':
  21915. case 'iife':
  21916. case 'umd': {
  21917. return configFormat;
  21918. }
  21919. default: {
  21920. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  21921. }
  21922. }
  21923. };
  21924. const getInlineDynamicImports = (config, inputOptions) => {
  21925. const inlineDynamicImports = config.inlineDynamicImports || false;
  21926. const { input } = inputOptions;
  21927. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  21928. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  21929. }
  21930. return inlineDynamicImports;
  21931. };
  21932. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  21933. const preserveModules = config.preserveModules || false;
  21934. if (preserveModules) {
  21935. if (inlineDynamicImports) {
  21936. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  21937. }
  21938. if (inputOptions.preserveEntrySignatures === false) {
  21939. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  21940. }
  21941. }
  21942. return preserveModules;
  21943. };
  21944. const getPreserveModulesRoot = (config) => {
  21945. const { preserveModulesRoot } = config;
  21946. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  21947. return undefined;
  21948. }
  21949. return resolve$1(preserveModulesRoot);
  21950. };
  21951. const getAmd = (config) => {
  21952. const mergedOption = {
  21953. autoId: false,
  21954. basePath: '',
  21955. define: 'define',
  21956. forceJsExtensionForImports: false,
  21957. ...config.amd
  21958. };
  21959. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  21960. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  21961. }
  21962. if (mergedOption.basePath && !mergedOption.autoId) {
  21963. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  21964. }
  21965. return mergedOption.autoId
  21966. ? {
  21967. autoId: true,
  21968. basePath: mergedOption.basePath,
  21969. define: mergedOption.define,
  21970. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  21971. }
  21972. : {
  21973. autoId: false,
  21974. define: mergedOption.define,
  21975. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  21976. id: mergedOption.id
  21977. };
  21978. };
  21979. const getAddon = (config, name) => {
  21980. const configAddon = config[name];
  21981. if (typeof configAddon === 'function') {
  21982. return configAddon;
  21983. }
  21984. return () => configAddon || '';
  21985. };
  21986. const getDir = (config, file) => {
  21987. const { dir } = config;
  21988. if (typeof dir === 'string' && typeof file === 'string') {
  21989. return error(logInvalidOption('output.dir', URL_OUTPUT_DIR, 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  21990. }
  21991. return dir;
  21992. };
  21993. const getEntryFileNames = (config, unsetOptions) => {
  21994. const configEntryFileNames = config.entryFileNames;
  21995. if (configEntryFileNames == null) {
  21996. unsetOptions.add('entryFileNames');
  21997. }
  21998. return configEntryFileNames ?? '[name].js';
  21999. };
  22000. function getExports(config, unsetOptions) {
  22001. const configExports = config.exports;
  22002. if (configExports == null) {
  22003. unsetOptions.add('exports');
  22004. }
  22005. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22006. return error(logInvalidExportOptionValue(configExports));
  22007. }
  22008. return configExports || 'auto';
  22009. }
  22010. const getExternalImportAttributes = (config, inputOptions) => {
  22011. if (config.externalImportAssertions != undefined) {
  22012. warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  22013. }
  22014. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  22015. };
  22016. const getGeneratedCode = (config) => {
  22017. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  22018. return {
  22019. arrowFunctions: configWithPreset.arrowFunctions === true,
  22020. constBindings: configWithPreset.constBindings === true,
  22021. objectShorthand: configWithPreset.objectShorthand === true,
  22022. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  22023. symbols: configWithPreset.symbols === true
  22024. };
  22025. };
  22026. const getIndent = (config, compact) => {
  22027. if (compact) {
  22028. return '';
  22029. }
  22030. const configIndent = config.indent;
  22031. return configIndent === false ? '' : (configIndent ?? true);
  22032. };
  22033. const ALLOWED_INTEROP_TYPES = new Set([
  22034. 'compat',
  22035. 'auto',
  22036. 'esModule',
  22037. 'default',
  22038. 'defaultOnly'
  22039. ]);
  22040. const getInterop = (config) => {
  22041. const configInterop = config.interop;
  22042. if (typeof configInterop === 'function') {
  22043. const interopPerId = Object.create(null);
  22044. let defaultInterop = null;
  22045. return id => id === null
  22046. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22047. : id in interopPerId
  22048. ? interopPerId[id]
  22049. : validateInterop((interopPerId[id] = configInterop(id)));
  22050. }
  22051. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  22052. };
  22053. const validateInterop = (interop) => {
  22054. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22055. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP, `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22056. }
  22057. return interop;
  22058. };
  22059. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  22060. const configManualChunks = config.manualChunks;
  22061. if (configManualChunks) {
  22062. if (inlineDynamicImports) {
  22063. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  22064. }
  22065. if (preserveModules) {
  22066. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  22067. }
  22068. }
  22069. return configManualChunks || {};
  22070. };
  22071. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  22072. const getSourcemapFileNames = (config, unsetOptions) => {
  22073. const configSourcemapFileNames = config.sourcemapFileNames;
  22074. if (configSourcemapFileNames == null) {
  22075. unsetOptions.add('sourcemapFileNames');
  22076. }
  22077. return configSourcemapFileNames;
  22078. };
  22079. const getSourcemapBaseUrl = (config) => {
  22080. const { sourcemapBaseUrl } = config;
  22081. if (sourcemapBaseUrl) {
  22082. if (isValidUrl(sourcemapBaseUrl)) {
  22083. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  22084. }
  22085. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22086. }
  22087. };
  22088. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  22089. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  22090. function rollup(rawInputOptions) {
  22091. return rollupInternal(rawInputOptions, null);
  22092. }
  22093. async function rollupInternal(rawInputOptions, watcher) {
  22094. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22095. initialiseTimers(inputOptions);
  22096. await initWasm();
  22097. const graph = new Graph(inputOptions, watcher);
  22098. // remove the cache object from the memory after graph creation (cache is not used anymore)
  22099. const useCache = rawInputOptions.cache !== false;
  22100. if (rawInputOptions.cache) {
  22101. inputOptions.cache = undefined;
  22102. rawInputOptions.cache = undefined;
  22103. }
  22104. timeStart('BUILD', 1);
  22105. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22106. try {
  22107. timeStart('initialize', 2);
  22108. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22109. timeEnd('initialize', 2);
  22110. await graph.build();
  22111. }
  22112. catch (error_) {
  22113. const watchFiles = Object.keys(graph.watchFiles);
  22114. if (watchFiles.length > 0) {
  22115. error_.watchFiles = watchFiles;
  22116. }
  22117. try {
  22118. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  22119. }
  22120. catch (buildEndError) {
  22121. // Create a compound error object to include both errors, based on the original error
  22122. const compoundError = getRollupError({
  22123. ...error_,
  22124. message: `There was an error during the build:\n ${error_.message}\nAdditionally, handling the error in the 'buildEnd' hook caused the following error:\n ${buildEndError.message}`
  22125. });
  22126. await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
  22127. throw compoundError;
  22128. }
  22129. await graph.pluginDriver.hookParallel('closeBundle', [error_]);
  22130. throw error_;
  22131. }
  22132. try {
  22133. await graph.pluginDriver.hookParallel('buildEnd', []);
  22134. }
  22135. catch (buildEndError) {
  22136. await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
  22137. throw buildEndError;
  22138. }
  22139. });
  22140. timeEnd('BUILD', 1);
  22141. const result = {
  22142. cache: useCache ? graph.getCache() : undefined,
  22143. async close() {
  22144. if (result.closed)
  22145. return;
  22146. result.closed = true;
  22147. await graph.pluginDriver.hookParallel('closeBundle', []);
  22148. },
  22149. closed: false,
  22150. async [Symbol.asyncDispose]() {
  22151. await this.close();
  22152. },
  22153. async generate(rawOutputOptions) {
  22154. if (result.closed)
  22155. return error(logAlreadyClosed());
  22156. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22157. },
  22158. get watchFiles() {
  22159. return Object.keys(graph.watchFiles);
  22160. },
  22161. async write(rawOutputOptions) {
  22162. if (result.closed)
  22163. return error(logAlreadyClosed());
  22164. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22165. }
  22166. };
  22167. if (inputOptions.perf)
  22168. result.getTimings = getTimings;
  22169. return result;
  22170. }
  22171. async function getInputOptions(initialInputOptions, watchMode) {
  22172. if (!initialInputOptions) {
  22173. throw new Error('You must supply an options object to rollup');
  22174. }
  22175. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  22176. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  22177. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22178. return { options, unsetOptions };
  22179. }
  22180. async function getProcessedInputOptions(inputOptions, watchMode) {
  22181. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  22182. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  22183. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  22184. for (const plugin of plugins) {
  22185. const { name, options } = plugin;
  22186. const handler = 'handler' in options ? options.handler : options;
  22187. const processedOptions = await handler.call({
  22188. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  22189. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  22190. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  22191. meta: { rollupVersion: version, watchMode },
  22192. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  22193. }, inputOptions);
  22194. if (processedOptions) {
  22195. inputOptions = processedOptions;
  22196. }
  22197. }
  22198. return inputOptions;
  22199. }
  22200. function normalizePlugins(plugins, anonymousPrefix) {
  22201. for (const [index, plugin] of plugins.entries()) {
  22202. if (!plugin.name) {
  22203. plugin.name = `${anonymousPrefix}${index + 1}`;
  22204. }
  22205. }
  22206. }
  22207. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22208. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22209. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22210. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22211. const generated = await bundle.generate(isWrite);
  22212. if (isWrite) {
  22213. timeStart('WRITE', 1);
  22214. if (!outputOptions.dir && !outputOptions.file) {
  22215. return error(logMissingFileOrDirOption());
  22216. }
  22217. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22218. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22219. timeEnd('WRITE', 1);
  22220. }
  22221. return createOutput(generated);
  22222. });
  22223. }
  22224. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22225. if (!rawOutputOptions) {
  22226. throw new Error('You must supply an options object');
  22227. }
  22228. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  22229. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22230. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22231. return {
  22232. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  22233. outputPluginDriver
  22234. };
  22235. }
  22236. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22237. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22238. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  22239. return {
  22240. ...pluginContext,
  22241. emitFile: emitError,
  22242. setAssetSource: emitError
  22243. };
  22244. }), inputOptions, unsetInputOptions);
  22245. }
  22246. function createOutput(outputBundle) {
  22247. return {
  22248. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22249. };
  22250. }
  22251. var SortingFileType;
  22252. (function (SortingFileType) {
  22253. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22254. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22255. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22256. })(SortingFileType || (SortingFileType = {}));
  22257. function getSortingFileType(file) {
  22258. if (file.type === 'asset') {
  22259. return SortingFileType.ASSET;
  22260. }
  22261. if (file.isEntry) {
  22262. return SortingFileType.ENTRY_CHUNK;
  22263. }
  22264. return SortingFileType.SECONDARY_CHUNK;
  22265. }
  22266. async function writeOutputFile(outputFile, outputOptions) {
  22267. const fileName = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  22268. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22269. await mkdir(dirname(fileName), { recursive: true });
  22270. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  22271. }
  22272. /**
  22273. * Auxiliary function for defining rollup configuration
  22274. * Mainly to facilitate IDE code prompts, after all, export default does not
  22275. * prompt, even if you add @type annotations, it is not accurate
  22276. * @param options
  22277. */
  22278. function defineConfig(options) {
  22279. return options;
  22280. }
  22281. var picocolors = {exports: {}};
  22282. var hasRequiredPicocolors;
  22283. function requirePicocolors () {
  22284. if (hasRequiredPicocolors) return picocolors.exports;
  22285. hasRequiredPicocolors = 1;
  22286. let p = process || {}, argv = p.argv || [], env = p.env || {};
  22287. let isColorSupported =
  22288. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  22289. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  22290. let formatter = (open, close, replace = open) =>
  22291. input => {
  22292. let string = "" + input, index = string.indexOf(close, open.length);
  22293. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  22294. };
  22295. let replaceClose = (string, close, replace, index) => {
  22296. let result = "", cursor = 0;
  22297. do {
  22298. result += string.substring(cursor, index) + replace;
  22299. cursor = index + close.length;
  22300. index = string.indexOf(close, cursor);
  22301. } while (~index)
  22302. return result + string.substring(cursor)
  22303. };
  22304. let createColors = (enabled = isColorSupported) => {
  22305. let f = enabled ? formatter : () => String;
  22306. return {
  22307. isColorSupported: enabled,
  22308. reset: f("\x1b[0m", "\x1b[0m"),
  22309. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  22310. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  22311. italic: f("\x1b[3m", "\x1b[23m"),
  22312. underline: f("\x1b[4m", "\x1b[24m"),
  22313. inverse: f("\x1b[7m", "\x1b[27m"),
  22314. hidden: f("\x1b[8m", "\x1b[28m"),
  22315. strikethrough: f("\x1b[9m", "\x1b[29m"),
  22316. black: f("\x1b[30m", "\x1b[39m"),
  22317. red: f("\x1b[31m", "\x1b[39m"),
  22318. green: f("\x1b[32m", "\x1b[39m"),
  22319. yellow: f("\x1b[33m", "\x1b[39m"),
  22320. blue: f("\x1b[34m", "\x1b[39m"),
  22321. magenta: f("\x1b[35m", "\x1b[39m"),
  22322. cyan: f("\x1b[36m", "\x1b[39m"),
  22323. white: f("\x1b[37m", "\x1b[39m"),
  22324. gray: f("\x1b[90m", "\x1b[39m"),
  22325. bgBlack: f("\x1b[40m", "\x1b[49m"),
  22326. bgRed: f("\x1b[41m", "\x1b[49m"),
  22327. bgGreen: f("\x1b[42m", "\x1b[49m"),
  22328. bgYellow: f("\x1b[43m", "\x1b[49m"),
  22329. bgBlue: f("\x1b[44m", "\x1b[49m"),
  22330. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  22331. bgCyan: f("\x1b[46m", "\x1b[49m"),
  22332. bgWhite: f("\x1b[47m", "\x1b[49m"),
  22333. blackBright: f("\x1b[90m", "\x1b[39m"),
  22334. redBright: f("\x1b[91m", "\x1b[39m"),
  22335. greenBright: f("\x1b[92m", "\x1b[39m"),
  22336. yellowBright: f("\x1b[93m", "\x1b[39m"),
  22337. blueBright: f("\x1b[94m", "\x1b[39m"),
  22338. magentaBright: f("\x1b[95m", "\x1b[39m"),
  22339. cyanBright: f("\x1b[96m", "\x1b[39m"),
  22340. whiteBright: f("\x1b[97m", "\x1b[39m"),
  22341. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  22342. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  22343. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  22344. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  22345. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  22346. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  22347. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  22348. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  22349. }
  22350. };
  22351. picocolors.exports = createColors();
  22352. picocolors.exports.createColors = createColors;
  22353. return picocolors.exports;
  22354. }
  22355. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  22356. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  22357. // @see https://no-color.org
  22358. // @see https://www.npmjs.com/package/chalk
  22359. const { bold, cyan, dim, red} = pc.createColors(env.FORCE_COLOR !== '0' && !env.NO_COLOR);
  22360. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  22361. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  22362. function handleError(error, recover = false) {
  22363. const name = error.name || error.cause?.name;
  22364. const nameSection = name ? `${name}: ` : '';
  22365. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  22366. const message = `${pluginSection}${nameSection}${error.message}`;
  22367. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  22368. if (error.url) {
  22369. outputLines.push(cyan(error.url));
  22370. }
  22371. if (error.loc) {
  22372. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  22373. }
  22374. else if (error.id) {
  22375. outputLines.push(relativeId(error.id));
  22376. }
  22377. if (error.frame) {
  22378. outputLines.push(dim(error.frame));
  22379. }
  22380. if (error.stack) {
  22381. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  22382. }
  22383. // ES2022: Error.prototype.cause is optional
  22384. if (error.cause) {
  22385. let cause = error.cause;
  22386. const causeErrorLines = [];
  22387. let indent = '';
  22388. while (cause) {
  22389. indent += ' ';
  22390. const message = cause.stack || cause;
  22391. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  22392. cause = cause.cause;
  22393. }
  22394. outputLines.push(dim(causeErrorLines.join('\n')));
  22395. }
  22396. outputLines.push('', '');
  22397. stderr(outputLines.join('\n'));
  22398. if (!recover)
  22399. process$1.exit(1);
  22400. }
  22401. const commandAliases = {
  22402. c: 'config',
  22403. d: 'dir',
  22404. e: 'external',
  22405. f: 'format',
  22406. g: 'globals',
  22407. h: 'help',
  22408. i: 'input',
  22409. m: 'sourcemap',
  22410. n: 'name',
  22411. o: 'file',
  22412. p: 'plugin',
  22413. v: 'version',
  22414. w: 'watch'
  22415. };
  22416. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  22417. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  22418. const command = getCommandOptions(rawCommandOptions);
  22419. const plugins = await normalizePluginOption(config.plugins);
  22420. const logLevel = config.logLevel || LOGLEVEL_INFO;
  22421. const onLog = getOnLog(config, logLevel, printLog);
  22422. const log = getLogger(plugins, onLog, watchMode, logLevel);
  22423. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  22424. if (command.output) {
  22425. Object.assign(command, command.output);
  22426. }
  22427. const outputOptionsArray = ensureArray(config.output);
  22428. if (outputOptionsArray.length === 0)
  22429. outputOptionsArray.push({});
  22430. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  22431. warnUnknownOptions(command, [
  22432. ...Object.keys(inputOptions),
  22433. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  22434. ...Object.keys(commandAliases),
  22435. 'bundleConfigAsCjs',
  22436. 'config',
  22437. 'configImportAttributesKey',
  22438. 'configPlugin',
  22439. 'environment',
  22440. 'failAfterWarnings',
  22441. 'filterLogs',
  22442. 'forceExit',
  22443. 'plugin',
  22444. 'silent',
  22445. 'stdin',
  22446. 'waitForBundleInput'
  22447. ], 'CLI flags', log, /^_$|output$|config/);
  22448. inputOptions.output = outputOptions;
  22449. return inputOptions;
  22450. }
  22451. function getCommandOptions(rawCommandOptions) {
  22452. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  22453. ? rawCommandOptions.external.split(',')
  22454. : [];
  22455. return {
  22456. ...rawCommandOptions,
  22457. external,
  22458. globals: typeof rawCommandOptions.globals === 'string'
  22459. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  22460. const [id, variableName] = globalDefinition.split(':');
  22461. globals[id] = variableName;
  22462. if (!external.includes(id)) {
  22463. external.push(id);
  22464. }
  22465. return globals;
  22466. }, Object.create(null))
  22467. : undefined
  22468. };
  22469. }
  22470. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  22471. const getOption = (name) => overrides[name] ?? config[name];
  22472. const inputOptions = {
  22473. cache: config.cache,
  22474. context: getOption('context'),
  22475. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  22476. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  22477. external: getExternal(config, overrides),
  22478. input: getOption('input') || [],
  22479. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', URL_JSX, 'false, ')),
  22480. logLevel: getOption('logLevel'),
  22481. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  22482. maxParallelFileOps: getOption('maxParallelFileOps'),
  22483. moduleContext: getOption('moduleContext'),
  22484. onLog,
  22485. onwarn: undefined,
  22486. perf: getOption('perf'),
  22487. plugins,
  22488. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  22489. preserveSymlinks: getOption('preserveSymlinks'),
  22490. shimMissingExports: getOption('shimMissingExports'),
  22491. strictDeprecations: getOption('strictDeprecations'),
  22492. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  22493. watch: getWatch(config, overrides)
  22494. };
  22495. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  22496. return inputOptions;
  22497. }
  22498. const getExternal = (config, overrides) => {
  22499. const configExternal = config.external;
  22500. return typeof configExternal === 'function'
  22501. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  22502. : [...ensureArray(configExternal), ...overrides.external];
  22503. };
  22504. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  22505. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  22506. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  22507. if (commandOption !== undefined) {
  22508. return commandOption && { ...configOption, ...commandOption };
  22509. }
  22510. return configOption;
  22511. };
  22512. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  22513. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  22514. if (!optionValue) {
  22515. return optionValue;
  22516. }
  22517. if (Array.isArray(optionValue)) {
  22518. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  22519. }
  22520. return objectifyValue(optionValue);
  22521. };
  22522. async function mergeOutputOptions(config, overrides, log) {
  22523. const getOption = (name) => overrides[name] ?? config[name];
  22524. const outputOptions = {
  22525. amd: getObjectOption(config, overrides, 'amd'),
  22526. assetFileNames: getOption('assetFileNames'),
  22527. banner: getOption('banner'),
  22528. chunkFileNames: getOption('chunkFileNames'),
  22529. compact: getOption('compact'),
  22530. dir: getOption('dir'),
  22531. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  22532. entryFileNames: getOption('entryFileNames'),
  22533. esModule: getOption('esModule'),
  22534. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  22535. exports: getOption('exports'),
  22536. extend: getOption('extend'),
  22537. externalImportAssertions: getOption('externalImportAssertions'),
  22538. externalImportAttributes: getOption('externalImportAttributes'),
  22539. externalLiveBindings: getOption('externalLiveBindings'),
  22540. file: getOption('file'),
  22541. footer: getOption('footer'),
  22542. format: getOption('format'),
  22543. freeze: getOption('freeze'),
  22544. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  22545. globals: getOption('globals'),
  22546. hashCharacters: getOption('hashCharacters'),
  22547. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  22548. importAttributesKey: getOption('importAttributesKey'),
  22549. indent: getOption('indent'),
  22550. inlineDynamicImports: getOption('inlineDynamicImports'),
  22551. interop: getOption('interop'),
  22552. intro: getOption('intro'),
  22553. manualChunks: getOption('manualChunks'),
  22554. minifyInternalExports: getOption('minifyInternalExports'),
  22555. name: getOption('name'),
  22556. noConflict: getOption('noConflict'),
  22557. outro: getOption('outro'),
  22558. paths: getOption('paths'),
  22559. plugins: await normalizePluginOption(config.plugins),
  22560. preserveModules: getOption('preserveModules'),
  22561. preserveModulesRoot: getOption('preserveModulesRoot'),
  22562. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  22563. sanitizeFileName: getOption('sanitizeFileName'),
  22564. sourcemap: getOption('sourcemap'),
  22565. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  22566. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  22567. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  22568. sourcemapFile: getOption('sourcemapFile'),
  22569. sourcemapFileNames: getOption('sourcemapFileNames'),
  22570. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  22571. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  22572. strict: getOption('strict'),
  22573. systemNullSetters: getOption('systemNullSetters'),
  22574. validate: getOption('validate'),
  22575. virtualDirname: getOption('virtualDirname')
  22576. };
  22577. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  22578. return outputOptions;
  22579. }
  22580. class WatchEmitter {
  22581. constructor() {
  22582. this.currentHandlers = Object.create(null);
  22583. this.persistentHandlers = Object.create(null);
  22584. }
  22585. // Will be overwritten by Rollup
  22586. async close() { }
  22587. emit(event, ...parameters) {
  22588. return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
  22589. }
  22590. off(event, listener) {
  22591. const listeners = this.persistentHandlers[event];
  22592. if (listeners) {
  22593. // A hack stolen from "mitt": ">>> 0" does not change numbers >= 0, but -1
  22594. // (which would remove the last array element if used unchanged) is turned
  22595. // into max_int, which is outside the array and does not change anything.
  22596. listeners.splice(listeners.indexOf(listener) >>> 0, 1);
  22597. }
  22598. return this;
  22599. }
  22600. on(event, listener) {
  22601. this.getPersistentHandlers(event).push(listener);
  22602. return this;
  22603. }
  22604. onCurrentRun(event, listener) {
  22605. this.getCurrentHandlers(event).push(listener);
  22606. return this;
  22607. }
  22608. once(event, listener) {
  22609. const selfRemovingListener = (...parameters) => {
  22610. this.off(event, selfRemovingListener);
  22611. return listener(...parameters);
  22612. };
  22613. this.on(event, selfRemovingListener);
  22614. return this;
  22615. }
  22616. removeAllListeners() {
  22617. this.removeListenersForCurrentRun();
  22618. this.persistentHandlers = Object.create(null);
  22619. return this;
  22620. }
  22621. removeListenersForCurrentRun() {
  22622. this.currentHandlers = Object.create(null);
  22623. return this;
  22624. }
  22625. getCurrentHandlers(event) {
  22626. return this.currentHandlers[event] || (this.currentHandlers[event] = []);
  22627. }
  22628. getPersistentHandlers(event) {
  22629. return this.persistentHandlers[event] || (this.persistentHandlers[event] = []);
  22630. }
  22631. }
  22632. let fsEvents;
  22633. let fsEventsImportError;
  22634. async function loadFsEvents() {
  22635. try {
  22636. ({ default: fsEvents } = await import('fsevents'));
  22637. }
  22638. catch (error) {
  22639. fsEventsImportError = error;
  22640. }
  22641. }
  22642. // A call to this function will be injected into the chokidar code
  22643. function getFsEvents() {
  22644. if (fsEventsImportError)
  22645. throw fsEventsImportError;
  22646. return fsEvents;
  22647. }
  22648. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  22649. __proto__: null,
  22650. getFsEvents,
  22651. loadFsEvents
  22652. }, Symbol.toStringTag, { value: 'Module' });
  22653. function watch(configs) {
  22654. const emitter = new WatchEmitter();
  22655. watchInternal(configs, emitter).catch(error => {
  22656. handleError(error);
  22657. });
  22658. return emitter;
  22659. }
  22660. async function watchInternal(configs, emitter) {
  22661. const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config, true)));
  22662. const watchOptionsList = optionsList.filter(config => config.watch !== false);
  22663. if (watchOptionsList.length === 0) {
  22664. return error(logInvalidOption('watch', URL_WATCH, 'there must be at least one config where "watch" is not set to "false"'));
  22665. }
  22666. await loadFsEvents();
  22667. const { Watcher } = await import('./watch.js');
  22668. new Watcher(watchOptionsList, emitter);
  22669. }
  22670. export { createFilter$1 as createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, getDefaultExportFromCjs, rollup, rollupInternal, version, watch };