NormalModule.js 42 KB

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