NormalModule.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const parseJson = require("json-parse-even-better-errors");
  7. const { getContext, runLoaders } = require("loader-runner");
  8. const querystring = require("querystring");
  9. const { HookMap, SyncHook, AsyncSeriesBailHook } = require("tapable");
  10. const {
  11. CachedSource,
  12. OriginalSource,
  13. RawSource,
  14. SourceMapSource
  15. } = require("webpack-sources");
  16. const Compilation = require("./Compilation");
  17. const HookWebpackError = require("./HookWebpackError");
  18. const Module = require("./Module");
  19. const ModuleBuildError = require("./ModuleBuildError");
  20. const ModuleError = require("./ModuleError");
  21. const ModuleGraphConnection = require("./ModuleGraphConnection");
  22. const ModuleParseError = require("./ModuleParseError");
  23. const { JAVASCRIPT_MODULE_TYPE_AUTO } = require("./ModuleTypeConstants");
  24. const ModuleWarning = require("./ModuleWarning");
  25. const RuntimeGlobals = require("./RuntimeGlobals");
  26. const UnhandledSchemeError = require("./UnhandledSchemeError");
  27. const WebpackError = require("./WebpackError");
  28. const formatLocation = require("./formatLocation");
  29. const LazySet = require("./util/LazySet");
  30. const { isSubset } = require("./util/SetHelpers");
  31. const { getScheme } = require("./util/URLAbsoluteSpecifier");
  32. const {
  33. compareLocations,
  34. concatComparators,
  35. compareSelect,
  36. keepOriginalOrder
  37. } = require("./util/comparators");
  38. const createHash = require("./util/createHash");
  39. const { createFakeHook } = require("./util/deprecation");
  40. const { join } = require("./util/fs");
  41. const {
  42. contextify,
  43. absolutify,
  44. makePathsRelative
  45. } = require("./util/identifier");
  46. const makeSerializable = require("./util/makeSerializable");
  47. const memoize = require("./util/memoize");
  48. /** @typedef {import("webpack-sources").Source} Source */
  49. /** @typedef {import("../declarations/WebpackOptions").Mode} Mode */
  50. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  51. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  52. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  53. /** @typedef {import("./Compiler")} Compiler */
  54. /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
  55. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  56. /** @typedef {import("./Generator")} Generator */
  57. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  58. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  59. /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
  60. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  61. /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
  62. /** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */
  63. /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
  64. /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
  65. /** @typedef {import("./Module").SourceTypes} SourceTypes */
  66. /** @typedef {import("./Module").UnsafeCacheData} UnsafeCacheData */
  67. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  68. /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
  69. /** @typedef {import("./ModuleTypeConstants").JavaScriptModuleTypes} JavaScriptModuleTypes */
  70. /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
  71. /** @typedef {import("./Parser")} Parser */
  72. /** @typedef {import("./RequestShortener")} RequestShortener */
  73. /** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */
  74. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  75. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  76. /** @typedef {import("./logging/Logger").Logger} WebpackLogger */
  77. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  78. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  79. /** @typedef {import("./util/Hash")} Hash */
  80. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  81. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  82. /** @typedef {{[k: string]: any}} ParserOptions */
  83. /** @typedef {{[k: string]: any}} GeneratorOptions */
  84. /** @typedef {UnsafeCacheData & { parser: undefined | Parser, parserOptions: undefined | ParserOptions, generator: undefined | Generator, generatorOptions: undefined | GeneratorOptions }} NormalModuleUnsafeCacheData */
  85. /**
  86. * @typedef {object} SourceMap
  87. * @property {number} version
  88. * @property {string[]} sources
  89. * @property {string} mappings
  90. * @property {string=} file
  91. * @property {string=} sourceRoot
  92. * @property {string[]=} sourcesContent
  93. * @property {string[]=} names
  94. */
  95. const getInvalidDependenciesModuleWarning = memoize(() =>
  96. require("./InvalidDependenciesModuleWarning")
  97. );
  98. const getValidate = memoize(() => require("schema-utils").validate);
  99. const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
  100. /**
  101. * @typedef {object} LoaderItem
  102. * @property {string} loader
  103. * @property {any} options
  104. * @property {string?} ident
  105. * @property {string?} type
  106. */
  107. /**
  108. * @param {string} context absolute context path
  109. * @param {string} source a source path
  110. * @param {object=} associatedObjectForCache an object to which the cache will be attached
  111. * @returns {string} new source path
  112. */
  113. const contextifySourceUrl = (context, source, associatedObjectForCache) => {
  114. if (source.startsWith("webpack://")) return source;
  115. return `webpack://${makePathsRelative(
  116. context,
  117. source,
  118. associatedObjectForCache
  119. )}`;
  120. };
  121. /**
  122. * @param {string} context absolute context path
  123. * @param {SourceMap} sourceMap a source map
  124. * @param {object=} associatedObjectForCache an object to which the cache will be attached
  125. * @returns {SourceMap} new source map
  126. */
  127. const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
  128. if (!Array.isArray(sourceMap.sources)) return sourceMap;
  129. const { sourceRoot } = sourceMap;
  130. /** @type {function(string): string} */
  131. const mapper = !sourceRoot
  132. ? source => source
  133. : sourceRoot.endsWith("/")
  134. ? source =>
  135. source.startsWith("/")
  136. ? `${sourceRoot.slice(0, -1)}${source}`
  137. : `${sourceRoot}${source}`
  138. : source =>
  139. source.startsWith("/")
  140. ? `${sourceRoot}${source}`
  141. : `${sourceRoot}/${source}`;
  142. const newSources = sourceMap.sources.map(source =>
  143. contextifySourceUrl(context, mapper(source), associatedObjectForCache)
  144. );
  145. return {
  146. ...sourceMap,
  147. file: "x",
  148. sourceRoot: undefined,
  149. sources: newSources
  150. };
  151. };
  152. /**
  153. * @param {string | Buffer} input the input
  154. * @returns {string} the converted string
  155. */
  156. const asString = input => {
  157. if (Buffer.isBuffer(input)) {
  158. return input.toString("utf-8");
  159. }
  160. return input;
  161. };
  162. /**
  163. * @param {string | Buffer} input the input
  164. * @returns {Buffer} the converted buffer
  165. */
  166. const asBuffer = input => {
  167. if (!Buffer.isBuffer(input)) {
  168. return Buffer.from(input, "utf-8");
  169. }
  170. return input;
  171. };
  172. class NonErrorEmittedError extends WebpackError {
  173. constructor(error) {
  174. super();
  175. this.name = "NonErrorEmittedError";
  176. this.message = "(Emitted value instead of an instance of Error) " + error;
  177. }
  178. }
  179. makeSerializable(
  180. NonErrorEmittedError,
  181. "webpack/lib/NormalModule",
  182. "NonErrorEmittedError"
  183. );
  184. /**
  185. * @typedef {object} NormalModuleCompilationHooks
  186. * @property {SyncHook<[object, NormalModule]>} loader
  187. * @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders
  188. * @property {SyncHook<[NormalModule]>} beforeParse
  189. * @property {SyncHook<[NormalModule]>} beforeSnapshot
  190. * @property {HookMap<AsyncSeriesBailHook<[string, NormalModule], string | Buffer>>} readResourceForScheme
  191. * @property {HookMap<AsyncSeriesBailHook<[object], string | Buffer>>} readResource
  192. * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
  193. */
  194. /**
  195. * @typedef {object} NormalModuleCreateData
  196. * @property {string=} layer an optional layer in which the module is
  197. * @property {JavaScriptModuleTypes | ""} type module type. When deserializing, this is set to an empty string "".
  198. * @property {string} request request string
  199. * @property {string} userRequest request intended by user (without loaders from config)
  200. * @property {string} rawRequest request without resolving
  201. * @property {LoaderItem[]} loaders list of loaders
  202. * @property {string} resource path + query of the real resource
  203. * @property {Record<string, any>=} resourceResolveData resource resolve data
  204. * @property {string} context context directory for resolving
  205. * @property {string=} matchResource path + query of the matched resource (virtual)
  206. * @property {Parser} parser the parser used
  207. * @property {ParserOptions=} parserOptions the options of the parser used
  208. * @property {Generator} generator the generator used
  209. * @property {GeneratorOptions=} generatorOptions the options of the generator used
  210. * @property {ResolveOptions=} resolveOptions options used for resolving requests from this module
  211. */
  212. /** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */
  213. const compilationHooksMap = new WeakMap();
  214. class NormalModule extends Module {
  215. /**
  216. * @param {Compilation} compilation the compilation
  217. * @returns {NormalModuleCompilationHooks} the attached hooks
  218. */
  219. static getCompilationHooks(compilation) {
  220. if (!(compilation instanceof Compilation)) {
  221. throw new TypeError(
  222. "The 'compilation' argument must be an instance of Compilation"
  223. );
  224. }
  225. let hooks = compilationHooksMap.get(compilation);
  226. if (hooks === undefined) {
  227. hooks = {
  228. loader: new SyncHook(["loaderContext", "module"]),
  229. beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]),
  230. beforeParse: new SyncHook(["module"]),
  231. beforeSnapshot: new SyncHook(["module"]),
  232. // TODO webpack 6 deprecate
  233. readResourceForScheme: new HookMap(scheme => {
  234. const hook = hooks.readResource.for(scheme);
  235. return createFakeHook(
  236. /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({
  237. tap: (options, fn) =>
  238. hook.tap(options, loaderContext =>
  239. fn(loaderContext.resource, loaderContext._module)
  240. ),
  241. tapAsync: (options, fn) =>
  242. hook.tapAsync(options, (loaderContext, callback) =>
  243. fn(loaderContext.resource, loaderContext._module, callback)
  244. ),
  245. tapPromise: (options, fn) =>
  246. hook.tapPromise(options, loaderContext =>
  247. fn(loaderContext.resource, loaderContext._module)
  248. )
  249. })
  250. );
  251. }),
  252. readResource: new HookMap(
  253. () => new AsyncSeriesBailHook(["loaderContext"])
  254. ),
  255. needBuild: new AsyncSeriesBailHook(["module", "context"])
  256. };
  257. compilationHooksMap.set(
  258. compilation,
  259. /** @type {NormalModuleCompilationHooks} */ (hooks)
  260. );
  261. }
  262. return /** @type {NormalModuleCompilationHooks} */ (hooks);
  263. }
  264. /**
  265. * @param {NormalModuleCreateData} options options object
  266. */
  267. constructor({
  268. layer,
  269. type,
  270. request,
  271. userRequest,
  272. rawRequest,
  273. loaders,
  274. resource,
  275. resourceResolveData,
  276. context,
  277. matchResource,
  278. parser,
  279. parserOptions,
  280. generator,
  281. generatorOptions,
  282. resolveOptions
  283. }) {
  284. super(type, context || getContext(resource), layer);
  285. // Info from Factory
  286. /** @type {string} */
  287. this.request = request;
  288. /** @type {string} */
  289. this.userRequest = userRequest;
  290. /** @type {string} */
  291. this.rawRequest = rawRequest;
  292. /** @type {boolean} */
  293. this.binary = /^(asset|webassembly)\b/.test(type);
  294. /** @type {undefined | Parser} */
  295. this.parser = parser;
  296. /** @type {undefined | ParserOptions} */
  297. this.parserOptions = parserOptions;
  298. /** @type {undefined | Generator} */
  299. this.generator = generator;
  300. /** @type {undefined | GeneratorOptions} */
  301. this.generatorOptions = generatorOptions;
  302. /** @type {string} */
  303. this.resource = resource;
  304. this.resourceResolveData = resourceResolveData;
  305. /** @type {string | undefined} */
  306. this.matchResource = matchResource;
  307. /** @type {LoaderItem[]} */
  308. this.loaders = loaders;
  309. if (resolveOptions !== undefined) {
  310. // already declared in super class
  311. this.resolveOptions = resolveOptions;
  312. }
  313. // Info from Build
  314. /** @type {WebpackError | null} */
  315. this.error = null;
  316. /**
  317. * @private
  318. * @type {Source | null}
  319. */
  320. this._source = null;
  321. /**
  322. * @private
  323. * @type {Map<string, number> | undefined}
  324. */
  325. this._sourceSizes = undefined;
  326. /**
  327. * @private
  328. * @type {undefined | SourceTypes}
  329. */
  330. this._sourceTypes = undefined;
  331. // Cache
  332. this._lastSuccessfulBuildMeta = {};
  333. this._forceBuild = true;
  334. this._isEvaluatingSideEffects = false;
  335. /** @type {WeakSet<ModuleGraph> | undefined} */
  336. this._addedSideEffectsBailout = undefined;
  337. /** @type {Map<string, any>} */
  338. this._codeGeneratorData = new Map();
  339. }
  340. /**
  341. * @returns {string} a unique identifier of the module
  342. */
  343. identifier() {
  344. if (this.layer === null) {
  345. if (this.type === JAVASCRIPT_MODULE_TYPE_AUTO) {
  346. return this.request;
  347. } else {
  348. return `${this.type}|${this.request}`;
  349. }
  350. } else {
  351. return `${this.type}|${this.request}|${this.layer}`;
  352. }
  353. }
  354. /**
  355. * @param {RequestShortener} requestShortener the request shortener
  356. * @returns {string} a user readable identifier of the module
  357. */
  358. readableIdentifier(requestShortener) {
  359. return requestShortener.shorten(this.userRequest);
  360. }
  361. /**
  362. * @param {LibIdentOptions} options options
  363. * @returns {string | null} an identifier for library inclusion
  364. */
  365. libIdent(options) {
  366. let ident = contextify(
  367. options.context,
  368. this.userRequest,
  369. options.associatedObjectForCache
  370. );
  371. if (this.layer) ident = `(${this.layer})/${ident}`;
  372. return ident;
  373. }
  374. /**
  375. * @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
  376. */
  377. nameForCondition() {
  378. const resource = this.matchResource || this.resource;
  379. const idx = resource.indexOf("?");
  380. if (idx >= 0) return resource.slice(0, idx);
  381. return resource;
  382. }
  383. /**
  384. * Assuming this module is in the cache. Update the (cached) module with
  385. * the fresh module from the factory. Usually updates internal references
  386. * and properties.
  387. * @param {Module} module fresh module
  388. * @returns {void}
  389. */
  390. updateCacheModule(module) {
  391. super.updateCacheModule(module);
  392. const m = /** @type {NormalModule} */ (module);
  393. this.binary = m.binary;
  394. this.request = m.request;
  395. this.userRequest = m.userRequest;
  396. this.rawRequest = m.rawRequest;
  397. this.parser = m.parser;
  398. this.parserOptions = m.parserOptions;
  399. this.generator = m.generator;
  400. this.generatorOptions = m.generatorOptions;
  401. this.resource = m.resource;
  402. this.resourceResolveData = m.resourceResolveData;
  403. this.context = m.context;
  404. this.matchResource = m.matchResource;
  405. this.loaders = m.loaders;
  406. }
  407. /**
  408. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  409. */
  410. cleanupForCache() {
  411. // Make sure to cache types and sizes before cleanup when this module has been built
  412. // They are accessed by the stats and we don't want them to crash after cleanup
  413. // TODO reconsider this for webpack 6
  414. if (this.buildInfo) {
  415. if (this._sourceTypes === undefined) this.getSourceTypes();
  416. for (const type of /** @type {SourceTypes} */ (this._sourceTypes)) {
  417. this.size(type);
  418. }
  419. }
  420. super.cleanupForCache();
  421. this.parser = undefined;
  422. this.parserOptions = undefined;
  423. this.generator = undefined;
  424. this.generatorOptions = undefined;
  425. }
  426. /**
  427. * Module should be unsafe cached. Get data that's needed for that.
  428. * This data will be passed to restoreFromUnsafeCache later.
  429. * @returns {UnsafeCacheData} cached data
  430. */
  431. getUnsafeCacheData() {
  432. const data =
  433. /** @type {NormalModuleUnsafeCacheData} */
  434. (super.getUnsafeCacheData());
  435. data.parserOptions = this.parserOptions;
  436. data.generatorOptions = this.generatorOptions;
  437. return data;
  438. }
  439. /**
  440. * restore unsafe cache data
  441. * @param {NormalModuleUnsafeCacheData} unsafeCacheData data from getUnsafeCacheData
  442. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  443. */
  444. restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  445. this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  446. }
  447. /**
  448. * restore unsafe cache data
  449. * @param {object} unsafeCacheData data from getUnsafeCacheData
  450. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  451. */
  452. _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  453. super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  454. this.parserOptions = unsafeCacheData.parserOptions;
  455. this.parser = normalModuleFactory.getParser(this.type, this.parserOptions);
  456. this.generatorOptions = unsafeCacheData.generatorOptions;
  457. this.generator = normalModuleFactory.getGenerator(
  458. this.type,
  459. this.generatorOptions
  460. );
  461. // we assume the generator behaves identically and keep cached sourceTypes/Sizes
  462. }
  463. /**
  464. * @param {string} context the compilation context
  465. * @param {string} name the asset name
  466. * @param {string | Buffer} content the content
  467. * @param {(string | SourceMap)=} sourceMap an optional source map
  468. * @param {object=} associatedObjectForCache object for caching
  469. * @returns {Source} the created source
  470. */
  471. createSourceForAsset(
  472. context,
  473. name,
  474. content,
  475. sourceMap,
  476. associatedObjectForCache
  477. ) {
  478. if (sourceMap) {
  479. if (
  480. typeof sourceMap === "string" &&
  481. (this.useSourceMap || this.useSimpleSourceMap)
  482. ) {
  483. return new OriginalSource(
  484. content,
  485. contextifySourceUrl(context, sourceMap, associatedObjectForCache)
  486. );
  487. }
  488. if (this.useSourceMap) {
  489. return new SourceMapSource(
  490. content,
  491. name,
  492. contextifySourceMap(
  493. context,
  494. /** @type {SourceMap} */ (sourceMap),
  495. associatedObjectForCache
  496. )
  497. );
  498. }
  499. }
  500. return new RawSource(content);
  501. }
  502. /**
  503. * @private
  504. * @template T
  505. * @param {ResolverWithOptions} resolver a resolver
  506. * @param {WebpackOptions} options webpack options
  507. * @param {Compilation} compilation the compilation
  508. * @param {InputFileSystem} fs file system from reading
  509. * @param {NormalModuleCompilationHooks} hooks the hooks
  510. * @returns {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} loader context
  511. */
  512. _createLoaderContext(resolver, options, compilation, fs, hooks) {
  513. const { requestShortener } = compilation.runtimeTemplate;
  514. const getCurrentLoaderName = () => {
  515. const currentLoader = this.getCurrentLoader(loaderContext);
  516. if (!currentLoader) return "(not in loader scope)";
  517. return requestShortener.shorten(currentLoader.loader);
  518. };
  519. /**
  520. * @returns {ResolveContext} resolve context
  521. */
  522. const getResolveContext = () => {
  523. return {
  524. fileDependencies: {
  525. add: d => /** @type {TODO} */ (loaderContext).addDependency(d)
  526. },
  527. contextDependencies: {
  528. add: d => /** @type {TODO} */ (loaderContext).addContextDependency(d)
  529. },
  530. missingDependencies: {
  531. add: d => /** @type {TODO} */ (loaderContext).addMissingDependency(d)
  532. }
  533. };
  534. };
  535. const getAbsolutify = memoize(() =>
  536. absolutify.bindCache(compilation.compiler.root)
  537. );
  538. const getAbsolutifyInContext = memoize(() =>
  539. absolutify.bindContextCache(this.context, compilation.compiler.root)
  540. );
  541. const getContextify = memoize(() =>
  542. contextify.bindCache(compilation.compiler.root)
  543. );
  544. const getContextifyInContext = memoize(() =>
  545. contextify.bindContextCache(this.context, compilation.compiler.root)
  546. );
  547. const utils = {
  548. /**
  549. * @param {string} context context
  550. * @param {string} request request
  551. * @returns {string} result
  552. */
  553. absolutify: (context, request) => {
  554. return context === this.context
  555. ? getAbsolutifyInContext()(request)
  556. : getAbsolutify()(context, request);
  557. },
  558. /**
  559. * @param {string} context context
  560. * @param {string} request request
  561. * @returns {string} result
  562. */
  563. contextify: (context, request) => {
  564. return context === this.context
  565. ? getContextifyInContext()(request)
  566. : getContextify()(context, request);
  567. },
  568. /**
  569. * @param {(string | typeof import("./util/Hash"))=} type type
  570. * @returns {Hash} hash
  571. */
  572. createHash: type => {
  573. return createHash(type || compilation.outputOptions.hashFunction);
  574. }
  575. };
  576. /** @type {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} */
  577. const loaderContext = {
  578. version: 2,
  579. getOptions: schema => {
  580. const loader = this.getCurrentLoader(loaderContext);
  581. let { options } = /** @type {LoaderItem} */ (loader);
  582. if (typeof options === "string") {
  583. if (options.startsWith("{") && options.endsWith("}")) {
  584. try {
  585. options = parseJson(options);
  586. } catch (e) {
  587. throw new Error(`Cannot parse string options: ${e.message}`);
  588. }
  589. } else {
  590. options = querystring.parse(options, "&", "=", {
  591. maxKeys: 0
  592. });
  593. }
  594. }
  595. if (options === null || options === undefined) {
  596. options = {};
  597. }
  598. if (schema) {
  599. let name = "Loader";
  600. let baseDataPath = "options";
  601. let match;
  602. if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) {
  603. [, name, baseDataPath] = match;
  604. }
  605. getValidate()(schema, options, {
  606. name,
  607. baseDataPath
  608. });
  609. }
  610. return options;
  611. },
  612. emitWarning: warning => {
  613. if (!(warning instanceof Error)) {
  614. warning = new NonErrorEmittedError(warning);
  615. }
  616. this.addWarning(
  617. new ModuleWarning(warning, {
  618. from: getCurrentLoaderName()
  619. })
  620. );
  621. },
  622. emitError: error => {
  623. if (!(error instanceof Error)) {
  624. error = new NonErrorEmittedError(error);
  625. }
  626. this.addError(
  627. new ModuleError(error, {
  628. from: getCurrentLoaderName()
  629. })
  630. );
  631. },
  632. getLogger: name => {
  633. const currentLoader = this.getCurrentLoader(loaderContext);
  634. return compilation.getLogger(() =>
  635. [currentLoader && currentLoader.loader, name, this.identifier()]
  636. .filter(Boolean)
  637. .join("|")
  638. );
  639. },
  640. resolve(context, request, callback) {
  641. resolver.resolve({}, context, request, getResolveContext(), callback);
  642. },
  643. getResolve(options) {
  644. const child = options ? resolver.withOptions(options) : resolver;
  645. return (context, request, callback) => {
  646. if (callback) {
  647. child.resolve({}, context, request, getResolveContext(), callback);
  648. } else {
  649. return new Promise((resolve, reject) => {
  650. child.resolve(
  651. {},
  652. context,
  653. request,
  654. getResolveContext(),
  655. (err, result) => {
  656. if (err) reject(err);
  657. else resolve(result);
  658. }
  659. );
  660. });
  661. }
  662. };
  663. },
  664. emitFile: (name, content, sourceMap, assetInfo) => {
  665. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  666. if (!buildInfo.assets) {
  667. buildInfo.assets = Object.create(null);
  668. buildInfo.assetsInfo = new Map();
  669. }
  670. const assets =
  671. /** @type {NonNullable<KnownBuildInfo["assets"]>} */
  672. (buildInfo.assets);
  673. const assetsInfo =
  674. /** @type {NonNullable<KnownBuildInfo["assetsInfo"]>} */
  675. (buildInfo.assetsInfo);
  676. assets[name] = this.createSourceForAsset(
  677. /** @type {string} */ (options.context),
  678. name,
  679. content,
  680. sourceMap,
  681. compilation.compiler.root
  682. );
  683. assetsInfo.set(name, assetInfo);
  684. },
  685. addBuildDependency: dep => {
  686. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  687. if (buildInfo.buildDependencies === undefined) {
  688. buildInfo.buildDependencies = new LazySet();
  689. }
  690. buildInfo.buildDependencies.add(dep);
  691. },
  692. utils,
  693. rootContext: /** @type {string} */ (options.context),
  694. webpack: true,
  695. sourceMap: !!this.useSourceMap,
  696. mode: options.mode || "production",
  697. _module: this,
  698. _compilation: compilation,
  699. _compiler: compilation.compiler,
  700. fs: fs
  701. };
  702. Object.assign(loaderContext, options.loader);
  703. hooks.loader.call(loaderContext, this);
  704. return loaderContext;
  705. }
  706. // TODO remove `loaderContext` in webpack@6
  707. /**
  708. * @param {TODO} loaderContext loader context
  709. * @param {number} index index
  710. * @returns {LoaderItem | null} loader
  711. */
  712. getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
  713. if (
  714. this.loaders &&
  715. this.loaders.length &&
  716. index < this.loaders.length &&
  717. index >= 0 &&
  718. this.loaders[index]
  719. ) {
  720. return this.loaders[index];
  721. }
  722. return null;
  723. }
  724. /**
  725. * @param {string} context the compilation context
  726. * @param {string | Buffer} content the content
  727. * @param {(string | SourceMapSource)=} sourceMap an optional source map
  728. * @param {object=} associatedObjectForCache object for caching
  729. * @returns {Source} the created source
  730. */
  731. createSource(context, content, sourceMap, associatedObjectForCache) {
  732. if (Buffer.isBuffer(content)) {
  733. return new RawSource(content);
  734. }
  735. // if there is no identifier return raw source
  736. if (!this.identifier) {
  737. return new RawSource(content);
  738. }
  739. // from here on we assume we have an identifier
  740. const identifier = this.identifier();
  741. if (this.useSourceMap && sourceMap) {
  742. return new SourceMapSource(
  743. content,
  744. contextifySourceUrl(context, identifier, associatedObjectForCache),
  745. contextifySourceMap(
  746. context,
  747. /** @type {TODO} */ (sourceMap),
  748. associatedObjectForCache
  749. )
  750. );
  751. }
  752. if (this.useSourceMap || this.useSimpleSourceMap) {
  753. return new OriginalSource(
  754. content,
  755. contextifySourceUrl(context, identifier, associatedObjectForCache)
  756. );
  757. }
  758. return new RawSource(content);
  759. }
  760. /**
  761. * @param {WebpackOptions} options webpack options
  762. * @param {Compilation} compilation the compilation
  763. * @param {ResolverWithOptions} resolver the resolver
  764. * @param {InputFileSystem} fs the file system
  765. * @param {NormalModuleCompilationHooks} hooks the hooks
  766. * @param {function((WebpackError | null)=): void} callback callback function
  767. * @returns {void}
  768. */
  769. _doBuild(options, compilation, resolver, fs, hooks, callback) {
  770. const loaderContext = this._createLoaderContext(
  771. resolver,
  772. options,
  773. compilation,
  774. fs,
  775. hooks
  776. );
  777. const processResult = (err, result) => {
  778. if (err) {
  779. if (!(err instanceof Error)) {
  780. err = new NonErrorEmittedError(err);
  781. }
  782. const currentLoader = this.getCurrentLoader(loaderContext);
  783. const error = new ModuleBuildError(err, {
  784. from:
  785. currentLoader &&
  786. compilation.runtimeTemplate.requestShortener.shorten(
  787. currentLoader.loader
  788. )
  789. });
  790. return callback(error);
  791. }
  792. const source = result[0];
  793. const sourceMap = result.length >= 1 ? result[1] : null;
  794. const extraInfo = result.length >= 2 ? result[2] : null;
  795. if (!Buffer.isBuffer(source) && typeof source !== "string") {
  796. const currentLoader = this.getCurrentLoader(loaderContext, 0);
  797. const err = new Error(
  798. `Final loader (${
  799. currentLoader
  800. ? compilation.runtimeTemplate.requestShortener.shorten(
  801. currentLoader.loader
  802. )
  803. : "unknown"
  804. }) didn't return a Buffer or String`
  805. );
  806. const error = new ModuleBuildError(err);
  807. return callback(error);
  808. }
  809. this._source = this.createSource(
  810. /** @type {string} */ (options.context),
  811. this.binary ? asBuffer(source) : asString(source),
  812. sourceMap,
  813. compilation.compiler.root
  814. );
  815. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  816. this._ast =
  817. typeof extraInfo === "object" &&
  818. extraInfo !== null &&
  819. extraInfo.webpackAST !== undefined
  820. ? extraInfo.webpackAST
  821. : null;
  822. return callback();
  823. };
  824. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  825. buildInfo.fileDependencies = new LazySet();
  826. buildInfo.contextDependencies = new LazySet();
  827. buildInfo.missingDependencies = new LazySet();
  828. buildInfo.cacheable = true;
  829. try {
  830. hooks.beforeLoaders.call(this.loaders, this, loaderContext);
  831. } catch (err) {
  832. processResult(err);
  833. return;
  834. }
  835. if (this.loaders.length > 0) {
  836. /** @type {BuildInfo} */
  837. (this.buildInfo).buildDependencies = new LazySet();
  838. }
  839. runLoaders(
  840. {
  841. resource: this.resource,
  842. loaders: this.loaders,
  843. context: loaderContext,
  844. processResource: (loaderContext, resourcePath, callback) => {
  845. const resource = loaderContext.resource;
  846. const scheme = getScheme(resource);
  847. hooks.readResource
  848. .for(scheme)
  849. .callAsync(loaderContext, (err, result) => {
  850. if (err) return callback(err);
  851. if (typeof result !== "string" && !result) {
  852. return callback(new UnhandledSchemeError(scheme, resource));
  853. }
  854. return callback(null, result);
  855. });
  856. }
  857. },
  858. (err, result) => {
  859. // Cleanup loaderContext to avoid leaking memory in ICs
  860. loaderContext._compilation =
  861. loaderContext._compiler =
  862. loaderContext._module =
  863. // eslint-disable-next-line no-warning-comments
  864. // @ts-ignore
  865. loaderContext.fs =
  866. undefined;
  867. if (!result) {
  868. /** @type {BuildInfo} */
  869. (this.buildInfo).cacheable = false;
  870. return processResult(
  871. err || new Error("No result from loader-runner processing"),
  872. null
  873. );
  874. }
  875. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  876. const fileDependencies =
  877. /** @type {NonNullable<KnownBuildInfo["fileDependencies"]>} */
  878. (buildInfo.fileDependencies);
  879. const contextDependencies =
  880. /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */
  881. (buildInfo.contextDependencies);
  882. const missingDependencies =
  883. /** @type {NonNullable<KnownBuildInfo["missingDependencies"]>} */
  884. (buildInfo.missingDependencies);
  885. fileDependencies.addAll(result.fileDependencies);
  886. contextDependencies.addAll(result.contextDependencies);
  887. missingDependencies.addAll(result.missingDependencies);
  888. for (const loader of this.loaders) {
  889. const buildDependencies =
  890. /** @type {NonNullable<KnownBuildInfo["buildDependencies"]>} */
  891. (buildInfo.buildDependencies);
  892. buildDependencies.add(loader.loader);
  893. }
  894. buildInfo.cacheable = buildInfo.cacheable && result.cacheable;
  895. processResult(err, result.result);
  896. }
  897. );
  898. }
  899. /**
  900. * @param {WebpackError} error the error
  901. * @returns {void}
  902. */
  903. markModuleAsErrored(error) {
  904. // Restore build meta from successful build to keep importing state
  905. this.buildMeta = { ...this._lastSuccessfulBuildMeta };
  906. this.error = error;
  907. this.addError(error);
  908. }
  909. /**
  910. * @param {TODO} rule rule
  911. * @param {string} content content
  912. * @returns {boolean} result
  913. */
  914. applyNoParseRule(rule, content) {
  915. // must start with "rule" if rule is a string
  916. if (typeof rule === "string") {
  917. return content.startsWith(rule);
  918. }
  919. if (typeof rule === "function") {
  920. return rule(content);
  921. }
  922. // we assume rule is a regexp
  923. return rule.test(content);
  924. }
  925. /**
  926. * @param {TODO} noParseRule no parse rule
  927. * @param {string} request request
  928. * @returns {boolean} check if module should not be parsed, returns "true" if the module should !not! be parsed, returns "false" if the module !must! be parsed
  929. */
  930. shouldPreventParsing(noParseRule, request) {
  931. // if no noParseRule exists, return false
  932. // the module !must! be parsed.
  933. if (!noParseRule) {
  934. return false;
  935. }
  936. // we only have one rule to check
  937. if (!Array.isArray(noParseRule)) {
  938. // returns "true" if the module is !not! to be parsed
  939. return this.applyNoParseRule(noParseRule, request);
  940. }
  941. for (let i = 0; i < noParseRule.length; i++) {
  942. const rule = noParseRule[i];
  943. // early exit on first truthy match
  944. // this module is !not! to be parsed
  945. if (this.applyNoParseRule(rule, request)) {
  946. return true;
  947. }
  948. }
  949. // no match found, so this module !should! be parsed
  950. return false;
  951. }
  952. /**
  953. * @param {Compilation} compilation compilation
  954. * @private
  955. */
  956. _initBuildHash(compilation) {
  957. const hash = createHash(compilation.outputOptions.hashFunction);
  958. if (this._source) {
  959. hash.update("source");
  960. this._source.updateHash(hash);
  961. }
  962. hash.update("meta");
  963. hash.update(JSON.stringify(this.buildMeta));
  964. /** @type {BuildInfo} */
  965. (this.buildInfo).hash = /** @type {string} */ (hash.digest("hex"));
  966. }
  967. /**
  968. * @param {WebpackOptions} options webpack options
  969. * @param {Compilation} compilation the compilation
  970. * @param {ResolverWithOptions} resolver the resolver
  971. * @param {InputFileSystem} fs the file system
  972. * @param {function(WebpackError=): void} callback callback function
  973. * @returns {void}
  974. */
  975. build(options, compilation, resolver, fs, callback) {
  976. this._forceBuild = false;
  977. this._source = null;
  978. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  979. this._sourceTypes = undefined;
  980. this._ast = null;
  981. this.error = null;
  982. this.clearWarningsAndErrors();
  983. this.clearDependenciesAndBlocks();
  984. this.buildMeta = {};
  985. this.buildInfo = {
  986. cacheable: false,
  987. parsed: true,
  988. fileDependencies: undefined,
  989. contextDependencies: undefined,
  990. missingDependencies: undefined,
  991. buildDependencies: undefined,
  992. valueDependencies: undefined,
  993. hash: undefined,
  994. assets: undefined,
  995. assetsInfo: undefined
  996. };
  997. const startTime = compilation.compiler.fsStartTime || Date.now();
  998. const hooks = NormalModule.getCompilationHooks(compilation);
  999. return this._doBuild(options, compilation, resolver, fs, hooks, err => {
  1000. // if we have an error mark module as failed and exit
  1001. if (err) {
  1002. this.markModuleAsErrored(err);
  1003. this._initBuildHash(compilation);
  1004. return callback();
  1005. }
  1006. /**
  1007. * @param {Error} e error
  1008. * @returns {void}
  1009. */
  1010. const handleParseError = e => {
  1011. const source = /** @type {Source} */ (this._source).source();
  1012. const loaders = this.loaders.map(item =>
  1013. contextify(
  1014. /** @type {string} */ (options.context),
  1015. item.loader,
  1016. compilation.compiler.root
  1017. )
  1018. );
  1019. const error = new ModuleParseError(source, e, loaders, this.type);
  1020. this.markModuleAsErrored(error);
  1021. this._initBuildHash(compilation);
  1022. return callback();
  1023. };
  1024. const handleParseResult = () => {
  1025. this.dependencies.sort(
  1026. concatComparators(
  1027. compareSelect(a => a.loc, compareLocations),
  1028. keepOriginalOrder(this.dependencies)
  1029. )
  1030. );
  1031. this._initBuildHash(compilation);
  1032. this._lastSuccessfulBuildMeta =
  1033. /** @type {BuildMeta} */
  1034. (this.buildMeta);
  1035. return handleBuildDone();
  1036. };
  1037. const handleBuildDone = () => {
  1038. try {
  1039. hooks.beforeSnapshot.call(this);
  1040. } catch (err) {
  1041. this.markModuleAsErrored(err);
  1042. return callback();
  1043. }
  1044. const snapshotOptions = compilation.options.snapshot.module;
  1045. const { cacheable } = /** @type {BuildInfo} */ (this.buildInfo);
  1046. if (!cacheable || !snapshotOptions) {
  1047. return callback();
  1048. }
  1049. // add warning for all non-absolute paths in fileDependencies, etc
  1050. // This makes it easier to find problems with watching and/or caching
  1051. /** @type {undefined | Set<string>} */
  1052. let nonAbsoluteDependencies = undefined;
  1053. /**
  1054. * @param {LazySet<string>} deps deps
  1055. */
  1056. const checkDependencies = deps => {
  1057. for (const dep of deps) {
  1058. if (!ABSOLUTE_PATH_REGEX.test(dep)) {
  1059. if (nonAbsoluteDependencies === undefined)
  1060. nonAbsoluteDependencies = new Set();
  1061. nonAbsoluteDependencies.add(dep);
  1062. deps.delete(dep);
  1063. try {
  1064. const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, "");
  1065. const absolute = join(
  1066. compilation.fileSystemInfo.fs,
  1067. this.context,
  1068. depWithoutGlob
  1069. );
  1070. if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) {
  1071. (depWithoutGlob !== dep
  1072. ? /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */
  1073. (
  1074. /** @type {BuildInfo} */ (this.buildInfo)
  1075. .contextDependencies
  1076. )
  1077. : deps
  1078. ).add(absolute);
  1079. }
  1080. } catch (e) {
  1081. // ignore
  1082. }
  1083. }
  1084. }
  1085. };
  1086. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  1087. const fileDependencies =
  1088. /** @type {NonNullable<KnownBuildInfo["fileDependencies"]>} */
  1089. (buildInfo.fileDependencies);
  1090. const contextDependencies =
  1091. /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */
  1092. (buildInfo.contextDependencies);
  1093. const missingDependencies =
  1094. /** @type {NonNullable<KnownBuildInfo["missingDependencies"]>} */
  1095. (buildInfo.missingDependencies);
  1096. checkDependencies(fileDependencies);
  1097. checkDependencies(missingDependencies);
  1098. checkDependencies(contextDependencies);
  1099. if (nonAbsoluteDependencies !== undefined) {
  1100. const InvalidDependenciesModuleWarning =
  1101. getInvalidDependenciesModuleWarning();
  1102. this.addWarning(
  1103. new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies)
  1104. );
  1105. }
  1106. // convert file/context/missingDependencies into filesystem snapshot
  1107. compilation.fileSystemInfo.createSnapshot(
  1108. startTime,
  1109. fileDependencies,
  1110. contextDependencies,
  1111. missingDependencies,
  1112. snapshotOptions,
  1113. (err, snapshot) => {
  1114. if (err) {
  1115. this.markModuleAsErrored(err);
  1116. return;
  1117. }
  1118. buildInfo.fileDependencies = undefined;
  1119. buildInfo.contextDependencies = undefined;
  1120. buildInfo.missingDependencies = undefined;
  1121. buildInfo.snapshot = snapshot;
  1122. return callback();
  1123. }
  1124. );
  1125. };
  1126. try {
  1127. hooks.beforeParse.call(this);
  1128. } catch (err) {
  1129. this.markModuleAsErrored(err);
  1130. this._initBuildHash(compilation);
  1131. return callback();
  1132. }
  1133. // check if this module should !not! be parsed.
  1134. // if so, exit here;
  1135. const noParseRule = options.module && options.module.noParse;
  1136. if (this.shouldPreventParsing(noParseRule, this.request)) {
  1137. // We assume that we need module and exports
  1138. /** @type {BuildInfo} */
  1139. (this.buildInfo).parsed = false;
  1140. this._initBuildHash(compilation);
  1141. return handleBuildDone();
  1142. }
  1143. try {
  1144. const source = /** @type {Source} */ (this._source).source();
  1145. /** @type {Parser} */
  1146. (this.parser).parse(this._ast || source, {
  1147. source,
  1148. current: this,
  1149. module: this,
  1150. compilation: compilation,
  1151. options: options
  1152. });
  1153. } catch (e) {
  1154. handleParseError(/** @type {Error} */ (e));
  1155. return;
  1156. }
  1157. handleParseResult();
  1158. });
  1159. }
  1160. /**
  1161. * @param {ConcatenationBailoutReasonContext} context context
  1162. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  1163. */
  1164. getConcatenationBailoutReason(context) {
  1165. return /** @type {Generator} */ (
  1166. this.generator
  1167. ).getConcatenationBailoutReason(this, context);
  1168. }
  1169. /**
  1170. * @param {ModuleGraph} moduleGraph the module graph
  1171. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  1172. */
  1173. getSideEffectsConnectionState(moduleGraph) {
  1174. if (this.factoryMeta !== undefined) {
  1175. if (this.factoryMeta.sideEffectFree) return false;
  1176. if (this.factoryMeta.sideEffectFree === false) return true;
  1177. }
  1178. if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) {
  1179. if (this._isEvaluatingSideEffects)
  1180. return ModuleGraphConnection.CIRCULAR_CONNECTION;
  1181. this._isEvaluatingSideEffects = true;
  1182. /** @type {ConnectionState} */
  1183. let current = false;
  1184. for (const dep of this.dependencies) {
  1185. const state = dep.getModuleEvaluationSideEffectsState(moduleGraph);
  1186. if (state === true) {
  1187. if (
  1188. this._addedSideEffectsBailout === undefined
  1189. ? ((this._addedSideEffectsBailout = new WeakSet()), true)
  1190. : !this._addedSideEffectsBailout.has(moduleGraph)
  1191. ) {
  1192. this._addedSideEffectsBailout.add(moduleGraph);
  1193. moduleGraph
  1194. .getOptimizationBailout(this)
  1195. .push(
  1196. () =>
  1197. `Dependency (${
  1198. dep.type
  1199. }) with side effects at ${formatLocation(dep.loc)}`
  1200. );
  1201. }
  1202. this._isEvaluatingSideEffects = false;
  1203. return true;
  1204. } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) {
  1205. current = ModuleGraphConnection.addConnectionStates(current, state);
  1206. }
  1207. }
  1208. this._isEvaluatingSideEffects = false;
  1209. // When caching is implemented here, make sure to not cache when
  1210. // at least one circular connection was in the loop above
  1211. return current;
  1212. } else {
  1213. return true;
  1214. }
  1215. }
  1216. /**
  1217. * @returns {SourceTypes} types available (do not mutate)
  1218. */
  1219. getSourceTypes() {
  1220. if (this._sourceTypes === undefined) {
  1221. this._sourceTypes = /** @type {Generator} */ (this.generator).getTypes(
  1222. this
  1223. );
  1224. }
  1225. return this._sourceTypes;
  1226. }
  1227. /**
  1228. * @param {CodeGenerationContext} context context for code generation
  1229. * @returns {CodeGenerationResult} result
  1230. */
  1231. codeGeneration({
  1232. dependencyTemplates,
  1233. runtimeTemplate,
  1234. moduleGraph,
  1235. chunkGraph,
  1236. runtime,
  1237. concatenationScope,
  1238. codeGenerationResults,
  1239. sourceTypes
  1240. }) {
  1241. /** @type {Set<string>} */
  1242. const runtimeRequirements = new Set();
  1243. const { parsed } = /** @type {BuildInfo} */ (this.buildInfo);
  1244. if (!parsed) {
  1245. runtimeRequirements.add(RuntimeGlobals.module);
  1246. runtimeRequirements.add(RuntimeGlobals.exports);
  1247. runtimeRequirements.add(RuntimeGlobals.thisAsExports);
  1248. }
  1249. /** @type {function(): Map<string, any>} */
  1250. const getData = () => {
  1251. return this._codeGeneratorData;
  1252. };
  1253. const sources = new Map();
  1254. for (const type of sourceTypes || chunkGraph.getModuleSourceTypes(this)) {
  1255. const source = this.error
  1256. ? new RawSource(
  1257. "throw new Error(" + JSON.stringify(this.error.message) + ");"
  1258. )
  1259. : /** @type {Generator} */ (this.generator).generate(this, {
  1260. dependencyTemplates,
  1261. runtimeTemplate,
  1262. moduleGraph,
  1263. chunkGraph,
  1264. runtimeRequirements,
  1265. runtime,
  1266. concatenationScope,
  1267. codeGenerationResults,
  1268. getData,
  1269. type
  1270. });
  1271. if (source) {
  1272. sources.set(type, new CachedSource(source));
  1273. }
  1274. }
  1275. /** @type {CodeGenerationResult} */
  1276. const resultEntry = {
  1277. sources,
  1278. runtimeRequirements,
  1279. data: this._codeGeneratorData
  1280. };
  1281. return resultEntry;
  1282. }
  1283. /**
  1284. * @returns {Source | null} the original source for the module before webpack transformation
  1285. */
  1286. originalSource() {
  1287. return this._source;
  1288. }
  1289. /**
  1290. * @returns {void}
  1291. */
  1292. invalidateBuild() {
  1293. this._forceBuild = true;
  1294. }
  1295. /**
  1296. * @param {NeedBuildContext} context context info
  1297. * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
  1298. * @returns {void}
  1299. */
  1300. needBuild(context, callback) {
  1301. const { fileSystemInfo, compilation, valueCacheVersions } = context;
  1302. // build if enforced
  1303. if (this._forceBuild) return callback(null, true);
  1304. // always try to build in case of an error
  1305. if (this.error) return callback(null, true);
  1306. const { cacheable, snapshot, valueDependencies } =
  1307. /** @type {BuildInfo} */ (this.buildInfo);
  1308. // always build when module is not cacheable
  1309. if (!cacheable) return callback(null, true);
  1310. // build when there is no snapshot to check
  1311. if (!snapshot) return callback(null, true);
  1312. // build when valueDependencies have changed
  1313. if (valueDependencies) {
  1314. if (!valueCacheVersions) return callback(null, true);
  1315. for (const [key, value] of valueDependencies) {
  1316. if (value === undefined) return callback(null, true);
  1317. const current = valueCacheVersions.get(key);
  1318. if (
  1319. value !== current &&
  1320. (typeof value === "string" ||
  1321. typeof current === "string" ||
  1322. current === undefined ||
  1323. !isSubset(value, current))
  1324. ) {
  1325. return callback(null, true);
  1326. }
  1327. }
  1328. }
  1329. // check snapshot for validity
  1330. fileSystemInfo.checkSnapshotValid(snapshot, (err, valid) => {
  1331. if (err) return callback(err);
  1332. if (!valid) return callback(null, true);
  1333. const hooks = NormalModule.getCompilationHooks(compilation);
  1334. hooks.needBuild.callAsync(this, context, (err, needBuild) => {
  1335. if (err) {
  1336. return callback(
  1337. HookWebpackError.makeWebpackError(
  1338. err,
  1339. "NormalModule.getCompilationHooks().needBuild"
  1340. )
  1341. );
  1342. }
  1343. callback(null, !!needBuild);
  1344. });
  1345. });
  1346. }
  1347. /**
  1348. * @param {string=} type the source type for which the size should be estimated
  1349. * @returns {number} the estimated size of the module (must be non-zero)
  1350. */
  1351. size(type) {
  1352. const cachedSize =
  1353. this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type);
  1354. if (cachedSize !== undefined) {
  1355. return cachedSize;
  1356. }
  1357. const size = Math.max(
  1358. 1,
  1359. /** @type {Generator} */ (this.generator).getSize(this, type)
  1360. );
  1361. if (this._sourceSizes === undefined) {
  1362. this._sourceSizes = new Map();
  1363. }
  1364. this._sourceSizes.set(type, size);
  1365. return size;
  1366. }
  1367. /**
  1368. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  1369. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  1370. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  1371. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  1372. */
  1373. addCacheDependencies(
  1374. fileDependencies,
  1375. contextDependencies,
  1376. missingDependencies,
  1377. buildDependencies
  1378. ) {
  1379. const { snapshot, buildDependencies: buildDeps } =
  1380. /** @type {BuildInfo} */ (this.buildInfo);
  1381. if (snapshot) {
  1382. fileDependencies.addAll(snapshot.getFileIterable());
  1383. contextDependencies.addAll(snapshot.getContextIterable());
  1384. missingDependencies.addAll(snapshot.getMissingIterable());
  1385. } else {
  1386. const {
  1387. fileDependencies: fileDeps,
  1388. contextDependencies: contextDeps,
  1389. missingDependencies: missingDeps
  1390. } = /** @type {BuildInfo} */ (this.buildInfo);
  1391. if (fileDeps !== undefined) fileDependencies.addAll(fileDeps);
  1392. if (contextDeps !== undefined) contextDependencies.addAll(contextDeps);
  1393. if (missingDeps !== undefined) missingDependencies.addAll(missingDeps);
  1394. }
  1395. if (buildDeps !== undefined) {
  1396. buildDependencies.addAll(buildDeps);
  1397. }
  1398. }
  1399. /**
  1400. * @param {Hash} hash the hash used to track dependencies
  1401. * @param {UpdateHashContext} context context
  1402. * @returns {void}
  1403. */
  1404. updateHash(hash, context) {
  1405. hash.update(/** @type {BuildInfo} */ (this.buildInfo).hash);
  1406. this.generator.updateHash(hash, {
  1407. module: this,
  1408. ...context
  1409. });
  1410. super.updateHash(hash, context);
  1411. }
  1412. /**
  1413. * @param {ObjectSerializerContext} context context
  1414. */
  1415. serialize(context) {
  1416. const { write } = context;
  1417. // deserialize
  1418. write(this._source);
  1419. write(this.error);
  1420. write(this._lastSuccessfulBuildMeta);
  1421. write(this._forceBuild);
  1422. write(this._codeGeneratorData);
  1423. super.serialize(context);
  1424. }
  1425. static deserialize(context) {
  1426. const obj = new NormalModule({
  1427. // will be deserialized by Module
  1428. layer: null,
  1429. type: "",
  1430. // will be filled by updateCacheModule
  1431. resource: "",
  1432. context: "",
  1433. request: null,
  1434. userRequest: null,
  1435. rawRequest: null,
  1436. loaders: null,
  1437. matchResource: null,
  1438. parser: null,
  1439. parserOptions: null,
  1440. generator: null,
  1441. generatorOptions: null,
  1442. resolveOptions: null
  1443. });
  1444. obj.deserialize(context);
  1445. return obj;
  1446. }
  1447. /**
  1448. * @param {ObjectDeserializerContext} context context
  1449. */
  1450. deserialize(context) {
  1451. const { read } = context;
  1452. this._source = read();
  1453. this.error = read();
  1454. this._lastSuccessfulBuildMeta = read();
  1455. this._forceBuild = read();
  1456. this._codeGeneratorData = read();
  1457. super.deserialize(context);
  1458. }
  1459. }
  1460. makeSerializable(NormalModule, "webpack/lib/NormalModule");
  1461. module.exports = NormalModule;