NormalModule.js 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  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 {
  8. AsyncSeriesBailHook,
  9. HookMap,
  10. SyncHook,
  11. SyncWaterfallHook
  12. } = require("tapable");
  13. const {
  14. CachedSource,
  15. OriginalSource,
  16. RawSource,
  17. SourceMapSource
  18. } = require("webpack-sources");
  19. const Dependency = require("./Dependency");
  20. const Module = require("./Module");
  21. const ModuleGraphConnection = require("./ModuleGraphConnection");
  22. const { JAVASCRIPT_MODULE_TYPE_AUTO } = require("./ModuleTypeConstants");
  23. const RuntimeGlobals = require("./RuntimeGlobals");
  24. const HarmonyImportSideEffectDependency = require("./dependencies/HarmonyImportSideEffectDependency");
  25. const HookWebpackError = require("./errors/HookWebpackError");
  26. const {
  27. createLoaderContext,
  28. getContext,
  29. runLoaders
  30. } = require("./loaders/LoaderRunner");
  31. const LazySet = require("./util/LazySet");
  32. const { isSubset } = require("./util/SetHelpers");
  33. const { getScheme } = require("./util/URLAbsoluteSpecifier");
  34. const {
  35. concatComparators,
  36. keepOriginalOrder,
  37. sortWithSourceOrder
  38. } = require("./util/comparators");
  39. const createHash = require("./util/createHash");
  40. const createHooksRegistry = require("./util/createHooksRegistry");
  41. const { createFakeHook } = require("./util/deprecation");
  42. const formatLocation = require("./util/formatLocation");
  43. const { join } = require("./util/fs");
  44. const {
  45. ABSOLUTE_PATH_REGEXP,
  46. absolutify,
  47. contextify,
  48. contextifySourceUrl
  49. } = require("./util/identifier");
  50. const makeSerializable = require("./util/makeSerializable");
  51. const memoize = require("./util/memoize");
  52. const parseJson = require("./util/parseJson");
  53. const getValidate = memoize(() => require("schema-utils").validate);
  54. const getGenerator = memoize(() => require("./Generator"));
  55. const getExtractSourceMap = memoize(() => require("./util/extractSourceMap"));
  56. const getInvalidDependenciesModuleWarning = memoize(() =>
  57. require("./errors/InvalidDependenciesModuleWarning")
  58. );
  59. const getUnhandledSchemeError = memoize(() =>
  60. require("./errors/UnhandledSchemeError")
  61. );
  62. const getNonErrorEmittedError = memoize(() =>
  63. require("./errors/NonErrorEmittedError")
  64. );
  65. const getModuleWarning = memoize(() => require("./errors/ModuleWarning"));
  66. const getModuleParseError = memoize(() => require("./errors/ModuleParseError"));
  67. const getModuleError = memoize(() => require("./errors/ModuleError"));
  68. const getModuleBuildError = memoize(() => require("./errors/ModuleBuildError"));
  69. /** @import { ResolveContext, ResolveRequest } from "enhanced-resolve" */
  70. /** @import { Source, RawSourceMap } from "webpack-sources" */
  71. /**
  72. * @import {
  73. * ResolveOptions,
  74. * NoParse,
  75. * HashFunction
  76. * } from "../declarations/WebpackOptions"
  77. */
  78. /**
  79. * @import Compilation, {
  80. * FileSystemDependencies,
  81. * UnsafeCacheData
  82. * } from "./Compilation"
  83. */
  84. /**
  85. * @import {
  86. * WebpackOptionsNormalizedWithDefaults as WebpackOptions
  87. * } from "./config/defaults"
  88. */
  89. /** @import { UpdateHashContext } from "./Dependency" */
  90. /** @import Generator, { GenerateErrorFn } from "./Generator" */
  91. /** @import { Snapshot } from "./FileSystemInfo" */
  92. /**
  93. * @import {
  94. * BuildInfo,
  95. * ValueCacheVersions,
  96. * BuildMeta,
  97. * CodeGenerationContext,
  98. * CodeGenerationResult,
  99. * CodeGenerationResultData,
  100. * ConcatenationBailoutReasonContext,
  101. * KnownBuildInfo,
  102. * LibIdentOptions,
  103. * LibIdent,
  104. * NameForCondition,
  105. * NeedBuildContext,
  106. * NeedBuildCallback,
  107. * BuildCallback,
  108. * RuntimeRequirements,
  109. * Sources,
  110. * SourceType,
  111. * SourceTypes
  112. * } from "./Module"
  113. */
  114. /** @import ModuleGraph from "./ModuleGraph" */
  115. /** @import { ConnectionState } from "./ModuleGraphConnection" */
  116. /**
  117. * @import NormalModuleFactory, {
  118. * NormalModuleTypes,
  119. * ParserByType,
  120. * ParserOptionsByType,
  121. * GeneratorByType,
  122. * GeneratorOptionsByType,
  123. * ResourceSchemeData
  124. * } from "./NormalModuleFactory"
  125. */
  126. /** @import Parser, { PreparsedAst } from "./Parser" */
  127. /** @import RequestShortener from "./RequestShortener" */
  128. /** @import { ResolverWithOptions } from "./ResolverFactory" */
  129. /**
  130. * @import {
  131. * ObjectDeserializerContext,
  132. * ObjectSerializerContext
  133. * } from "./serialization/ObjectMiddleware"
  134. */
  135. /** @import Hash from "./util/Hash" */
  136. /** @import { InputFileSystem } from "./util/fs" */
  137. /** @import { AssociatedObjectForCache } from "./util/identifier" */
  138. /**
  139. * @template T
  140. * @typedef {import("./util/deprecation").FakeHook<T>} FakeHook
  141. */
  142. /** @typedef {{ [k: string]: EXPECTED_ANY }} ParserOptions */
  143. /** @typedef {{ [k: string]: EXPECTED_ANY }} GeneratorOptions */
  144. /**
  145. * @template T
  146. * @typedef {import("../declarations/LoaderContext").LoaderContext<T>} LoaderContext
  147. */
  148. /**
  149. * @template T
  150. * @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} NormalModuleLoaderContext
  151. */
  152. /** @typedef {(content: string) => boolean} NoParseFn */
  153. /**
  154. * @param {NormalModule} mod the module
  155. * @param {ModuleGraph} moduleGraph the module graph
  156. * @param {Dependency} dep the dep that triggered the bailout
  157. */
  158. const recordSideEffectsBailout = (mod, moduleGraph, dep) => {
  159. if (mod._addedSideEffectsBailout === undefined) {
  160. mod._addedSideEffectsBailout = new WeakSet();
  161. } else if (mod._addedSideEffectsBailout.has(moduleGraph)) {
  162. return;
  163. }
  164. mod._addedSideEffectsBailout.add(moduleGraph);
  165. moduleGraph
  166. .getOptimizationBailout(mod)
  167. .push(
  168. () =>
  169. `Dependency (${dep.type}) with side effects at ${formatLocation(dep.loc)}`
  170. );
  171. };
  172. /**
  173. * Walks the `HarmonyImportSideEffectDependency` graph to decide how `rootMod`
  174. * connects to a referrer when consumed for its side effects only.
  175. *
  176. * Iterative (explicit work stack) so deep import chains never approach V8's
  177. * recursion limit — the overflow behind #20986 — with no separate recursive
  178. * form or depth cap. Cycles use Tarjan's `index`/`lowlink`: a module's result
  179. * is memoized on `_sideEffectsStateGraph` only when it is context-independent
  180. * (cycle-free, or the root of its strongly-connected component), i.e. exactly
  181. * when the result cannot depend on which ancestors are mid-walk.
  182. *
  183. * The previous walker disabled memoization for the whole walk the moment any
  184. * cycle appeared (one global `circular` flag). With diamond-shaped graphs that
  185. * made the walk exponential, so a single circular import could blow up an
  186. * otherwise-linear graph. Per-module lowlink keeps the cycle-free majority
  187. * memoized while a cycle exists elsewhere.
  188. *
  189. * Caching under `lowlink === index` is conservative: an imprecise lowlink can
  190. * only skip caching (a later recompute yields the same value), never memoize a
  191. * state that depended on stack context. `true` is monotonic and always cached.
  192. * A non-`NormalModule` dependency (e.g. `ConcatenatedModule` re-entering this
  193. * method) is treated as a taint so its chain is never memoized, and any module
  194. * already flagged `_isEvaluatingSideEffects` (this walk or an outer re-entrant
  195. * one) counts as circular, matching the previous walker.
  196. * @param {NormalModule} rootMod the module being walked
  197. * @param {ModuleGraph} moduleGraph the module graph
  198. * @param {EXPECTED_ANY} SideEffectDep `HarmonyImportSideEffectDependency` constructor, resolved once at the entry
  199. * @returns {ConnectionState} the side-effects connection state
  200. */
  201. const walkSideEffects = (rootMod, moduleGraph, SideEffectDep) => {
  202. // Context-independent state without descending; `undefined` => walk deps.
  203. /**
  204. * @param {NormalModule} mod module
  205. * @returns {ConnectionState | undefined} resolved state or undefined
  206. */
  207. const quick = (mod) => {
  208. if (mod._sideEffectsStateGraph === moduleGraph) {
  209. return /** @type {ConnectionState} */ (mod._sideEffectsStateValue);
  210. }
  211. const fm = mod.factoryMeta;
  212. if (fm !== undefined) {
  213. if (fm.sideEffectFree) return false;
  214. if (fm.sideEffectFree === false) return true;
  215. }
  216. if (!(mod.buildMeta !== undefined && mod.buildMeta.sideEffectFree)) {
  217. return true;
  218. }
  219. return undefined;
  220. };
  221. const q0 = quick(rootMod);
  222. if (q0 !== undefined) return q0;
  223. /** @type {Map<NormalModule, number>} module -> Tarjan index */
  224. const indexOf = new Map();
  225. /** @type {Map<NormalModule, number>} module -> Tarjan lowlink */
  226. const lowOf = new Map();
  227. // Parallel frame arrays, to avoid a per-frame object allocation.
  228. /** @type {NormalModule[]} */
  229. const fMod = [];
  230. /** @type {Dependency[][]} */
  231. const fDeps = [];
  232. /** @type {number[]} */
  233. const fIdx = [];
  234. /** @type {ConnectionState[]} */
  235. const fCur = [];
  236. let counter = 0;
  237. /**
  238. * @param {NormalModule} mod module to push a frame for
  239. */
  240. const enter = (mod) => {
  241. indexOf.set(mod, counter);
  242. lowOf.set(mod, counter);
  243. counter++;
  244. mod._isEvaluatingSideEffects = true;
  245. fMod.push(mod);
  246. fDeps.push(mod.dependencies);
  247. fIdx.push(0);
  248. fCur.push(false);
  249. };
  250. enter(rootMod);
  251. /** @type {ConnectionState} the just-popped frame's result */
  252. let result = false;
  253. /**
  254. * Result of a just-popped child frame, to apply to the new top's current
  255. * dep. `undefined` means "no pending; advance normally".
  256. * @type {ConnectionState | undefined}
  257. */
  258. let pending;
  259. while (fMod.length > 0) {
  260. const top = fMod.length - 1;
  261. const mod = fMod[top];
  262. const deps = fDeps[top];
  263. let i = fIdx[top];
  264. let current = fCur[top];
  265. // Apply a popped child's result to the dep that spawned it.
  266. if (pending !== undefined) {
  267. const state = pending;
  268. pending = undefined;
  269. const dep = deps[i];
  270. if (state === true) {
  271. recordSideEffectsBailout(mod, moduleGraph, dep);
  272. mod._sideEffectsStateGraph = moduleGraph;
  273. mod._sideEffectsStateValue = true;
  274. mod._isEvaluatingSideEffects = false;
  275. fMod.pop();
  276. fDeps.pop();
  277. fIdx.pop();
  278. fCur.pop();
  279. result = true;
  280. pending = true;
  281. continue;
  282. }
  283. if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) {
  284. current = ModuleGraphConnection.addConnectionStates(current, state);
  285. }
  286. i++;
  287. }
  288. let descended = false;
  289. while (i < deps.length) {
  290. const dep = deps[i];
  291. /** @type {ConnectionState} */
  292. let state;
  293. if (dep instanceof SideEffectDep) {
  294. const refModule = moduleGraph.getModule(dep);
  295. if (!refModule) {
  296. state = true;
  297. } else if (refModule instanceof NormalModule) {
  298. if (refModule._isEvaluatingSideEffects) {
  299. // On the current stack (or an outer re-entrant walk) => cycle.
  300. state = ModuleGraphConnection.CIRCULAR_CONNECTION;
  301. const ri = indexOf.get(refModule);
  302. lowOf.set(
  303. mod,
  304. Math.min(
  305. /** @type {number} */ (lowOf.get(mod)),
  306. ri === undefined ? -1 : ri
  307. )
  308. );
  309. } else {
  310. const q = quick(refModule);
  311. if (q !== undefined) {
  312. state = q;
  313. } else {
  314. // Descend: pause this frame, walk the child next.
  315. fIdx[top] = i;
  316. fCur[top] = current;
  317. enter(refModule);
  318. descended = true;
  319. break;
  320. }
  321. }
  322. } else {
  323. // Non-NormalModule (e.g. ConcatenatedModule delegating back
  324. // through here) resolves via a re-entrant walk that may see our
  325. // in-progress modules as circular, so taint this chain: never
  326. // memoize it.
  327. state = refModule.getSideEffectsConnectionState(moduleGraph);
  328. lowOf.set(mod, -1);
  329. }
  330. } else {
  331. state = dep.getModuleEvaluationSideEffectsState(moduleGraph);
  332. }
  333. if (state === true) {
  334. recordSideEffectsBailout(mod, moduleGraph, dep);
  335. // `true` is monotonic — always safe to memoize.
  336. mod._sideEffectsStateGraph = moduleGraph;
  337. mod._sideEffectsStateValue = true;
  338. mod._isEvaluatingSideEffects = false;
  339. fMod.pop();
  340. fDeps.pop();
  341. fIdx.pop();
  342. fCur.pop();
  343. result = true;
  344. pending = true;
  345. descended = true;
  346. break;
  347. }
  348. if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) {
  349. current = ModuleGraphConnection.addConnectionStates(current, state);
  350. }
  351. i++;
  352. }
  353. if (descended) continue;
  354. // `mod` finished without a `true` bailout.
  355. mod._isEvaluatingSideEffects = false;
  356. // Memoize only when the result is context-independent: no back-edge in
  357. // this subtree reached above `mod` (a cycle-free module or an SCC root).
  358. if (lowOf.get(mod) === indexOf.get(mod)) {
  359. mod._sideEffectsStateGraph = moduleGraph;
  360. mod._sideEffectsStateValue = current;
  361. }
  362. fMod.pop();
  363. fDeps.pop();
  364. fIdx.pop();
  365. fCur.pop();
  366. result = current;
  367. pending = current;
  368. if (fMod.length > 0) {
  369. const parent = fMod[fMod.length - 1];
  370. lowOf.set(
  371. parent,
  372. Math.min(
  373. /** @type {number} */ (lowOf.get(parent)),
  374. /** @type {number} */ (lowOf.get(mod))
  375. )
  376. );
  377. }
  378. }
  379. return result;
  380. };
  381. /**
  382. * @typedef {object} LoaderItem
  383. * @property {string} loader
  384. * @property {string | null | undefined | Record<string, EXPECTED_ANY>} options
  385. * @property {string | null=} ident
  386. * @property {string | null=} type
  387. */
  388. /**
  389. * @param {string} context absolute context path
  390. * @param {string | RawSourceMap} sourceMap a source map
  391. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  392. * @returns {string | RawSourceMap} new source map
  393. */
  394. const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
  395. if (typeof sourceMap === "string" || !Array.isArray(sourceMap.sources)) {
  396. return sourceMap;
  397. }
  398. const { sourceRoot } = sourceMap;
  399. /** @type {(source: string) => string} */
  400. const mapper = !sourceRoot
  401. ? (source) => source
  402. : sourceRoot.endsWith("/")
  403. ? (source) =>
  404. source.startsWith("/")
  405. ? `${sourceRoot.slice(0, -1)}${source}`
  406. : `${sourceRoot}${source}`
  407. : (source) =>
  408. source.startsWith("/")
  409. ? `${sourceRoot}${source}`
  410. : `${sourceRoot}/${source}`;
  411. const newSources = sourceMap.sources.map((source) =>
  412. contextifySourceUrl(context, mapper(source), associatedObjectForCache)
  413. );
  414. return {
  415. ...sourceMap,
  416. file: "x",
  417. sourceRoot: undefined,
  418. sources: newSources
  419. };
  420. };
  421. /**
  422. * @param {string | Buffer} input the input
  423. * @returns {string} the converted string
  424. */
  425. const asString = (input) => {
  426. if (Buffer.isBuffer(input)) {
  427. return input.toString("utf8");
  428. }
  429. return input;
  430. };
  431. /**
  432. * @param {string | Buffer} input the input
  433. * @returns {Buffer} the converted buffer
  434. */
  435. const asBuffer = (input) => {
  436. if (!Buffer.isBuffer(input)) {
  437. return Buffer.from(input, "utf8");
  438. }
  439. return input;
  440. };
  441. /** @typedef {[string | Buffer, string | RawSourceMap | undefined, PreparsedAst | undefined]} Result */
  442. /** @typedef {LoaderContext<EXPECTED_ANY>} AnyLoaderContext */
  443. /**
  444. * @deprecated Use the `readResource` hook instead.
  445. * @typedef {HookMap<FakeHook<AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>>>} DeprecatedReadResourceForScheme
  446. */
  447. const createCompilationHooks = () => {
  448. /** @type {HookMap<AsyncSeriesBailHook<[AnyLoaderContext], string | Buffer | null>>} */
  449. const readResource = new HookMap(
  450. () => new AsyncSeriesBailHook(["loaderContext"])
  451. );
  452. return {
  453. // TODO webpack 6 deprecate
  454. /**
  455. * @deprecated Use the `readResource` hook instead.
  456. * @type {DeprecatedReadResourceForScheme}
  457. */
  458. readResourceForScheme: new HookMap((scheme) => {
  459. const hook = readResource.for(scheme);
  460. return createFakeHook(
  461. /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>} */ ({
  462. tap: (options, fn) =>
  463. hook.tap(options, (loaderContext) =>
  464. fn(
  465. loaderContext.resource,
  466. /** @type {NormalModule} */ (loaderContext._module)
  467. )
  468. ),
  469. tapAsync: (options, fn) =>
  470. hook.tapAsync(options, (loaderContext, callback) =>
  471. fn(
  472. loaderContext.resource,
  473. /** @type {NormalModule} */ (loaderContext._module),
  474. callback
  475. )
  476. ),
  477. tapPromise: (options, fn) =>
  478. hook.tapPromise(options, (loaderContext) =>
  479. fn(
  480. loaderContext.resource,
  481. /** @type {NormalModule} */ (loaderContext._module)
  482. )
  483. )
  484. })
  485. );
  486. }),
  487. /**
  488. * @since 5.58.0
  489. */
  490. readResource,
  491. /** @type {SyncHook<[AnyLoaderContext, NormalModule]>} */
  492. loader: new SyncHook(["loaderContext", "module"]),
  493. /** @type {SyncHook<[LoaderItem[], NormalModule, AnyLoaderContext]>} */
  494. beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]),
  495. /**
  496. * @type {SyncHook<[NormalModule]>}
  497. * @since 5.59.0
  498. */
  499. beforeParse: new SyncHook(["module"]),
  500. /**
  501. * @type {SyncHook<[NormalModule]>}
  502. * @since 5.59.0
  503. */
  504. beforeSnapshot: new SyncHook(["module"]),
  505. /**
  506. * @type {SyncWaterfallHook<[Result, NormalModule]>}
  507. * @since 5.99.0
  508. */
  509. processResult: new SyncWaterfallHook(["result", "module"]),
  510. /**
  511. * @type {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>}
  512. * @since 5.49.0
  513. */
  514. needBuild: new AsyncSeriesBailHook(["module", "context"])
  515. };
  516. };
  517. /**
  518. * @typedef {ReturnType<typeof createCompilationHooks>} NormalModuleCompilationHooks
  519. */
  520. /**
  521. * @template {NormalModuleTypes | ""} [T=NormalModuleTypes | ""]
  522. * @typedef {object} NormalModuleCreateData
  523. * @property {string=} layer an optional layer in which the module is
  524. * @property {T} type module type. When deserializing, this is set to an empty string "".
  525. * @property {string} request request string
  526. * @property {string} userRequest request intended by user (without loaders from config)
  527. * @property {string} rawRequest request without resolving
  528. * @property {LoaderItem[]} loaders list of loaders
  529. * @property {string} resource path + query of the real resource
  530. * @property {(ResourceSchemeData & Partial<ResolveRequest>)=} resourceResolveData resource resolve data
  531. * @property {string} context context directory for resolving
  532. * @property {string=} matchResource path + query of the matched resource (virtual)
  533. * @property {ParserByType[T]} parser the parser used
  534. * @property {ParserOptionsByType[T]=} parserOptions the options of the parser used
  535. * @property {GeneratorByType[T]} generator the generator used
  536. * @property {GeneratorOptionsByType[T]=} generatorOptions the options of the generator used
  537. * @property {ResolveOptions=} resolveOptions options used for resolving requests from this module
  538. * @property {boolean} extractSourceMap enable/disable extracting source map
  539. */
  540. /**
  541. * @typedef {(resourcePath: string, getLoaderContext: (resourcePath: string) => AnyLoaderContext) => Promise<string | Buffer<ArrayBufferLike>>} ReadResource
  542. */
  543. /**
  544. * Defines the build info properties of normal modules (filesystem-backed, loader-processed).
  545. * @typedef {object} KnownNormalModuleBuildInfo
  546. * @property {boolean=} parsed
  547. * @property {string=} hash
  548. * @property {FileSystemDependencies=} fileDependencies
  549. * @property {FileSystemDependencies=} contextDependencies
  550. * @property {FileSystemDependencies=} missingDependencies
  551. * @property {FileSystemDependencies=} buildDependencies
  552. * @property {ValueCacheVersions=} valueDependencies
  553. * @property {(InstanceType<Snapshot> | null)=} snapshot
  554. * @property {string=} resourceIntegrity using in HttpUriPlugin
  555. */
  556. /** @typedef {BuildInfo & KnownNormalModuleBuildInfo} NormalModuleBuildInfo */
  557. const normalModuleHooksRegistry = createHooksRegistry(createCompilationHooks);
  558. class NormalModule extends Module {
  559. /**
  560. * @param {Compilation} compilation the compilation
  561. * @returns {NormalModuleCompilationHooks} the attached hooks
  562. */
  563. static getCompilationHooks(compilation) {
  564. return normalModuleHooksRegistry(compilation);
  565. }
  566. /**
  567. * @param {NormalModuleCreateData} options options object
  568. */
  569. constructor({
  570. layer,
  571. type,
  572. request,
  573. userRequest,
  574. rawRequest,
  575. loaders,
  576. resource,
  577. resourceResolveData,
  578. context,
  579. matchResource,
  580. parser,
  581. parserOptions,
  582. generator,
  583. generatorOptions,
  584. resolveOptions,
  585. extractSourceMap
  586. }) {
  587. super(type, context || getContext(resource), layer);
  588. // Info from Factory
  589. /** @type {NormalModuleCreateData['request']} */
  590. this.request = request;
  591. /** @type {NormalModuleCreateData['userRequest']} */
  592. this.userRequest = userRequest;
  593. /** @type {NormalModuleCreateData['rawRequest']} */
  594. this.rawRequest = rawRequest;
  595. /** @type {boolean} */
  596. this.binary = /^(?:asset|webassembly)\b/.test(type);
  597. /** @type {NormalModuleCreateData['parser'] | undefined} */
  598. this.parser = parser;
  599. /** @type {NormalModuleCreateData['parserOptions']} */
  600. this.parserOptions = parserOptions;
  601. /** @type {NormalModuleCreateData['generator'] | undefined} */
  602. this.generator = generator;
  603. /** @type {NormalModuleCreateData['generatorOptions']} */
  604. this.generatorOptions = generatorOptions;
  605. /** @type {NormalModuleCreateData['resource']} */
  606. this.resource = resource;
  607. /** @type {NormalModuleCreateData['resourceResolveData']} */
  608. this.resourceResolveData = resourceResolveData;
  609. /** @type {NormalModuleCreateData['matchResource']} */
  610. this.matchResource = matchResource;
  611. /** @type {NormalModuleCreateData['loaders']} */
  612. this.loaders = loaders;
  613. if (resolveOptions !== undefined) {
  614. // already declared in super class
  615. /** @type {NormalModuleCreateData['resolveOptions']} */
  616. this.resolveOptions = resolveOptions;
  617. }
  618. /** @type {NormalModuleCreateData['extractSourceMap']} */
  619. this.extractSourceMap = extractSourceMap;
  620. // Set by HotModuleReplacementPlugin via NormalModuleFactory's `module` hook
  621. /** @type {boolean} */
  622. this.hot = false;
  623. // Info from Build
  624. // Redeclared with the normal module specific shape (see KnownNormalModuleBuildInfo)
  625. /** @type {NormalModuleBuildInfo | undefined} */
  626. this.buildInfo = undefined;
  627. /** @type {Error | null} */
  628. this.error = null;
  629. /**
  630. * @private
  631. * @type {Source | null}
  632. */
  633. this._source = null;
  634. // Set at build time; declared here so the instance shape is fixed at construction
  635. /**
  636. * @private
  637. * @type {PreparsedAst | null}
  638. */
  639. this._ast = null;
  640. /**
  641. * @private
  642. * @type {Map<undefined | SourceType, number> | undefined}
  643. */
  644. this._sourceSizes = undefined;
  645. /**
  646. * @private
  647. * @type {undefined | SourceTypes}
  648. */
  649. this._sourceTypes = undefined;
  650. // Cache
  651. /**
  652. * @private
  653. * @type {BuildMeta}
  654. */
  655. this._lastSuccessfulBuildMeta = {};
  656. /**
  657. * @private
  658. * @type {boolean}
  659. */
  660. this._forceBuild = true;
  661. /**
  662. * @type {boolean}
  663. */
  664. this._isEvaluatingSideEffects = false;
  665. /**
  666. * @type {WeakSet<ModuleGraph> | undefined}
  667. */
  668. this._addedSideEffectsBailout = undefined;
  669. /**
  670. * Memoizes the result of `getSideEffectsConnectionState`. The
  671. * graph slot keys the cached value to the `ModuleGraph` it was
  672. * computed against so stale values never leak across compilations
  673. * — a walk that targets a different graph just overwrites both
  674. * slots. Populated only for context-independent results (cycle-free
  675. * or SCC-root modules; see `walkSideEffects`).
  676. * @type {ModuleGraph | undefined}
  677. */
  678. this._sideEffectsStateGraph = undefined;
  679. /** @type {ConnectionState | undefined} */
  680. this._sideEffectsStateValue = undefined;
  681. /**
  682. * @private
  683. * @type {CodeGenerationResultData}
  684. */
  685. this._codeGeneratorData = new Map();
  686. }
  687. /**
  688. * Returns the unique identifier used to reference this module.
  689. * @returns {string} a unique identifier of the module
  690. */
  691. identifier() {
  692. if (this.layer === null) {
  693. if (this.type === JAVASCRIPT_MODULE_TYPE_AUTO) {
  694. return this.request;
  695. }
  696. return `${this.type}|${this.request}`;
  697. }
  698. return `${this.type}|${this.request}|${this.layer}`;
  699. }
  700. /**
  701. * Returns a human-readable identifier for this module.
  702. * @param {RequestShortener} requestShortener the request shortener
  703. * @returns {string} a user readable identifier of the module
  704. */
  705. readableIdentifier(requestShortener) {
  706. return /** @type {string} */ (requestShortener.shorten(this.userRequest));
  707. }
  708. /**
  709. * @returns {string | null} return the resource path
  710. */
  711. getResource() {
  712. return this.matchResource || this.resource;
  713. }
  714. /**
  715. * Gets the library identifier.
  716. * @param {LibIdentOptions} options options
  717. * @returns {LibIdent | null} an identifier for library inclusion
  718. */
  719. libIdent(options) {
  720. let ident = contextify(
  721. options.context,
  722. this.userRequest,
  723. options.associatedObjectForCache
  724. );
  725. if (this.layer) ident = `(${this.layer})/${ident}`;
  726. return ident;
  727. }
  728. /**
  729. * Returns the path used when matching this module against rule conditions.
  730. * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
  731. */
  732. nameForCondition() {
  733. const resource = /** @type {string} */ (this.getResource());
  734. const idx = resource.indexOf("?");
  735. if (idx >= 0) return resource.slice(0, idx);
  736. return resource;
  737. }
  738. /**
  739. * Assuming this module is in the cache. Update the (cached) module with
  740. * the fresh module from the factory. Usually updates internal references
  741. * and properties.
  742. * @param {Module} module fresh module
  743. * @returns {void}
  744. */
  745. updateCacheModule(module) {
  746. super.updateCacheModule(module);
  747. const m = /** @type {NormalModule} */ (module);
  748. this.binary = m.binary;
  749. this.request = m.request;
  750. this.userRequest = m.userRequest;
  751. this.rawRequest = m.rawRequest;
  752. this.parser = m.parser;
  753. this.parserOptions = m.parserOptions;
  754. this.generator = m.generator;
  755. this.generatorOptions = m.generatorOptions;
  756. this.resource = m.resource;
  757. this.resourceResolveData = m.resourceResolveData;
  758. this.context = m.context;
  759. this.matchResource = m.matchResource;
  760. this.loaders = m.loaders;
  761. this.extractSourceMap = m.extractSourceMap;
  762. }
  763. /**
  764. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  765. */
  766. cleanupForCache() {
  767. // Make sure to cache types and sizes before cleanup when this module has been built
  768. // They are accessed by the stats and we don't want them to crash after cleanup
  769. // TODO reconsider this for webpack 6
  770. if (this.buildInfo) {
  771. if (this._sourceTypes === undefined) this.getSourceTypes();
  772. for (const type of /** @type {SourceTypes} */ (this._sourceTypes)) {
  773. this.size(type);
  774. }
  775. }
  776. super.cleanupForCache();
  777. this.parser = undefined;
  778. this.parserOptions = undefined;
  779. this.generator = undefined;
  780. this.generatorOptions = undefined;
  781. // Drop the side-effects memoization so a long-lived module doesn't
  782. // strong-reference a stale `ModuleGraph`/`Compilation` for graphs
  783. // that never get re-queried with a fresh one.
  784. this._sideEffectsStateGraph = undefined;
  785. this._sideEffectsStateValue = undefined;
  786. }
  787. /**
  788. * Releases the cached parser between incremental rebuilds so it doesn't keep
  789. * the previous compilation alive.
  790. * @returns {void}
  791. */
  792. _cleanupParserForCache() {
  793. this.parser = undefined;
  794. }
  795. /**
  796. * Re-acquire factory-derived helpers (parser/generator) for an incremental
  797. * rebuild so this compilation's plugin hooks apply.
  798. * @param {NormalModuleFactory} normalModuleFactory the normal module factory
  799. * @returns {void}
  800. */
  801. _restoreParserAndGenerator(normalModuleFactory) {
  802. this.parser = normalModuleFactory.getParser(this.type, this.parserOptions);
  803. this.generator = normalModuleFactory.getGenerator(
  804. this.type,
  805. this.generatorOptions
  806. );
  807. }
  808. /**
  809. * Module should be unsafe cached. Get data that's needed for that.
  810. * This data will be passed to restoreFromUnsafeCache later.
  811. * @returns {UnsafeCacheData} cached data
  812. */
  813. getUnsafeCacheData() {
  814. const data = super.getUnsafeCacheData();
  815. data.parserOptions = this.parserOptions;
  816. data.generatorOptions = this.generatorOptions;
  817. return data;
  818. }
  819. /**
  820. * restore unsafe cache data
  821. * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData
  822. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  823. */
  824. restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  825. this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  826. }
  827. /**
  828. * restore unsafe cache data
  829. * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData
  830. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  831. */
  832. _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  833. super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  834. this.parserOptions = unsafeCacheData.parserOptions;
  835. this.parser = normalModuleFactory.getParser(this.type, this.parserOptions);
  836. this.generatorOptions = unsafeCacheData.generatorOptions;
  837. this.generator = normalModuleFactory.getGenerator(
  838. this.type,
  839. this.generatorOptions
  840. );
  841. // we assume the generator behaves identically and keep cached sourceTypes/Sizes
  842. }
  843. /**
  844. * @param {string} context the compilation context
  845. * @param {string} name the asset name
  846. * @param {string | Buffer} content the content
  847. * @param {(string | RawSourceMap)=} sourceMap an optional source map
  848. * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching
  849. * @returns {Source} the created source
  850. */
  851. createSourceForAsset(
  852. context,
  853. name,
  854. content,
  855. sourceMap,
  856. associatedObjectForCache
  857. ) {
  858. if (sourceMap) {
  859. if (
  860. typeof sourceMap === "string" &&
  861. (this.useSourceMap || this.useSimpleSourceMap)
  862. ) {
  863. return new OriginalSource(
  864. content,
  865. contextifySourceUrl(context, sourceMap, associatedObjectForCache)
  866. );
  867. }
  868. if (this.useSourceMap) {
  869. return new SourceMapSource(
  870. content,
  871. name,
  872. contextifySourceMap(
  873. context,
  874. /** @type {RawSourceMap} */
  875. (sourceMap),
  876. associatedObjectForCache
  877. )
  878. );
  879. }
  880. }
  881. return new RawSource(content);
  882. }
  883. /**
  884. * @private
  885. * @template T
  886. * @param {ResolverWithOptions} resolver a resolver
  887. * @param {WebpackOptions} options webpack options
  888. * @param {Compilation} compilation the compilation
  889. * @param {InputFileSystem} fs file system from reading
  890. * @param {NormalModuleCompilationHooks} hooks the hooks
  891. * @returns {import("../declarations/LoaderContext").LoaderContext<T>} loader context
  892. */
  893. _createLoaderContext(resolver, options, compilation, fs, hooks) {
  894. const { requestShortener } = compilation.runtimeTemplate;
  895. const getCurrentLoaderName = () => {
  896. const currentLoader = this.getCurrentLoader(
  897. /** @type {AnyLoaderContext} */
  898. (loaderContext)
  899. );
  900. if (!currentLoader) return "(not in loader scope)";
  901. return requestShortener.shorten(currentLoader.loader);
  902. };
  903. /**
  904. * @returns {ResolveContext} resolve context
  905. */
  906. const getResolveContext = () => ({
  907. fileDependencies: {
  908. add: (d) =>
  909. /** @type {AnyLoaderContext} */
  910. (loaderContext).addDependency(d)
  911. },
  912. contextDependencies: {
  913. add: (d) =>
  914. /** @type {AnyLoaderContext} */
  915. (loaderContext).addContextDependency(d)
  916. },
  917. missingDependencies: {
  918. add: (d) =>
  919. /** @type {AnyLoaderContext} */
  920. (loaderContext).addMissingDependency(d)
  921. }
  922. });
  923. const getAbsolutify = memoize(() =>
  924. absolutify.bindCache(compilation.compiler.root)
  925. );
  926. const getAbsolutifyInContext = memoize(() =>
  927. absolutify.bindContextCache(
  928. /** @type {string} */
  929. (this.context),
  930. compilation.compiler.root
  931. )
  932. );
  933. const getContextify = memoize(() =>
  934. contextify.bindCache(compilation.compiler.root)
  935. );
  936. const getContextifyInContext = memoize(() =>
  937. contextify.bindContextCache(
  938. /** @type {string} */
  939. (this.context),
  940. compilation.compiler.root
  941. )
  942. );
  943. const utils = {
  944. /**
  945. * @param {string} context context
  946. * @param {string} request request
  947. * @returns {string} result
  948. */
  949. absolutify: (context, request) =>
  950. context === this.context
  951. ? getAbsolutifyInContext()(request)
  952. : getAbsolutify()(context, request),
  953. /**
  954. * @param {string} context context
  955. * @param {string} request request
  956. * @returns {string} result
  957. */
  958. contextify: (context, request) =>
  959. context === this.context
  960. ? getContextifyInContext()(request)
  961. : getContextify()(context, request),
  962. /**
  963. * @param {HashFunction=} type type
  964. * @returns {Hash} hash
  965. */
  966. createHash: (type) =>
  967. createHash(type || compilation.outputOptions.hashFunction)
  968. };
  969. /** @type {NormalModuleLoaderContext<T>} */
  970. const loaderContext = {
  971. version: 2,
  972. /** @type {LoaderContext<EXPECTED_ANY>["getOptions"]} */
  973. getOptions: (/** @type {EXPECTED_ANY} */ schema = undefined) => {
  974. const loader = this.getCurrentLoader(
  975. /** @type {AnyLoaderContext} */
  976. (loaderContext)
  977. );
  978. let { options } = /** @type {LoaderItem} */ (loader);
  979. if (typeof options === "string") {
  980. if (options.startsWith("{") && options.endsWith("}")) {
  981. try {
  982. options =
  983. /** @type {LoaderItem["options"]} */
  984. (parseJson(options));
  985. } catch (err) {
  986. throw new Error(
  987. `Cannot parse string options: ${/** @type {Error} */ (err).message}`,
  988. { cause: err }
  989. );
  990. }
  991. } else {
  992. options = querystring.parse(options, "&", "=", {
  993. maxKeys: 0
  994. });
  995. }
  996. }
  997. if (options === null || options === undefined) {
  998. options = {};
  999. }
  1000. if (schema && compilation.options.validate) {
  1001. let name = "Loader";
  1002. let baseDataPath = "options";
  1003. /** @type {RegExpExecArray | null} */
  1004. let match;
  1005. if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) {
  1006. [, name, baseDataPath] = match;
  1007. }
  1008. getValidate()(schema, /** @type {EXPECTED_OBJECT} */ (options), {
  1009. name,
  1010. baseDataPath
  1011. });
  1012. }
  1013. return /** @type {T} */ (options);
  1014. },
  1015. /** @type {LoaderContext<EXPECTED_ANY>["emitWarning"]} */
  1016. emitWarning: (warning) => {
  1017. if (!(warning instanceof Error)) {
  1018. warning = new (getNonErrorEmittedError())(warning);
  1019. }
  1020. this.addWarning(
  1021. new (getModuleWarning())(warning, {
  1022. from: getCurrentLoaderName()
  1023. })
  1024. );
  1025. },
  1026. /** @type {LoaderContext<EXPECTED_ANY>["emitError"]} */
  1027. emitError: (error) => {
  1028. if (!(error instanceof Error)) {
  1029. error = new (getNonErrorEmittedError())(error);
  1030. }
  1031. this.addError(
  1032. new (getModuleError())(error, {
  1033. from: getCurrentLoaderName()
  1034. })
  1035. );
  1036. },
  1037. /** @type {LoaderContext<EXPECTED_ANY>["getLogger"]} */
  1038. getLogger: (name) => {
  1039. const currentLoader = this.getCurrentLoader(
  1040. /** @type {AnyLoaderContext} */
  1041. (loaderContext)
  1042. );
  1043. return compilation.getLogger(() =>
  1044. [currentLoader && currentLoader.loader, name, this.identifier()]
  1045. .filter(Boolean)
  1046. .join("|")
  1047. );
  1048. },
  1049. /** @type {LoaderContext<EXPECTED_ANY>["resolve"]} */
  1050. resolve(context, request, callback) {
  1051. resolver.resolve({}, context, request, getResolveContext(), callback);
  1052. },
  1053. /** @type {LoaderContext<EXPECTED_ANY>["getResolve"]} */
  1054. getResolve(options) {
  1055. const child = options ? resolver.withOptions(options) : resolver;
  1056. return /** @type {ReturnType<import("../declarations/LoaderContext").NormalModuleLoaderContext<T>["getResolve"]>} */ (
  1057. (context, request, callback) => {
  1058. if (callback) {
  1059. child.resolve(
  1060. {},
  1061. context,
  1062. request,
  1063. getResolveContext(),
  1064. callback
  1065. );
  1066. } else {
  1067. return new Promise((resolve, reject) => {
  1068. child.resolve(
  1069. {},
  1070. context,
  1071. request,
  1072. getResolveContext(),
  1073. (err, result) => {
  1074. if (err) reject(err);
  1075. else resolve(result);
  1076. }
  1077. );
  1078. });
  1079. }
  1080. }
  1081. );
  1082. },
  1083. /** @type {LoaderContext<EXPECTED_ANY>["emitFile"]} */
  1084. emitFile: (name, content, sourceMap, assetInfo) => {
  1085. const buildInfo = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1086. if (!buildInfo.assets) {
  1087. buildInfo.assets = Object.create(null);
  1088. buildInfo.assetsInfo = new Map();
  1089. }
  1090. const assets =
  1091. /** @type {NonNullable<KnownBuildInfo["assets"]>} */
  1092. (buildInfo.assets);
  1093. const assetsInfo =
  1094. /** @type {NonNullable<KnownBuildInfo["assetsInfo"]>} */
  1095. (buildInfo.assetsInfo);
  1096. assets[name] = this.createSourceForAsset(
  1097. options.context,
  1098. name,
  1099. content,
  1100. sourceMap,
  1101. compilation.compiler.root
  1102. );
  1103. assetsInfo.set(name, assetInfo);
  1104. },
  1105. addBuildDependency: (dep) => {
  1106. const buildInfo = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1107. if (buildInfo.buildDependencies === undefined) {
  1108. buildInfo.buildDependencies = new LazySet();
  1109. }
  1110. buildInfo.buildDependencies.add(dep);
  1111. },
  1112. utils,
  1113. rootContext: options.context,
  1114. webpack: true,
  1115. sourceMap: Boolean(this.useSourceMap),
  1116. mode: options.mode || "production",
  1117. hashFunction: options.output.hashFunction,
  1118. hashDigest: options.output.hashDigest,
  1119. hashDigestLength: options.output.hashDigestLength,
  1120. hashSalt: options.output.hashSalt,
  1121. _module: this,
  1122. _compilation: compilation,
  1123. _compiler: compilation.compiler,
  1124. fs
  1125. };
  1126. Object.assign(loaderContext, options.loader);
  1127. createLoaderContext(loaderContext);
  1128. hooks.loader.call(
  1129. /** @type {AnyLoaderContext} */
  1130. (loaderContext),
  1131. this
  1132. );
  1133. return /** @type {AnyLoaderContext} */ (loaderContext);
  1134. }
  1135. /**
  1136. * @param {AnyLoaderContext} loaderContext loader context
  1137. * @param {number} index index
  1138. * @returns {LoaderItem | null} loader
  1139. */
  1140. getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
  1141. if (
  1142. this.loaders &&
  1143. this.loaders.length &&
  1144. index < this.loaders.length &&
  1145. index >= 0 &&
  1146. this.loaders[index]
  1147. ) {
  1148. return this.loaders[index];
  1149. }
  1150. return null;
  1151. }
  1152. /**
  1153. * @param {string} context the compilation context
  1154. * @param {string | Buffer} content the content
  1155. * @param {(string | RawSourceMap | null)=} sourceMap an optional source map
  1156. * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching
  1157. * @returns {Source} the created source
  1158. */
  1159. createSource(context, content, sourceMap, associatedObjectForCache) {
  1160. if (Buffer.isBuffer(content)) {
  1161. return new RawSource(content);
  1162. }
  1163. // if there is no identifier return raw source
  1164. if (!this.identifier) {
  1165. return new RawSource(content);
  1166. }
  1167. // from here on we assume we have an identifier
  1168. const identifier = this.identifier();
  1169. if (this.useSourceMap && sourceMap) {
  1170. return new SourceMapSource(
  1171. content,
  1172. contextifySourceUrl(context, identifier, associatedObjectForCache),
  1173. contextifySourceMap(context, sourceMap, associatedObjectForCache)
  1174. );
  1175. }
  1176. if (this.useSourceMap || this.useSimpleSourceMap) {
  1177. return new OriginalSource(
  1178. content,
  1179. contextifySourceUrl(context, identifier, associatedObjectForCache)
  1180. );
  1181. }
  1182. return new RawSource(content);
  1183. }
  1184. /**
  1185. * @param {WebpackOptions} options webpack options
  1186. * @param {Compilation} compilation the compilation
  1187. * @param {ResolverWithOptions} resolver the resolver
  1188. * @param {InputFileSystem} fs the file system
  1189. * @param {NormalModuleCompilationHooks} hooks the hooks
  1190. * @param {BuildCallback} callback callback function
  1191. * @returns {void}
  1192. */
  1193. _doBuild(options, compilation, resolver, fs, hooks, callback) {
  1194. const loaderContext = this._createLoaderContext(
  1195. resolver,
  1196. options,
  1197. compilation,
  1198. fs,
  1199. hooks
  1200. );
  1201. /**
  1202. * @param {Error | null} err err
  1203. * @param {(Result | null)=} result_ result
  1204. * @returns {void}
  1205. */
  1206. const processResult = (err, result_) => {
  1207. if (err) {
  1208. if (!(err instanceof Error)) {
  1209. err = new (getNonErrorEmittedError())(err);
  1210. }
  1211. const currentLoader = this.getCurrentLoader(loaderContext);
  1212. const error = new (getModuleBuildError())(err, {
  1213. from:
  1214. currentLoader &&
  1215. compilation.runtimeTemplate.requestShortener.shorten(
  1216. currentLoader.loader
  1217. )
  1218. });
  1219. return callback(error);
  1220. }
  1221. const result = hooks.processResult.call(
  1222. /** @type {Result} */
  1223. (result_),
  1224. this
  1225. );
  1226. const source = result[0];
  1227. const sourceMap = result.length >= 1 ? result[1] : null;
  1228. const extraInfo = result.length >= 2 ? result[2] : null;
  1229. if (!Buffer.isBuffer(source) && typeof source !== "string") {
  1230. const currentLoader = this.getCurrentLoader(loaderContext, 0);
  1231. const err = new Error(
  1232. `Final loader (${
  1233. currentLoader
  1234. ? compilation.runtimeTemplate.requestShortener.shorten(
  1235. currentLoader.loader
  1236. )
  1237. : "unknown"
  1238. }) didn't return a Buffer or String`
  1239. );
  1240. const error = new (getModuleBuildError())(err);
  1241. return callback(error);
  1242. }
  1243. const isBinaryModule =
  1244. this.generatorOptions && this.generatorOptions.binary !== undefined
  1245. ? this.generatorOptions.binary
  1246. : this.binary;
  1247. this._source = this.createSource(
  1248. options.context,
  1249. isBinaryModule ? asBuffer(source) : asString(source),
  1250. sourceMap,
  1251. compilation.compiler.root
  1252. );
  1253. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  1254. /** @type {PreparsedAst | null} */
  1255. this._ast =
  1256. typeof extraInfo === "object" &&
  1257. extraInfo !== null &&
  1258. extraInfo.webpackAST !== undefined
  1259. ? extraInfo.webpackAST
  1260. : null;
  1261. return callback();
  1262. };
  1263. const buildInfo = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1264. buildInfo.fileDependencies = new LazySet();
  1265. buildInfo.contextDependencies = new LazySet();
  1266. buildInfo.missingDependencies = new LazySet();
  1267. buildInfo.cacheable = true;
  1268. try {
  1269. hooks.beforeLoaders.call(
  1270. this.loaders,
  1271. this,
  1272. /** @type {AnyLoaderContext} */
  1273. (loaderContext)
  1274. );
  1275. } catch (err) {
  1276. processResult(/** @type {Error} */ (err));
  1277. return;
  1278. }
  1279. if (this.loaders.length > 0) {
  1280. /** @type {NormalModuleBuildInfo} */
  1281. (this.buildInfo).buildDependencies = new LazySet();
  1282. }
  1283. runLoaders(
  1284. {
  1285. resource: this.resource,
  1286. loaders: this.loaders,
  1287. context: loaderContext,
  1288. /**
  1289. * @param {AnyLoaderContext} loaderContext the loader context
  1290. * @param {string} resourcePath the resource Path
  1291. * @param {(err: Error | null, result?: string | Buffer, sourceMap?: Result[1]) => void} callback callback
  1292. * @returns {Promise<void>}
  1293. */
  1294. processResource: async (loaderContext, resourcePath, callback) => {
  1295. /** @type {ReadResource} */
  1296. const readResource = (resourcePath, getLoaderContext) => {
  1297. const scheme = getScheme(resourcePath);
  1298. return new Promise((resolve, reject) => {
  1299. hooks.readResource
  1300. .for(scheme)
  1301. .callAsync(getLoaderContext(resourcePath), (err, result) => {
  1302. if (err) {
  1303. reject(err);
  1304. } else {
  1305. if (typeof result !== "string" && !result) {
  1306. return reject(
  1307. new (getUnhandledSchemeError())(
  1308. /** @type {string} */
  1309. (scheme),
  1310. resourcePath
  1311. )
  1312. );
  1313. }
  1314. resolve(result);
  1315. }
  1316. });
  1317. });
  1318. };
  1319. try {
  1320. const result = await readResource(
  1321. resourcePath,
  1322. () => loaderContext
  1323. );
  1324. if (
  1325. this.extractSourceMap &&
  1326. (this.useSourceMap || this.useSimpleSourceMap)
  1327. ) {
  1328. try {
  1329. const { source, sourceMap } = await getExtractSourceMap()(
  1330. result,
  1331. resourcePath,
  1332. /** @type {ReadResource} */
  1333. (resourcePath) =>
  1334. readResource(
  1335. resourcePath,
  1336. (resourcePath) =>
  1337. /** @type {AnyLoaderContext} */
  1338. ({
  1339. addDependency(dependency) {
  1340. loaderContext.addDependency(dependency);
  1341. },
  1342. fs: loaderContext.fs,
  1343. _module: undefined,
  1344. resourcePath,
  1345. resource: resourcePath
  1346. })
  1347. ).catch((err) => {
  1348. throw new Error(
  1349. `Failed to parse source map. ${/** @type {Error} */ (err).message}`
  1350. );
  1351. })
  1352. );
  1353. return callback(null, source, sourceMap);
  1354. } catch (err) {
  1355. this.addWarning(
  1356. new (getModuleWarning())(/** @type {Error} */ (err))
  1357. );
  1358. return callback(null, result);
  1359. }
  1360. }
  1361. return callback(null, result);
  1362. } catch (error) {
  1363. return callback(/** @type {Error} */ (error));
  1364. }
  1365. }
  1366. },
  1367. (err, result) => {
  1368. // Cleanup loaderContext to avoid leaking memory in ICs
  1369. loaderContext._compilation =
  1370. loaderContext._compiler =
  1371. loaderContext._module =
  1372. loaderContext.fs =
  1373. /** @type {EXPECTED_ANY} */
  1374. (undefined);
  1375. if (!result) {
  1376. /** @type {NormalModuleBuildInfo} */
  1377. (this.buildInfo).cacheable = false;
  1378. return processResult(
  1379. err || new Error("No result from loader-runner processing"),
  1380. null
  1381. );
  1382. }
  1383. const buildInfo = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1384. const fileDependencies =
  1385. /** @type {NonNullable<KnownNormalModuleBuildInfo["fileDependencies"]>} */
  1386. (buildInfo.fileDependencies);
  1387. const contextDependencies =
  1388. /** @type {NonNullable<KnownNormalModuleBuildInfo["contextDependencies"]>} */
  1389. (buildInfo.contextDependencies);
  1390. const missingDependencies =
  1391. /** @type {NonNullable<KnownNormalModuleBuildInfo["missingDependencies"]>} */
  1392. (buildInfo.missingDependencies);
  1393. fileDependencies.addAll(result.fileDependencies);
  1394. contextDependencies.addAll(result.contextDependencies);
  1395. missingDependencies.addAll(result.missingDependencies);
  1396. for (const loader of this.loaders) {
  1397. const buildDependencies =
  1398. /** @type {NonNullable<KnownNormalModuleBuildInfo["buildDependencies"]>} */
  1399. (buildInfo.buildDependencies);
  1400. buildDependencies.add(loader.loader);
  1401. }
  1402. buildInfo.cacheable = buildInfo.cacheable && result.cacheable;
  1403. if (result.notCacheableReasons.length > 0) {
  1404. buildInfo.notCacheableReasons = result.notCacheableReasons;
  1405. }
  1406. processResult(err, result.result);
  1407. }
  1408. );
  1409. }
  1410. /**
  1411. * @param {Error} error the error
  1412. * @returns {void}
  1413. */
  1414. markModuleAsErrored(error) {
  1415. // Restore build meta from successful build to keep importing state
  1416. this.buildMeta = { ...this._lastSuccessfulBuildMeta };
  1417. this.error = error;
  1418. this.addError(error);
  1419. }
  1420. /**
  1421. * @param {Exclude<NoParse, EXPECTED_ANY[]>} rule rule
  1422. * @param {string} content content
  1423. * @returns {boolean} result
  1424. */
  1425. applyNoParseRule(rule, content) {
  1426. // must start with "rule" if rule is a string
  1427. if (typeof rule === "string") {
  1428. return content.startsWith(rule);
  1429. }
  1430. if (typeof rule === "function") {
  1431. return rule(content);
  1432. }
  1433. // we assume rule is a regexp
  1434. return rule.test(content);
  1435. }
  1436. /**
  1437. * @param {undefined | NoParse} noParseRule no parse rule
  1438. * @param {string} request request
  1439. * @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
  1440. */
  1441. shouldPreventParsing(noParseRule, request) {
  1442. // if no noParseRule exists, return false
  1443. // the module !must! be parsed.
  1444. if (!noParseRule) {
  1445. return false;
  1446. }
  1447. // we only have one rule to check
  1448. if (!Array.isArray(noParseRule)) {
  1449. // returns "true" if the module is !not! to be parsed
  1450. return this.applyNoParseRule(noParseRule, request);
  1451. }
  1452. for (let i = 0; i < noParseRule.length; i++) {
  1453. const rule = noParseRule[i];
  1454. // early exit on first truthy match
  1455. // this module is !not! to be parsed
  1456. if (this.applyNoParseRule(rule, request)) {
  1457. return true;
  1458. }
  1459. }
  1460. // no match found, so this module !should! be parsed
  1461. return false;
  1462. }
  1463. /**
  1464. * @param {Compilation} compilation compilation
  1465. * @private
  1466. */
  1467. _initBuildHash(compilation) {
  1468. const hash = createHash(compilation.outputOptions.hashFunction);
  1469. if (this._source) {
  1470. hash.update("source");
  1471. this._source.updateHash(hash);
  1472. }
  1473. hash.update("meta");
  1474. hash.update(JSON.stringify(this.buildMeta));
  1475. /** @type {NormalModuleBuildInfo} */
  1476. (this.buildInfo).hash = hash.digest("hex");
  1477. }
  1478. /**
  1479. * Builds the module using the provided compilation context.
  1480. * @param {WebpackOptions} options webpack options
  1481. * @param {Compilation} compilation the compilation
  1482. * @param {ResolverWithOptions} resolver the resolver
  1483. * @param {InputFileSystem} fs the file system
  1484. * @param {BuildCallback} callback callback function
  1485. * @returns {void}
  1486. */
  1487. build(options, compilation, resolver, fs, callback) {
  1488. this._forceBuild = false;
  1489. this._source = null;
  1490. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  1491. this._sourceTypes = undefined;
  1492. this._ast = null;
  1493. this.error = null;
  1494. this.clearWarningsAndErrors();
  1495. this.clearDependenciesAndBlocks();
  1496. this.buildMeta = {
  1497. exportsType: undefined,
  1498. defaultObject: undefined,
  1499. strictHarmonyModule: undefined,
  1500. async: undefined
  1501. };
  1502. this.buildInfo = {
  1503. cacheable: false,
  1504. notCacheableReasons: undefined,
  1505. parsed: true,
  1506. fileDependencies: undefined,
  1507. contextDependencies: undefined,
  1508. missingDependencies: undefined,
  1509. buildDependencies: undefined,
  1510. valueDependencies: undefined,
  1511. hash: undefined,
  1512. assets: undefined,
  1513. assetsInfo: undefined,
  1514. snapshot: undefined,
  1515. strict: undefined,
  1516. exportsArgument: undefined,
  1517. moduleArgument: undefined,
  1518. topLevelDeclarations: undefined,
  1519. pureFunctions: undefined,
  1520. inlineExports: undefined,
  1521. moduleConcatenationBailout: undefined,
  1522. needCreateRequire: undefined,
  1523. usesTopLevelUsingDeclaration: undefined
  1524. };
  1525. const startTime = compilation.compiler.fsStartTime || Date.now();
  1526. const hooks = NormalModule.getCompilationHooks(compilation);
  1527. return this._doBuild(options, compilation, resolver, fs, hooks, (err) => {
  1528. // if we have an error mark module as failed and exit
  1529. if (err) {
  1530. this.markModuleAsErrored(err);
  1531. this._initBuildHash(compilation);
  1532. return callback();
  1533. }
  1534. /**
  1535. * @param {Error} e error
  1536. * @returns {void}
  1537. */
  1538. const handleParseError = (e) => {
  1539. const source = /** @type {Source} */ (this._source).source();
  1540. const loaders = this.loaders.map((item) =>
  1541. contextify(options.context, item.loader, compilation.compiler.root)
  1542. );
  1543. const error = new (getModuleParseError())(
  1544. source,
  1545. e,
  1546. loaders,
  1547. this.type
  1548. );
  1549. this.markModuleAsErrored(error);
  1550. this._initBuildHash(compilation);
  1551. return callback();
  1552. };
  1553. const handleParseResult = () => {
  1554. this.dependencies.sort(
  1555. concatComparators(
  1556. Dependency.compareLocations,
  1557. keepOriginalOrder(this.dependencies)
  1558. )
  1559. );
  1560. sortWithSourceOrder(this.dependencies, new WeakMap());
  1561. this._initBuildHash(compilation);
  1562. this._lastSuccessfulBuildMeta =
  1563. /** @type {BuildMeta} */
  1564. (this.buildMeta);
  1565. return handleBuildDone();
  1566. };
  1567. const handleBuildDone = () => {
  1568. try {
  1569. hooks.beforeSnapshot.call(this);
  1570. } catch (err) {
  1571. this.markModuleAsErrored(/** @type {Error} */ (err));
  1572. return callback();
  1573. }
  1574. const snapshotOptions = compilation.options.snapshot.module;
  1575. const { cacheable } = /** @type {NormalModuleBuildInfo} */ (
  1576. this.buildInfo
  1577. );
  1578. if (!cacheable || !snapshotOptions) {
  1579. return callback();
  1580. }
  1581. // add warning for all non-absolute paths in fileDependencies, etc
  1582. // This makes it easier to find problems with watching and/or caching
  1583. /** @type {undefined | Set<string>} */
  1584. let nonAbsoluteDependencies;
  1585. /**
  1586. * @param {FileSystemDependencies} deps deps
  1587. */
  1588. const checkDependencies = (deps) => {
  1589. for (const dep of deps) {
  1590. if (!ABSOLUTE_PATH_REGEXP.test(dep)) {
  1591. if (nonAbsoluteDependencies === undefined) {
  1592. nonAbsoluteDependencies = new Set();
  1593. }
  1594. nonAbsoluteDependencies.add(dep);
  1595. deps.delete(dep);
  1596. try {
  1597. const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, "");
  1598. const absolute = join(
  1599. compilation.fileSystemInfo.fs,
  1600. /** @type {string} */
  1601. (this.context),
  1602. depWithoutGlob
  1603. );
  1604. if (absolute !== dep && ABSOLUTE_PATH_REGEXP.test(absolute)) {
  1605. (depWithoutGlob !== dep
  1606. ? /** @type {NonNullable<KnownNormalModuleBuildInfo["contextDependencies"]>} */
  1607. (
  1608. /** @type {NormalModuleBuildInfo} */
  1609. (this.buildInfo).contextDependencies
  1610. )
  1611. : deps
  1612. ).add(absolute);
  1613. }
  1614. } catch (_err) {
  1615. // ignore
  1616. }
  1617. }
  1618. }
  1619. };
  1620. const buildInfo = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1621. const fileDependencies =
  1622. /** @type {NonNullable<KnownNormalModuleBuildInfo["fileDependencies"]>} */
  1623. (buildInfo.fileDependencies);
  1624. const contextDependencies =
  1625. /** @type {NonNullable<KnownNormalModuleBuildInfo["contextDependencies"]>} */
  1626. (buildInfo.contextDependencies);
  1627. const missingDependencies =
  1628. /** @type {NonNullable<KnownNormalModuleBuildInfo["missingDependencies"]>} */
  1629. (buildInfo.missingDependencies);
  1630. checkDependencies(fileDependencies);
  1631. checkDependencies(missingDependencies);
  1632. checkDependencies(contextDependencies);
  1633. if (nonAbsoluteDependencies !== undefined) {
  1634. const InvalidDependenciesModuleWarning =
  1635. getInvalidDependenciesModuleWarning();
  1636. this.addWarning(
  1637. new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies)
  1638. );
  1639. }
  1640. // convert file/context/missingDependencies into filesystem snapshot
  1641. compilation.fileSystemInfo.createSnapshot(
  1642. startTime,
  1643. fileDependencies,
  1644. contextDependencies,
  1645. missingDependencies,
  1646. snapshotOptions,
  1647. (err, snapshot) => {
  1648. if (err) {
  1649. this.markModuleAsErrored(err);
  1650. return;
  1651. }
  1652. buildInfo.fileDependencies = undefined;
  1653. buildInfo.contextDependencies = undefined;
  1654. buildInfo.missingDependencies = undefined;
  1655. buildInfo.snapshot = snapshot;
  1656. return callback();
  1657. }
  1658. );
  1659. };
  1660. try {
  1661. hooks.beforeParse.call(this);
  1662. } catch (err) {
  1663. this.markModuleAsErrored(/** @type {Error} */ (err));
  1664. this._initBuildHash(compilation);
  1665. return callback();
  1666. }
  1667. // check if this module should !not! be parsed.
  1668. // if so, exit here;
  1669. const noParseRule = options.module && options.module.noParse;
  1670. if (this.shouldPreventParsing(noParseRule, this.request)) {
  1671. // We assume that we need module and exports
  1672. /** @type {NormalModuleBuildInfo} */
  1673. (this.buildInfo).parsed = false;
  1674. this._initBuildHash(compilation);
  1675. return handleBuildDone();
  1676. }
  1677. try {
  1678. const source = /** @type {Source} */ (this._source).source();
  1679. /** @type {Parser} */
  1680. (this.parser).parse(this._ast || source, {
  1681. source,
  1682. current: this,
  1683. module: this,
  1684. compilation,
  1685. options,
  1686. harmonyNamedExports: undefined,
  1687. harmonyStarExports: undefined,
  1688. lastHarmonyImportOrder: undefined,
  1689. localModules: undefined
  1690. });
  1691. } catch (parseErr) {
  1692. handleParseError(/** @type {Error} */ (parseErr));
  1693. return;
  1694. }
  1695. handleParseResult();
  1696. });
  1697. }
  1698. /**
  1699. * Returns the reason this module cannot be concatenated, when one exists.
  1700. * @param {ConcatenationBailoutReasonContext} context context
  1701. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  1702. */
  1703. getConcatenationBailoutReason(context) {
  1704. return /** @type {Generator} */ (
  1705. this.generator
  1706. ).getConcatenationBailoutReason(this, context);
  1707. }
  1708. /**
  1709. * Gets side effects connection state.
  1710. * @param {ModuleGraph} moduleGraph the module graph
  1711. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  1712. */
  1713. getSideEffectsConnectionState(moduleGraph) {
  1714. // Each call owns its Tarjan bookkeeping; re-entrant calls (e.g.
  1715. // `ConcatenatedModule.getSideEffectsConnectionState` delegating back
  1716. // through here) can't clobber the outer walk.
  1717. return walkSideEffects(
  1718. this,
  1719. moduleGraph,
  1720. HarmonyImportSideEffectDependency
  1721. );
  1722. }
  1723. /**
  1724. * Returns the source types this module can generate.
  1725. * @returns {SourceTypes} types available (do not mutate)
  1726. */
  1727. getSourceTypes() {
  1728. if (this._sourceTypes === undefined) {
  1729. this._sourceTypes = /** @type {Generator} */ (this.generator).getTypes(
  1730. this
  1731. );
  1732. }
  1733. return this._sourceTypes;
  1734. }
  1735. /**
  1736. * Freshly recomputed source types when they depend on incoming connections, for chunk-graph cache invalidation; undefined otherwise. #20800
  1737. * @returns {SourceTypes | undefined} source types or undefined
  1738. */
  1739. getReferencedSourceTypes() {
  1740. const generator = /** @type {Generator} */ (this.generator);
  1741. // Bypass the _sourceTypes cache: it may be stale when the module is not rebuilt.
  1742. return generator.getTypesDependOnIncomingConnections()
  1743. ? generator.getTypes(this)
  1744. : undefined;
  1745. }
  1746. /**
  1747. * Generates code and runtime requirements for this module.
  1748. * @param {CodeGenerationContext} context context for code generation
  1749. * @returns {CodeGenerationResult} result
  1750. */
  1751. codeGeneration({
  1752. dependencyTemplates,
  1753. runtimeTemplate,
  1754. moduleGraph,
  1755. chunkGraph,
  1756. runtime,
  1757. concatenationScope,
  1758. codeGenerationResults,
  1759. sourceTypes
  1760. }) {
  1761. /** @type {RuntimeRequirements} */
  1762. const runtimeRequirements = new Set();
  1763. const { parsed } = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1764. if (!parsed) {
  1765. runtimeRequirements.add(RuntimeGlobals.module);
  1766. runtimeRequirements.add(RuntimeGlobals.exports);
  1767. runtimeRequirements.add(RuntimeGlobals.thisAsExports);
  1768. }
  1769. const getData = () => this._codeGeneratorData;
  1770. /** @type {Sources} */
  1771. const sources = new Map();
  1772. for (const type of sourceTypes || chunkGraph.getModuleSourceTypes(this)) {
  1773. // TODO webpack@6 make generateError required
  1774. const generator =
  1775. /** @type {Generator & { generateError?: GenerateErrorFn }} */
  1776. (this.generator);
  1777. const source = this.error
  1778. ? generator.generateError
  1779. ? generator.generateError(this.error, this, {
  1780. dependencyTemplates,
  1781. runtimeTemplate,
  1782. moduleGraph,
  1783. chunkGraph,
  1784. runtimeRequirements,
  1785. runtime,
  1786. concatenationScope,
  1787. codeGenerationResults,
  1788. getData,
  1789. type
  1790. })
  1791. : new RawSource(getGenerator().throwBuildErrorCode(this.error))
  1792. : generator.generate(this, {
  1793. dependencyTemplates,
  1794. runtimeTemplate,
  1795. moduleGraph,
  1796. chunkGraph,
  1797. runtimeRequirements,
  1798. runtime,
  1799. concatenationScope,
  1800. codeGenerationResults,
  1801. getData,
  1802. type
  1803. });
  1804. if (source) {
  1805. sources.set(type, new CachedSource(source));
  1806. }
  1807. }
  1808. /** @type {CodeGenerationResult} */
  1809. const resultEntry = {
  1810. sources,
  1811. runtimeRequirements,
  1812. data: this._codeGeneratorData,
  1813. hash: undefined
  1814. };
  1815. return resultEntry;
  1816. }
  1817. /**
  1818. * Gets the original source.
  1819. * @returns {Source | null} the original source for the module before webpack transformation
  1820. */
  1821. originalSource() {
  1822. return this._source;
  1823. }
  1824. /**
  1825. * Invalidates the cached state associated with this value.
  1826. * @returns {void}
  1827. */
  1828. invalidateBuild() {
  1829. this._forceBuild = true;
  1830. }
  1831. /**
  1832. * Checks whether the module needs to be rebuilt for the current build state.
  1833. * @param {NeedBuildContext} context context info
  1834. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  1835. * @returns {void}
  1836. */
  1837. needBuild(context, callback) {
  1838. const { fileSystemInfo, compilation, valueCacheVersions } = context;
  1839. // build if enforced
  1840. if (this._forceBuild) return callback(null, true);
  1841. // always try to build in case of an error
  1842. if (this.error) return callback(null, true);
  1843. const { cacheable, snapshot, valueDependencies } =
  1844. /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1845. // always build when module is not cacheable
  1846. if (!cacheable) return callback(null, true);
  1847. // build when there is no snapshot to check
  1848. if (!snapshot) return callback(null, true);
  1849. // build when valueDependencies have changed
  1850. if (valueDependencies) {
  1851. if (!valueCacheVersions) return callback(null, true);
  1852. for (const [key, value] of valueDependencies) {
  1853. if (value === undefined) return callback(null, true);
  1854. const current = valueCacheVersions.get(key);
  1855. if (
  1856. value !== current &&
  1857. (typeof value === "string" ||
  1858. typeof current === "string" ||
  1859. current === undefined ||
  1860. !isSubset(value, current))
  1861. ) {
  1862. return callback(null, true);
  1863. }
  1864. }
  1865. }
  1866. // check snapshot for validity
  1867. fileSystemInfo.checkSnapshotValid(snapshot, (err, valid) => {
  1868. if (err) return callback(err);
  1869. if (!valid) return callback(null, true);
  1870. const hooks = NormalModule.getCompilationHooks(compilation);
  1871. hooks.needBuild.callAsync(this, context, (err, needBuild) => {
  1872. if (err) {
  1873. return callback(
  1874. HookWebpackError.makeWebpackError(
  1875. err,
  1876. "NormalModule.getCompilationHooks().needBuild"
  1877. )
  1878. );
  1879. }
  1880. callback(null, Boolean(needBuild));
  1881. });
  1882. });
  1883. }
  1884. /**
  1885. * Returns the estimated size for the requested source type.
  1886. * @param {string=} type the source type for which the size should be estimated
  1887. * @returns {number} the estimated size of the module (must be non-zero)
  1888. */
  1889. size(type) {
  1890. const cachedSize =
  1891. this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type);
  1892. if (cachedSize !== undefined) {
  1893. return cachedSize;
  1894. }
  1895. const size = Math.max(
  1896. 1,
  1897. /** @type {Generator} */ (this.generator).getSize(this, type)
  1898. );
  1899. if (this._sourceSizes === undefined) {
  1900. this._sourceSizes = new Map();
  1901. }
  1902. this._sourceSizes.set(type, size);
  1903. return size;
  1904. }
  1905. /**
  1906. * Adds the provided file dependencies to the module.
  1907. * @param {FileSystemDependencies} fileDependencies set where file dependencies are added to
  1908. * @param {FileSystemDependencies} contextDependencies set where context dependencies are added to
  1909. * @param {FileSystemDependencies} missingDependencies set where missing dependencies are added to
  1910. * @param {FileSystemDependencies} buildDependencies set where build dependencies are added to
  1911. */
  1912. addCacheDependencies(
  1913. fileDependencies,
  1914. contextDependencies,
  1915. missingDependencies,
  1916. buildDependencies
  1917. ) {
  1918. const { snapshot, buildDependencies: buildDeps } =
  1919. /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1920. if (snapshot) {
  1921. fileDependencies.addAll(snapshot.getFileIterable());
  1922. contextDependencies.addAll(snapshot.getContextIterable());
  1923. missingDependencies.addAll(snapshot.getMissingIterable());
  1924. } else {
  1925. const {
  1926. fileDependencies: fileDeps,
  1927. contextDependencies: contextDeps,
  1928. missingDependencies: missingDeps
  1929. } = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1930. if (fileDeps !== undefined) fileDependencies.addAll(fileDeps);
  1931. if (contextDeps !== undefined) contextDependencies.addAll(contextDeps);
  1932. if (missingDeps !== undefined) missingDependencies.addAll(missingDeps);
  1933. }
  1934. if (buildDeps !== undefined) {
  1935. buildDependencies.addAll(buildDeps);
  1936. }
  1937. }
  1938. /**
  1939. * Updates the hash with the data contributed by this instance.
  1940. * @param {Hash} hash the hash used to track dependencies
  1941. * @param {UpdateHashContext} context context
  1942. * @returns {void}
  1943. */
  1944. updateHash(hash, context) {
  1945. const buildInfo = /** @type {NormalModuleBuildInfo} */ (this.buildInfo);
  1946. hash.update(
  1947. /** @type {string} */
  1948. (buildInfo.hash)
  1949. );
  1950. // Clear cached source types and re-compute so that changes in incoming
  1951. // connections (e.g. asset module newly referenced from JS via lazy
  1952. // compilation) are reflected in the hash and trigger code generation
  1953. // cache invalidation.
  1954. // https://github.com/webpack/webpack/issues/20800
  1955. this._sourceTypes = undefined;
  1956. for (const type of this.getSourceTypes()) {
  1957. hash.update(type);
  1958. }
  1959. /** @type {Generator} */
  1960. (this.generator).updateHash(hash, {
  1961. module: this,
  1962. ...context
  1963. });
  1964. super.updateHash(hash, context);
  1965. }
  1966. /**
  1967. * Serializes this instance into the provided serializer context.
  1968. * @param {ObjectSerializerContext} context context
  1969. */
  1970. serialize(context) {
  1971. const { write } = context;
  1972. // deserialize
  1973. write(this._source);
  1974. write(this.error);
  1975. write(this._lastSuccessfulBuildMeta);
  1976. write(this._forceBuild);
  1977. write(this._codeGeneratorData);
  1978. write(this.hot);
  1979. super.serialize(context);
  1980. }
  1981. /**
  1982. * @param {ObjectDeserializerContext} context context
  1983. * @returns {NormalModule} module
  1984. */
  1985. static deserialize(context) {
  1986. // `new this` so subclasses without extra constructor options inherit this method
  1987. const obj = new this({
  1988. // will be deserialized by Module
  1989. layer: /** @type {EXPECTED_ANY} */ (null),
  1990. type: "",
  1991. // will be filled by updateCacheModule
  1992. resource: "",
  1993. context: "",
  1994. request: /** @type {EXPECTED_ANY} */ (null),
  1995. userRequest: /** @type {EXPECTED_ANY} */ (null),
  1996. rawRequest: /** @type {EXPECTED_ANY} */ (null),
  1997. loaders: /** @type {EXPECTED_ANY} */ (null),
  1998. matchResource: /** @type {EXPECTED_ANY} */ (null),
  1999. parser: /** @type {EXPECTED_ANY} */ (null),
  2000. parserOptions: /** @type {EXPECTED_ANY} */ (null),
  2001. generator: /** @type {EXPECTED_ANY} */ (null),
  2002. generatorOptions: /** @type {EXPECTED_ANY} */ (null),
  2003. resolveOptions: /** @type {EXPECTED_ANY} */ (null),
  2004. extractSourceMap: /** @type {EXPECTED_ANY} */ (null)
  2005. });
  2006. obj.deserialize(context);
  2007. return obj;
  2008. }
  2009. /**
  2010. * Restores this instance from the provided deserializer context.
  2011. * @param {ObjectDeserializerContext} context context
  2012. */
  2013. deserialize(context) {
  2014. const { read } = context;
  2015. this._source = read();
  2016. this.error = read();
  2017. this._lastSuccessfulBuildMeta = read();
  2018. this._forceBuild = read();
  2019. this._codeGeneratorData = read();
  2020. this.hot = read();
  2021. super.deserialize(context);
  2022. }
  2023. }
  2024. makeSerializable(NormalModule, "webpack/lib/NormalModule");
  2025. module.exports = NormalModule;