NormalModule.js 50 KB

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