NormalModule.js 53 KB

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