NormalModule.js 41 KB

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