NormalModule.js 47 KB

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