Compilation.js 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const asyncLib = require("neo-async");
  8. const {
  9. AsyncParallelHook,
  10. AsyncSeriesBailHook,
  11. AsyncSeriesHook,
  12. HookMap,
  13. SyncBailHook,
  14. SyncHook,
  15. SyncWaterfallHook
  16. } = require("tapable");
  17. const { CachedSource } = require("webpack-sources");
  18. const { MultiItemCache } = require("./CacheFacade");
  19. const Chunk = require("./Chunk");
  20. const ChunkGraph = require("./ChunkGraph");
  21. const ChunkGroup = require("./ChunkGroup");
  22. const ChunkRenderError = require("./ChunkRenderError");
  23. const ChunkTemplate = require("./ChunkTemplate");
  24. const CodeGenerationError = require("./CodeGenerationError");
  25. const CodeGenerationResults = require("./CodeGenerationResults");
  26. const Dependency = require("./Dependency");
  27. const DependencyTemplates = require("./DependencyTemplates");
  28. const Entrypoint = require("./Entrypoint");
  29. const ErrorHelpers = require("./ErrorHelpers");
  30. const FileSystemInfo = require("./FileSystemInfo");
  31. const {
  32. connectChunkGroupAndChunk,
  33. connectChunkGroupParentAndChild
  34. } = require("./GraphHelpers");
  35. const {
  36. makeWebpackError,
  37. tryRunOrWebpackError
  38. } = require("./HookWebpackError");
  39. const MainTemplate = require("./MainTemplate");
  40. const Module = require("./Module");
  41. const ModuleDependencyError = require("./ModuleDependencyError");
  42. const ModuleDependencyWarning = require("./ModuleDependencyWarning");
  43. const ModuleGraph = require("./ModuleGraph");
  44. const ModuleHashingError = require("./ModuleHashingError");
  45. const ModuleNotFoundError = require("./ModuleNotFoundError");
  46. const ModuleProfile = require("./ModuleProfile");
  47. const ModuleRestoreError = require("./ModuleRestoreError");
  48. const ModuleStoreError = require("./ModuleStoreError");
  49. const ModuleTemplate = require("./ModuleTemplate");
  50. const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
  51. const RuntimeGlobals = require("./RuntimeGlobals");
  52. const RuntimeTemplate = require("./RuntimeTemplate");
  53. const Stats = require("./Stats");
  54. const WebpackError = require("./WebpackError");
  55. const buildChunkGraph = require("./buildChunkGraph");
  56. const BuildCycleError = require("./errors/BuildCycleError");
  57. const { LogType, Logger } = require("./logging/Logger");
  58. const StatsFactory = require("./stats/StatsFactory");
  59. const StatsPrinter = require("./stats/StatsPrinter");
  60. const { equals: arrayEquals } = require("./util/ArrayHelpers");
  61. const AsyncQueue = require("./util/AsyncQueue");
  62. const LazySet = require("./util/LazySet");
  63. const { getOrInsert } = require("./util/MapHelpers");
  64. const WeakTupleMap = require("./util/WeakTupleMap");
  65. const { cachedCleverMerge } = require("./util/cleverMerge");
  66. const {
  67. compareIds,
  68. compareLocations,
  69. compareModulesByIdentifier,
  70. compareSelect,
  71. compareStringsNumeric,
  72. concatComparators
  73. } = require("./util/comparators");
  74. const createHash = require("./util/createHash");
  75. const {
  76. arrayToSetDeprecation,
  77. createFakeHook,
  78. soonFrozenObjectDeprecation
  79. } = require("./util/deprecation");
  80. const processAsyncTree = require("./util/processAsyncTree");
  81. const { getRuntimeKey } = require("./util/runtime");
  82. const { isSourceEqual } = require("./util/source");
  83. /** @template T @typedef {import("tapable").AsArray<T>} AsArray<T> */
  84. /** @typedef {import("webpack-sources").Source} Source */
  85. /** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */
  86. /** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
  87. /** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
  88. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  89. /** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */
  90. /** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */
  91. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  92. /** @typedef {import("./Cache")} Cache */
  93. /** @typedef {import("./CacheFacade")} CacheFacade */
  94. /** @typedef {import("./Chunk").ChunkName} ChunkName */
  95. /** @typedef {import("./Chunk").ChunkId} ChunkId */
  96. /** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */
  97. /** @typedef {import("./Compiler")} Compiler */
  98. /** @typedef {import("./Compiler").CompilationParams} CompilationParams */
  99. /** @typedef {import("./Compiler").MemCache} MemCache */
  100. /** @typedef {import("./Compiler").WeakReferences} WeakReferences */
  101. /** @typedef {import("./Compiler").ModuleMemCachesItem} ModuleMemCachesItem */
  102. /** @typedef {import("./Compiler").Records} Records */
  103. /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
  104. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  105. /** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */
  106. /** @typedef {import("./DependencyTemplate")} DependencyTemplate */
  107. /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
  108. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  109. /** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
  110. /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
  111. /** @typedef {import("./NormalModule").NormalModuleCompilationHooks} NormalModuleCompilationHooks */
  112. /** @typedef {import("./Module").FactoryMeta} FactoryMeta */
  113. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  114. /** @typedef {import("./ModuleFactory")} ModuleFactory */
  115. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  116. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  117. /** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */
  118. /** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */
  119. /** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
  120. /** @typedef {import("./NormalModule").ParserOptions} ParserOptions */
  121. /** @typedef {import("./NormalModule").GeneratorOptions} GeneratorOptions */
  122. /** @typedef {import("./RequestShortener")} RequestShortener */
  123. /** @typedef {import("./RuntimeModule")} RuntimeModule */
  124. /** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */
  125. /** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */
  126. /** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */
  127. /** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */
  128. /** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */
  129. /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
  130. /** @typedef {import("./util/Hash")} Hash */
  131. /** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
  132. /**
  133. * @template T
  134. * @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
  135. */
  136. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  137. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  138. /**
  139. * @callback Callback
  140. * @param {(WebpackError | null)=} err
  141. * @returns {void}
  142. */
  143. /**
  144. * @callback ModuleCallback
  145. * @param {(WebpackError | null)=} err
  146. * @param {(Module | null)=} result
  147. * @returns {void}
  148. */
  149. /**
  150. * @callback ModuleFactoryResultCallback
  151. * @param {(WebpackError | null)=} err
  152. * @param {ModuleFactoryResult=} result
  153. * @returns {void}
  154. */
  155. /**
  156. * @callback ModuleOrFactoryResultCallback
  157. * @param {(WebpackError | null)=} err
  158. * @param {Module | ModuleFactoryResult=} result
  159. * @returns {void}
  160. */
  161. /**
  162. * @callback ExecuteModuleCallback
  163. * @param {WebpackError | null} err
  164. * @param {ExecuteModuleResult=} result
  165. * @returns {void}
  166. */
  167. /** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DepConstructor */
  168. /** @typedef {Record<string, Source>} CompilationAssets */
  169. /**
  170. * @typedef {object} AvailableModulesChunkGroupMapping
  171. * @property {ChunkGroup} chunkGroup
  172. * @property {Set<Module>} availableModules
  173. * @property {boolean} needCopy
  174. */
  175. /**
  176. * @typedef {object} DependenciesBlockLike
  177. * @property {Dependency[]} dependencies
  178. * @property {AsyncDependenciesBlock[]} blocks
  179. */
  180. /**
  181. * @typedef {object} ChunkPathData
  182. * @property {string | number} id
  183. * @property {string=} name
  184. * @property {string} hash
  185. * @property {((length: number) => string)=} hashWithLength
  186. * @property {(Record<string, string>)=} contentHash
  187. * @property {(Record<string, (length: number) => string>)=} contentHashWithLength
  188. */
  189. /**
  190. * @typedef {object} ChunkHashContext
  191. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  192. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  193. * @property {ModuleGraph} moduleGraph the module graph
  194. * @property {ChunkGraph} chunkGraph the chunk graph
  195. */
  196. /**
  197. * @typedef {object} RuntimeRequirementsContext
  198. * @property {ChunkGraph} chunkGraph the chunk graph
  199. * @property {CodeGenerationResults} codeGenerationResults the code generation results
  200. */
  201. /**
  202. * @typedef {object} ExecuteModuleOptions
  203. * @property {EntryOptions=} entryOptions
  204. */
  205. /** @typedef {EXPECTED_ANY} ExecuteModuleExports */
  206. /**
  207. * @typedef {object} ExecuteModuleResult
  208. * @property {ExecuteModuleExports} exports
  209. * @property {boolean} cacheable
  210. * @property {Map<string, { source: Source, info: AssetInfo | undefined }>} assets
  211. * @property {LazySet<string>} fileDependencies
  212. * @property {LazySet<string>} contextDependencies
  213. * @property {LazySet<string>} missingDependencies
  214. * @property {LazySet<string>} buildDependencies
  215. */
  216. /**
  217. * @typedef {object} ExecuteModuleObject
  218. * @property {string=} id module id
  219. * @property {ExecuteModuleExports} exports exports
  220. * @property {boolean} loaded is loaded
  221. * @property {Error=} error error
  222. */
  223. /**
  224. * @typedef {object} ExecuteModuleArgument
  225. * @property {Module} module
  226. * @property {ExecuteModuleObject=} moduleObject
  227. * @property {TODO} preparedInfo
  228. * @property {CodeGenerationResult} codeGenerationResult
  229. */
  230. /** @typedef {((id: string) => ExecuteModuleExports) & { i?: ((options: ExecuteOptions) => void)[], c?: Record<string, ExecuteModuleObject> }} WebpackRequire */
  231. /**
  232. * @typedef {object} ExecuteOptions
  233. * @property {string=} id module id
  234. * @property {ExecuteModuleObject} module module
  235. * @property {WebpackRequire} require require function
  236. */
  237. /**
  238. * @typedef {object} ExecuteModuleContext
  239. * @property {Map<string, { source: Source, info: AssetInfo | undefined }>} assets
  240. * @property {Chunk} chunk
  241. * @property {ChunkGraph} chunkGraph
  242. * @property {WebpackRequire=} __webpack_require__
  243. */
  244. /**
  245. * @typedef {object} EntryData
  246. * @property {Dependency[]} dependencies dependencies of the entrypoint that should be evaluated at startup
  247. * @property {Dependency[]} includeDependencies dependencies of the entrypoint that should be included but not evaluated
  248. * @property {EntryOptions} options options of the entrypoint
  249. */
  250. /**
  251. * @typedef {object} LogEntry
  252. * @property {string} type
  253. * @property {EXPECTED_ANY[]=} args
  254. * @property {number} time
  255. * @property {string[]=} trace
  256. */
  257. /**
  258. * @typedef {object} KnownAssetInfo
  259. * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash)
  260. * @property {boolean=} minimized whether the asset is minimized
  261. * @property {string | string[]=} fullhash the value(s) of the full hash used for this asset
  262. * @property {string | string[]=} chunkhash the value(s) of the chunk hash used for this asset
  263. * @property {string | string[]=} modulehash the value(s) of the module hash used for this asset
  264. * @property {string | string[]=} contenthash the value(s) of the content hash used for this asset
  265. * @property {string=} sourceFilename when asset was created from a source file (potentially transformed), the original filename relative to compilation context
  266. * @property {number=} size size in bytes, only set after asset has been emitted
  267. * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets
  268. * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR)
  269. * @property {boolean=} javascriptModule true, when asset is javascript and an ESM
  270. * @property {Record<string, null | string | string[]>=} related object of pointers to other assets, keyed by type of relation (only points from parent to child)
  271. */
  272. /** @typedef {KnownAssetInfo & Record<string, EXPECTED_ANY>} AssetInfo */
  273. /** @typedef {{ path: string, info: AssetInfo }} InterpolatedPathAndAssetInfo */
  274. /**
  275. * @typedef {object} Asset
  276. * @property {string} name the filename of the asset
  277. * @property {Source} source source of the asset
  278. * @property {AssetInfo} info info about the asset
  279. */
  280. /**
  281. * @typedef {object} ModulePathData
  282. * @property {string | number} id
  283. * @property {string} hash
  284. * @property {((length: number) => string)=} hashWithLength
  285. */
  286. /**
  287. * @typedef {object} PathData
  288. * @property {ChunkGraph=} chunkGraph
  289. * @property {string=} hash
  290. * @property {((length: number) => string)=} hashWithLength
  291. * @property {(Chunk | ChunkPathData)=} chunk
  292. * @property {(Module | ModulePathData)=} module
  293. * @property {RuntimeSpec=} runtime
  294. * @property {string=} filename
  295. * @property {string=} basename
  296. * @property {string=} query
  297. * @property {string=} contentHashType
  298. * @property {string=} contentHash
  299. * @property {((length: number) => string)=} contentHashWithLength
  300. * @property {boolean=} noChunkHash
  301. * @property {string=} url
  302. */
  303. /** @typedef {"module" | "chunk" | "root-of-chunk" | "nested"} ExcludeModulesType */
  304. /**
  305. * @typedef {object} KnownNormalizedStatsOptions
  306. * @property {string} context
  307. * @property {RequestShortener} requestShortener
  308. * @property {string | false} chunksSort
  309. * @property {string | false} modulesSort
  310. * @property {string | false} chunkModulesSort
  311. * @property {string | false} nestedModulesSort
  312. * @property {string | false} assetsSort
  313. * @property {boolean} ids
  314. * @property {boolean} cachedAssets
  315. * @property {boolean} groupAssetsByEmitStatus
  316. * @property {boolean} groupAssetsByPath
  317. * @property {boolean} groupAssetsByExtension
  318. * @property {number} assetsSpace
  319. * @property {((value: string, asset: StatsAsset) => boolean)[]} excludeAssets
  320. * @property {((name: string, module: StatsModule, type: ExcludeModulesType) => boolean)[]} excludeModules
  321. * @property {((warning: StatsError, textValue: string) => boolean)[]} warningsFilter
  322. * @property {boolean} cachedModules
  323. * @property {boolean} orphanModules
  324. * @property {boolean} dependentModules
  325. * @property {boolean} runtimeModules
  326. * @property {boolean} groupModulesByCacheStatus
  327. * @property {boolean} groupModulesByLayer
  328. * @property {boolean} groupModulesByAttributes
  329. * @property {boolean} groupModulesByPath
  330. * @property {boolean} groupModulesByExtension
  331. * @property {boolean} groupModulesByType
  332. * @property {boolean | "auto"} entrypoints
  333. * @property {boolean} chunkGroups
  334. * @property {boolean} chunkGroupAuxiliary
  335. * @property {boolean} chunkGroupChildren
  336. * @property {number} chunkGroupMaxAssets
  337. * @property {number} modulesSpace
  338. * @property {number} chunkModulesSpace
  339. * @property {number} nestedModulesSpace
  340. * @property {false | "none" | "error" | "warn" | "info" | "log" | "verbose"} logging
  341. * @property {((value: string) => boolean)[]} loggingDebug
  342. * @property {boolean} loggingTrace
  343. * @property {TODO} _env
  344. */
  345. /** @typedef {KnownNormalizedStatsOptions & Omit<StatsOptions, keyof KnownNormalizedStatsOptions> & Record<string, EXPECTED_ANY>} NormalizedStatsOptions */
  346. /**
  347. * @typedef {object} KnownCreateStatsOptionsContext
  348. * @property {boolean=} forToString
  349. */
  350. /** @typedef {KnownCreateStatsOptionsContext & Record<string, EXPECTED_ANY>} CreateStatsOptionsContext */
  351. /** @typedef {{ module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}} CodeGenerationJob */
  352. /** @typedef {CodeGenerationJob[]} CodeGenerationJobs */
  353. /** @typedef {{javascript: ModuleTemplate}} ModuleTemplates */
  354. /** @typedef {Set<Module>} NotCodeGeneratedModules */
  355. /** @type {AssetInfo} */
  356. const EMPTY_ASSET_INFO = Object.freeze({});
  357. const esmDependencyCategory = "esm";
  358. // TODO webpack 6: remove
  359. const deprecatedNormalModuleLoaderHook = util.deprecate(
  360. /**
  361. * @param {Compilation} compilation compilation
  362. * @returns {NormalModuleCompilationHooks["loader"]} hooks
  363. */
  364. compilation =>
  365. require("./NormalModule").getCompilationHooks(compilation).loader,
  366. "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader",
  367. "DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK"
  368. );
  369. // TODO webpack 6: remove
  370. /**
  371. * @param {ModuleTemplates | undefined} moduleTemplates module templates
  372. */
  373. const defineRemovedModuleTemplates = moduleTemplates => {
  374. Object.defineProperties(moduleTemplates, {
  375. asset: {
  376. enumerable: false,
  377. configurable: false,
  378. get: () => {
  379. throw new WebpackError(
  380. "Compilation.moduleTemplates.asset has been removed"
  381. );
  382. }
  383. },
  384. webassembly: {
  385. enumerable: false,
  386. configurable: false,
  387. get: () => {
  388. throw new WebpackError(
  389. "Compilation.moduleTemplates.webassembly has been removed"
  390. );
  391. }
  392. }
  393. });
  394. moduleTemplates = undefined;
  395. };
  396. const byId = compareSelect(c => c.id, compareIds);
  397. const byNameOrHash = concatComparators(
  398. compareSelect(c => c.name, compareIds),
  399. compareSelect(c => c.fullHash, compareIds)
  400. );
  401. const byMessage = compareSelect(err => `${err.message}`, compareStringsNumeric);
  402. const byModule = compareSelect(
  403. err => (err.module && err.module.identifier()) || "",
  404. compareStringsNumeric
  405. );
  406. const byLocation = compareSelect(err => err.loc, compareLocations);
  407. const compareErrors = concatComparators(byModule, byLocation, byMessage);
  408. /**
  409. * @typedef {object} KnownUnsafeCacheData
  410. * @property {FactoryMeta=} factoryMeta factory meta
  411. * @property {ResolveOptions=} resolveOptions resolve options
  412. * @property {ParserOptions=} parserOptions
  413. * @property {GeneratorOptions=} generatorOptions
  414. */
  415. /** @typedef {KnownUnsafeCacheData & Record<string, EXPECTED_ANY>} UnsafeCacheData */
  416. /**
  417. * @typedef {Module & { restoreFromUnsafeCache?: (unsafeCacheData: UnsafeCacheData, moduleFactory: ModuleFactory, compilationParams: CompilationParams) => void }} ModuleWithRestoreFromUnsafeCache
  418. */
  419. /** @type {WeakMap<Dependency, ModuleWithRestoreFromUnsafeCache | null>} */
  420. const unsafeCacheDependencies = new WeakMap();
  421. /** @type {WeakMap<ModuleWithRestoreFromUnsafeCache, UnsafeCacheData>} */
  422. const unsafeCacheData = new WeakMap();
  423. /** @typedef {{ id: ModuleId, modules?: Map<Module, string | number | undefined>, blocks?: (string | number | null)[] }} References */
  424. /** @typedef {Map<Module, WeakTupleMap<EXPECTED_ANY[], EXPECTED_ANY>>} ModuleMemCaches */
  425. class Compilation {
  426. /**
  427. * Creates an instance of Compilation.
  428. * @param {Compiler} compiler the compiler which created the compilation
  429. * @param {CompilationParams} params the compilation parameters
  430. */
  431. constructor(compiler, params) {
  432. this._backCompat = compiler._backCompat;
  433. const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this);
  434. /** @typedef {{ additionalAssets?: true | TODO }} ProcessAssetsAdditionalOptions */
  435. /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */
  436. const processAssetsHook = new AsyncSeriesHook(["assets"]);
  437. let savedAssets = new Set();
  438. /**
  439. * @param {CompilationAssets} assets assets
  440. * @returns {CompilationAssets} new assets
  441. */
  442. const popNewAssets = assets => {
  443. let newAssets;
  444. for (const file of Object.keys(assets)) {
  445. if (savedAssets.has(file)) continue;
  446. if (newAssets === undefined) {
  447. newAssets = Object.create(null);
  448. }
  449. newAssets[file] = assets[file];
  450. savedAssets.add(file);
  451. }
  452. return newAssets;
  453. };
  454. processAssetsHook.intercept({
  455. name: "Compilation",
  456. call: () => {
  457. savedAssets = new Set(Object.keys(this.assets));
  458. },
  459. register: tap => {
  460. const { type, name } = tap;
  461. const { fn, additionalAssets, ...remainingTap } = tap;
  462. const additionalAssetsFn =
  463. additionalAssets === true ? fn : additionalAssets;
  464. /** @typedef {WeakSet<CompilationAssets>} ProcessedAssets */
  465. /** @type {ProcessedAssets | undefined} */
  466. const processedAssets = additionalAssetsFn ? new WeakSet() : undefined;
  467. switch (type) {
  468. case "sync":
  469. if (additionalAssetsFn) {
  470. this.hooks.processAdditionalAssets.tap(name, assets => {
  471. if (
  472. /** @type {ProcessedAssets} */
  473. (processedAssets).has(this.assets)
  474. ) {
  475. additionalAssetsFn(assets);
  476. }
  477. });
  478. }
  479. return {
  480. ...remainingTap,
  481. type: "async",
  482. /**
  483. * @param {CompilationAssets} assets assets
  484. * @param {(err?: Error | null, result?: void) => void} callback callback
  485. * @returns {void}
  486. */
  487. fn: (assets, callback) => {
  488. try {
  489. fn(assets);
  490. } catch (err) {
  491. return callback(/** @type {Error} */ (err));
  492. }
  493. if (processedAssets !== undefined) {
  494. processedAssets.add(this.assets);
  495. }
  496. const newAssets = popNewAssets(assets);
  497. if (newAssets !== undefined) {
  498. this.hooks.processAdditionalAssets.callAsync(
  499. newAssets,
  500. callback
  501. );
  502. return;
  503. }
  504. callback();
  505. }
  506. };
  507. case "async":
  508. if (additionalAssetsFn) {
  509. this.hooks.processAdditionalAssets.tapAsync(
  510. name,
  511. (assets, callback) => {
  512. if (
  513. /** @type {ProcessedAssets} */
  514. (processedAssets).has(this.assets)
  515. ) {
  516. return additionalAssetsFn(assets, callback);
  517. }
  518. callback();
  519. }
  520. );
  521. }
  522. return {
  523. ...remainingTap,
  524. /**
  525. * @param {CompilationAssets} assets assets
  526. * @param {(err?: Error | null, result?: void) => void} callback callback
  527. * @returns {void}
  528. */
  529. fn: (assets, callback) => {
  530. fn(
  531. assets,
  532. /**
  533. * @param {Error} err err
  534. * @returns {void}
  535. */
  536. err => {
  537. if (err) return callback(err);
  538. if (processedAssets !== undefined) {
  539. processedAssets.add(this.assets);
  540. }
  541. const newAssets = popNewAssets(assets);
  542. if (newAssets !== undefined) {
  543. this.hooks.processAdditionalAssets.callAsync(
  544. newAssets,
  545. callback
  546. );
  547. return;
  548. }
  549. callback();
  550. }
  551. );
  552. }
  553. };
  554. case "promise":
  555. if (additionalAssetsFn) {
  556. this.hooks.processAdditionalAssets.tapPromise(name, assets => {
  557. if (
  558. /** @type {ProcessedAssets} */
  559. (processedAssets).has(this.assets)
  560. ) {
  561. return additionalAssetsFn(assets);
  562. }
  563. return Promise.resolve();
  564. });
  565. }
  566. return {
  567. ...remainingTap,
  568. /**
  569. * @param {CompilationAssets} assets assets
  570. * @returns {Promise<CompilationAssets>} result
  571. */
  572. fn: assets => {
  573. const p = fn(assets);
  574. if (!p || !p.then) return p;
  575. return p.then(() => {
  576. if (processedAssets !== undefined) {
  577. processedAssets.add(this.assets);
  578. }
  579. const newAssets = popNewAssets(assets);
  580. if (newAssets !== undefined) {
  581. return this.hooks.processAdditionalAssets.promise(
  582. newAssets
  583. );
  584. }
  585. });
  586. }
  587. };
  588. }
  589. }
  590. });
  591. /** @type {SyncHook<[CompilationAssets]>} */
  592. const afterProcessAssetsHook = new SyncHook(["assets"]);
  593. /**
  594. * @template T
  595. * @param {string} name name of the hook
  596. * @param {number} stage new stage
  597. * @param {() => AsArray<T>} getArgs get old hook function args
  598. * @param {string=} code deprecation code (not deprecated when unset)
  599. * @returns {FakeHook<Pick<AsyncSeriesHook<T>, "tap" | "tapAsync" | "tapPromise" | "name">> | undefined} fake hook which redirects
  600. */
  601. const createProcessAssetsHook = (name, stage, getArgs, code) => {
  602. if (!this._backCompat && code) return;
  603. /**
  604. * @param {string} reason reason
  605. * @returns {string} error message
  606. */
  607. const errorMessage =
  608. reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}.
  609. BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`;
  610. /**
  611. * @param {string | (import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions)} options hook options
  612. * @returns {import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions} modified options
  613. */
  614. const getOptions = options => {
  615. if (typeof options === "string") options = { name: options };
  616. if (options.stage) {
  617. throw new Error(errorMessage("it's using the 'stage' option"));
  618. }
  619. return { ...options, stage };
  620. };
  621. return createFakeHook(
  622. {
  623. name,
  624. /** @type {AsyncSeriesHook<T>["intercept"]} */
  625. intercept(_interceptor) {
  626. throw new Error(errorMessage("it's using 'intercept'"));
  627. },
  628. /** @type {AsyncSeriesHook<T>["tap"]} */
  629. tap: (options, fn) => {
  630. processAssetsHook.tap(getOptions(options), () => fn(...getArgs()));
  631. },
  632. /** @type {AsyncSeriesHook<T>["tapAsync"]} */
  633. tapAsync: (options, fn) => {
  634. processAssetsHook.tapAsync(
  635. getOptions(options),
  636. (assets, callback) =>
  637. /** @type {TODO} */ (fn)(...getArgs(), callback)
  638. );
  639. },
  640. /** @type {AsyncSeriesHook<T>["tapPromise"]} */
  641. tapPromise: (options, fn) => {
  642. processAssetsHook.tapPromise(getOptions(options), () =>
  643. fn(...getArgs())
  644. );
  645. }
  646. },
  647. `${name} is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)`,
  648. code
  649. );
  650. };
  651. this.hooks = Object.freeze({
  652. /** @type {SyncHook<[Module]>} */
  653. buildModule: new SyncHook(["module"]),
  654. /** @type {SyncHook<[Module]>} */
  655. rebuildModule: new SyncHook(["module"]),
  656. /** @type {SyncHook<[Module, WebpackError]>} */
  657. failedModule: new SyncHook(["module", "error"]),
  658. /** @type {SyncHook<[Module]>} */
  659. succeedModule: new SyncHook(["module"]),
  660. /** @type {SyncHook<[Module]>} */
  661. stillValidModule: new SyncHook(["module"]),
  662. /** @type {SyncHook<[Dependency, EntryOptions]>} */
  663. addEntry: new SyncHook(["entry", "options"]),
  664. /** @type {SyncHook<[Dependency, EntryOptions, Error]>} */
  665. failedEntry: new SyncHook(["entry", "options", "error"]),
  666. /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */
  667. succeedEntry: new SyncHook(["entry", "options", "module"]),
  668. /** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */
  669. dependencyReferencedExports: new SyncWaterfallHook([
  670. "referencedExports",
  671. "dependency",
  672. "runtime"
  673. ]),
  674. /** @type {SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */
  675. executeModule: new SyncHook(["options", "context"]),
  676. /** @type {AsyncParallelHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */
  677. prepareModuleExecution: new AsyncParallelHook(["options", "context"]),
  678. /** @type {AsyncSeriesHook<[Iterable<Module>]>} */
  679. finishModules: new AsyncSeriesHook(["modules"]),
  680. /** @type {AsyncSeriesHook<[Module]>} */
  681. finishRebuildingModule: new AsyncSeriesHook(["module"]),
  682. /** @type {SyncHook<[]>} */
  683. unseal: new SyncHook([]),
  684. /** @type {SyncHook<[]>} */
  685. seal: new SyncHook([]),
  686. /** @type {SyncHook<[]>} */
  687. beforeChunks: new SyncHook([]),
  688. /**
  689. * The `afterChunks` hook is called directly after the chunks and module graph have
  690. * been created and before the chunks and modules have been optimized. This hook is useful to
  691. * inspect, analyze, and/or modify the chunk graph.
  692. * @type {SyncHook<[Iterable<Chunk>]>}
  693. */
  694. afterChunks: new SyncHook(["chunks"]),
  695. /** @type {SyncBailHook<[Iterable<Module>], boolean | void>} */
  696. optimizeDependencies: new SyncBailHook(["modules"]),
  697. /** @type {SyncHook<[Iterable<Module>]>} */
  698. afterOptimizeDependencies: new SyncHook(["modules"]),
  699. /** @type {SyncHook<[]>} */
  700. optimize: new SyncHook([]),
  701. /** @type {SyncBailHook<[Iterable<Module>], boolean | void>} */
  702. optimizeModules: new SyncBailHook(["modules"]),
  703. /** @type {SyncHook<[Iterable<Module>]>} */
  704. afterOptimizeModules: new SyncHook(["modules"]),
  705. /** @type {SyncBailHook<[Iterable<Chunk>, ChunkGroup[]], boolean | void>} */
  706. optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]),
  707. /** @type {SyncHook<[Iterable<Chunk>, ChunkGroup[]]>} */
  708. afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]),
  709. /** @type {AsyncSeriesHook<[Iterable<Chunk>, Iterable<Module>]>} */
  710. optimizeTree: new AsyncSeriesHook(["chunks", "modules"]),
  711. /** @type {SyncHook<[Iterable<Chunk>, Iterable<Module>]>} */
  712. afterOptimizeTree: new SyncHook(["chunks", "modules"]),
  713. /** @type {AsyncSeriesBailHook<[Iterable<Chunk>, Iterable<Module>], void>} */
  714. optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]),
  715. /** @type {SyncHook<[Iterable<Chunk>, Iterable<Module>]>} */
  716. afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]),
  717. /** @type {SyncBailHook<[], boolean | void>} */
  718. shouldRecord: new SyncBailHook([]),
  719. /** @type {SyncHook<[Chunk, Set<string>, RuntimeRequirementsContext]>} */
  720. additionalChunkRuntimeRequirements: new SyncHook([
  721. "chunk",
  722. "runtimeRequirements",
  723. "context"
  724. ]),
  725. /** @type {HookMap<SyncBailHook<[Chunk, Set<string>, RuntimeRequirementsContext], void>>} */
  726. runtimeRequirementInChunk: new HookMap(
  727. () => new SyncBailHook(["chunk", "runtimeRequirements", "context"])
  728. ),
  729. /** @type {SyncHook<[Module, Set<string>, RuntimeRequirementsContext]>} */
  730. additionalModuleRuntimeRequirements: new SyncHook([
  731. "module",
  732. "runtimeRequirements",
  733. "context"
  734. ]),
  735. /** @type {HookMap<SyncBailHook<[Module, Set<string>, RuntimeRequirementsContext], void>>} */
  736. runtimeRequirementInModule: new HookMap(
  737. () => new SyncBailHook(["module", "runtimeRequirements", "context"])
  738. ),
  739. /** @type {SyncHook<[Chunk, Set<string>, RuntimeRequirementsContext]>} */
  740. additionalTreeRuntimeRequirements: new SyncHook([
  741. "chunk",
  742. "runtimeRequirements",
  743. "context"
  744. ]),
  745. /** @type {HookMap<SyncBailHook<[Chunk, Set<string>, RuntimeRequirementsContext], void>>} */
  746. runtimeRequirementInTree: new HookMap(
  747. () => new SyncBailHook(["chunk", "runtimeRequirements", "context"])
  748. ),
  749. /** @type {SyncHook<[RuntimeModule, Chunk]>} */
  750. runtimeModule: new SyncHook(["module", "chunk"]),
  751. /** @type {SyncHook<[Iterable<Module>, Records]>} */
  752. reviveModules: new SyncHook(["modules", "records"]),
  753. /** @type {SyncHook<[Iterable<Module>]>} */
  754. beforeModuleIds: new SyncHook(["modules"]),
  755. /** @type {SyncHook<[Iterable<Module>]>} */
  756. moduleIds: new SyncHook(["modules"]),
  757. /** @type {SyncHook<[Iterable<Module>]>} */
  758. optimizeModuleIds: new SyncHook(["modules"]),
  759. /** @type {SyncHook<[Iterable<Module>]>} */
  760. afterOptimizeModuleIds: new SyncHook(["modules"]),
  761. /** @type {SyncHook<[Iterable<Chunk>, Records]>} */
  762. reviveChunks: new SyncHook(["chunks", "records"]),
  763. /** @type {SyncHook<[Iterable<Chunk>]>} */
  764. beforeChunkIds: new SyncHook(["chunks"]),
  765. /** @type {SyncHook<[Iterable<Chunk>]>} */
  766. chunkIds: new SyncHook(["chunks"]),
  767. /** @type {SyncHook<[Iterable<Chunk>]>} */
  768. optimizeChunkIds: new SyncHook(["chunks"]),
  769. /** @type {SyncHook<[Iterable<Chunk>]>} */
  770. afterOptimizeChunkIds: new SyncHook(["chunks"]),
  771. /** @type {SyncHook<[Iterable<Module>, Records]>} */
  772. recordModules: new SyncHook(["modules", "records"]),
  773. /** @type {SyncHook<[Iterable<Chunk>, Records]>} */
  774. recordChunks: new SyncHook(["chunks", "records"]),
  775. /** @type {SyncHook<[Iterable<Module>]>} */
  776. optimizeCodeGeneration: new SyncHook(["modules"]),
  777. /** @type {SyncHook<[]>} */
  778. beforeModuleHash: new SyncHook([]),
  779. /** @type {SyncHook<[]>} */
  780. afterModuleHash: new SyncHook([]),
  781. /** @type {SyncHook<[]>} */
  782. beforeCodeGeneration: new SyncHook([]),
  783. /** @type {SyncHook<[]>} */
  784. afterCodeGeneration: new SyncHook([]),
  785. /** @type {SyncHook<[]>} */
  786. beforeRuntimeRequirements: new SyncHook([]),
  787. /** @type {SyncHook<[]>} */
  788. afterRuntimeRequirements: new SyncHook([]),
  789. /** @type {SyncHook<[]>} */
  790. beforeHash: new SyncHook([]),
  791. /** @type {SyncHook<[Chunk]>} */
  792. contentHash: new SyncHook(["chunk"]),
  793. /** @type {SyncHook<[]>} */
  794. afterHash: new SyncHook([]),
  795. /** @type {SyncHook<[Records]>} */
  796. recordHash: new SyncHook(["records"]),
  797. /** @type {SyncHook<[Compilation, Records]>} */
  798. record: new SyncHook(["compilation", "records"]),
  799. /** @type {SyncHook<[]>} */
  800. beforeModuleAssets: new SyncHook([]),
  801. /** @type {SyncBailHook<[], boolean | void>} */
  802. shouldGenerateChunkAssets: new SyncBailHook([]),
  803. /** @type {SyncHook<[]>} */
  804. beforeChunkAssets: new SyncHook([]),
  805. // TODO webpack 6 remove
  806. /** @deprecated */
  807. additionalChunkAssets:
  808. /** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  809. (
  810. createProcessAssetsHook(
  811. "additionalChunkAssets",
  812. Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
  813. () => [this.chunks],
  814. "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS"
  815. )
  816. ),
  817. // TODO webpack 6 deprecate
  818. /** @deprecated */
  819. additionalAssets:
  820. /** @type {FakeHook<Pick<AsyncSeriesHook<[]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  821. (
  822. createProcessAssetsHook(
  823. "additionalAssets",
  824. Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
  825. () => []
  826. )
  827. ),
  828. // TODO webpack 6 remove
  829. /** @deprecated */
  830. optimizeChunkAssets:
  831. /** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  832. (
  833. createProcessAssetsHook(
  834. "optimizeChunkAssets",
  835. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE,
  836. () => [this.chunks],
  837. "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS"
  838. )
  839. ),
  840. // TODO webpack 6 remove
  841. /** @deprecated */
  842. afterOptimizeChunkAssets:
  843. /** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  844. (
  845. createProcessAssetsHook(
  846. "afterOptimizeChunkAssets",
  847. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1,
  848. () => [this.chunks],
  849. "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS"
  850. )
  851. ),
  852. // TODO webpack 6 deprecate
  853. /** @deprecated */
  854. optimizeAssets: processAssetsHook,
  855. // TODO webpack 6 deprecate
  856. /** @deprecated */
  857. afterOptimizeAssets: afterProcessAssetsHook,
  858. processAssets: processAssetsHook,
  859. afterProcessAssets: afterProcessAssetsHook,
  860. /** @type {AsyncSeriesHook<[CompilationAssets]>} */
  861. processAdditionalAssets: new AsyncSeriesHook(["assets"]),
  862. /** @type {SyncBailHook<[], boolean | void>} */
  863. needAdditionalSeal: new SyncBailHook([]),
  864. /** @type {AsyncSeriesHook<[]>} */
  865. afterSeal: new AsyncSeriesHook([]),
  866. /** @type {SyncWaterfallHook<[RenderManifestEntry[], RenderManifestOptions]>} */
  867. renderManifest: new SyncWaterfallHook(["result", "options"]),
  868. /** @type {SyncHook<[Hash]>} */
  869. fullHash: new SyncHook(["hash"]),
  870. /** @type {SyncHook<[Chunk, Hash, ChunkHashContext]>} */
  871. chunkHash: new SyncHook(["chunk", "chunkHash", "ChunkHashContext"]),
  872. /** @type {SyncHook<[Module, string]>} */
  873. moduleAsset: new SyncHook(["module", "filename"]),
  874. /** @type {SyncHook<[Chunk, string]>} */
  875. chunkAsset: new SyncHook(["chunk", "filename"]),
  876. /** @type {SyncWaterfallHook<[string, PathData, AssetInfo | undefined]>} */
  877. assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]),
  878. /** @type {SyncBailHook<[], boolean | void>} */
  879. needAdditionalPass: new SyncBailHook([]),
  880. /** @type {SyncHook<[Compiler, string, number]>} */
  881. childCompiler: new SyncHook([
  882. "childCompiler",
  883. "compilerName",
  884. "compilerIndex"
  885. ]),
  886. /** @type {SyncBailHook<[string, LogEntry], boolean | void>} */
  887. log: new SyncBailHook(["origin", "logEntry"]),
  888. /** @type {SyncWaterfallHook<[Error[]]>} */
  889. processWarnings: new SyncWaterfallHook(["warnings"]),
  890. /** @type {SyncWaterfallHook<[Error[]]>} */
  891. processErrors: new SyncWaterfallHook(["errors"]),
  892. /** @type {HookMap<SyncHook<[Partial<NormalizedStatsOptions>, CreateStatsOptionsContext]>>} */
  893. statsPreset: new HookMap(() => new SyncHook(["options", "context"])),
  894. /** @type {SyncHook<[Partial<NormalizedStatsOptions>, CreateStatsOptionsContext]>} */
  895. statsNormalize: new SyncHook(["options", "context"]),
  896. /** @type {SyncHook<[StatsFactory, NormalizedStatsOptions]>} */
  897. statsFactory: new SyncHook(["statsFactory", "options"]),
  898. /** @type {SyncHook<[StatsPrinter, NormalizedStatsOptions]>} */
  899. statsPrinter: new SyncHook(["statsPrinter", "options"]),
  900. get normalModuleLoader() {
  901. return getNormalModuleLoader();
  902. }
  903. });
  904. /** @type {string=} */
  905. this.name = undefined;
  906. /** @type {number | undefined} */
  907. this.startTime = undefined;
  908. /** @type {number | undefined} */
  909. this.endTime = undefined;
  910. /** @type {Compiler} */
  911. this.compiler = compiler;
  912. this.resolverFactory = compiler.resolverFactory;
  913. /** @type {InputFileSystem} */
  914. this.inputFileSystem =
  915. /** @type {InputFileSystem} */
  916. (compiler.inputFileSystem);
  917. this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, {
  918. unmanagedPaths: compiler.unmanagedPaths,
  919. managedPaths: compiler.managedPaths,
  920. immutablePaths: compiler.immutablePaths,
  921. logger: this.getLogger("webpack.FileSystemInfo"),
  922. hashFunction: compiler.options.output.hashFunction
  923. });
  924. if (compiler.fileTimestamps) {
  925. this.fileSystemInfo.addFileTimestamps(compiler.fileTimestamps, true);
  926. }
  927. if (compiler.contextTimestamps) {
  928. this.fileSystemInfo.addContextTimestamps(
  929. compiler.contextTimestamps,
  930. true
  931. );
  932. }
  933. /** @type {ValueCacheVersions} */
  934. this.valueCacheVersions = new Map();
  935. this.requestShortener = compiler.requestShortener;
  936. this.compilerPath = compiler.compilerPath;
  937. this.logger = this.getLogger("webpack.Compilation");
  938. const options = /** @type {WebpackOptions} */ (compiler.options);
  939. this.options = options;
  940. this.outputOptions = options && options.output;
  941. /** @type {boolean} */
  942. this.bail = (options && options.bail) || false;
  943. /** @type {boolean} */
  944. this.profile = (options && options.profile) || false;
  945. this.params = params;
  946. this.mainTemplate = new MainTemplate(this.outputOptions, this);
  947. this.chunkTemplate = new ChunkTemplate(this.outputOptions, this);
  948. this.runtimeTemplate = new RuntimeTemplate(
  949. this,
  950. this.outputOptions,
  951. this.requestShortener
  952. );
  953. /** @type {ModuleTemplates} */
  954. this.moduleTemplates = {
  955. javascript: new ModuleTemplate(this.runtimeTemplate, this)
  956. };
  957. defineRemovedModuleTemplates(this.moduleTemplates);
  958. // We need to think how implement types here
  959. /** @type {ModuleMemCaches | undefined} */
  960. this.moduleMemCaches = undefined;
  961. /** @type {ModuleMemCaches | undefined} */
  962. this.moduleMemCaches2 = undefined;
  963. this.moduleGraph = new ModuleGraph();
  964. /** @type {ChunkGraph} */
  965. this.chunkGraph = /** @type {TODO} */ (undefined);
  966. /** @type {CodeGenerationResults} */
  967. this.codeGenerationResults = /** @type {TODO} */ (undefined);
  968. /** @type {AsyncQueue<Module, Module, Module>} */
  969. this.processDependenciesQueue = new AsyncQueue({
  970. name: "processDependencies",
  971. parallelism: options.parallelism || 100,
  972. processor: this._processModuleDependencies.bind(this)
  973. });
  974. /** @type {AsyncQueue<Module, string, Module>} */
  975. this.addModuleQueue = new AsyncQueue({
  976. name: "addModule",
  977. parent: this.processDependenciesQueue,
  978. getKey: module => module.identifier(),
  979. processor: this._addModule.bind(this)
  980. });
  981. /** @type {AsyncQueue<FactorizeModuleOptions, string, Module | ModuleFactoryResult>} */
  982. this.factorizeQueue = new AsyncQueue({
  983. name: "factorize",
  984. parent: this.addModuleQueue,
  985. processor: this._factorizeModule.bind(this)
  986. });
  987. /** @type {AsyncQueue<Module, Module, Module>} */
  988. this.buildQueue = new AsyncQueue({
  989. name: "build",
  990. parent: this.factorizeQueue,
  991. processor: this._buildModule.bind(this)
  992. });
  993. /** @type {AsyncQueue<Module, Module, Module>} */
  994. this.rebuildQueue = new AsyncQueue({
  995. name: "rebuild",
  996. parallelism: options.parallelism || 100,
  997. processor: this._rebuildModule.bind(this)
  998. });
  999. /**
  1000. * Modules in value are building during the build of Module in key.
  1001. * Means value blocking key from finishing.
  1002. * Needed to detect build cycles.
  1003. * @type {WeakMap<Module, Set<Module>>}
  1004. */
  1005. this.creatingModuleDuringBuild = new WeakMap();
  1006. /** @type {Map<Exclude<ChunkName, null>, EntryData>} */
  1007. this.entries = new Map();
  1008. /** @type {EntryData} */
  1009. this.globalEntry = {
  1010. dependencies: [],
  1011. includeDependencies: [],
  1012. options: {
  1013. name: undefined
  1014. }
  1015. };
  1016. /** @type {Map<string, Entrypoint>} */
  1017. this.entrypoints = new Map();
  1018. /** @type {Entrypoint[]} */
  1019. this.asyncEntrypoints = [];
  1020. /** @type {Set<Chunk>} */
  1021. this.chunks = new Set();
  1022. /** @type {ChunkGroup[]} */
  1023. this.chunkGroups = [];
  1024. /** @type {Map<string, ChunkGroup>} */
  1025. this.namedChunkGroups = new Map();
  1026. /** @type {Map<string, Chunk>} */
  1027. this.namedChunks = new Map();
  1028. /** @type {Set<Module>} */
  1029. this.modules = new Set();
  1030. if (this._backCompat) {
  1031. arrayToSetDeprecation(this.chunks, "Compilation.chunks");
  1032. arrayToSetDeprecation(this.modules, "Compilation.modules");
  1033. }
  1034. /**
  1035. * @private
  1036. * @type {Map<string, Module>}
  1037. */
  1038. this._modules = new Map();
  1039. /** @type {Records | null} */
  1040. this.records = null;
  1041. /** @type {string[]} */
  1042. this.additionalChunkAssets = [];
  1043. /** @type {CompilationAssets} */
  1044. this.assets = {};
  1045. /** @type {Map<string, AssetInfo>} */
  1046. this.assetsInfo = new Map();
  1047. /** @type {Map<string, Map<string, Set<string>>>} */
  1048. this._assetsRelatedIn = new Map();
  1049. /** @type {Error[]} */
  1050. this.errors = [];
  1051. /** @type {Error[]} */
  1052. this.warnings = [];
  1053. /** @type {Compilation[]} */
  1054. this.children = [];
  1055. /** @type {Map<string, LogEntry[]>} */
  1056. this.logging = new Map();
  1057. /** @type {Map<DepConstructor, ModuleFactory>} */
  1058. this.dependencyFactories = new Map();
  1059. /** @type {DependencyTemplates} */
  1060. this.dependencyTemplates = new DependencyTemplates(
  1061. this.outputOptions.hashFunction
  1062. );
  1063. /** @type {Record<string, number>} */
  1064. this.childrenCounters = {};
  1065. /** @type {Set<number|string> | null} */
  1066. this.usedChunkIds = null;
  1067. /** @type {Set<number> | null} */
  1068. this.usedModuleIds = null;
  1069. /** @type {boolean} */
  1070. this.needAdditionalPass = false;
  1071. /** @type {Set<ModuleWithRestoreFromUnsafeCache>} */
  1072. this._restoredUnsafeCacheModuleEntries = new Set();
  1073. /** @type {Map<string, ModuleWithRestoreFromUnsafeCache>} */
  1074. this._restoredUnsafeCacheEntries = new Map();
  1075. /** @type {WeakSet<Module>} */
  1076. this.builtModules = new WeakSet();
  1077. /** @type {WeakSet<Module>} */
  1078. this.codeGeneratedModules = new WeakSet();
  1079. /** @type {WeakSet<Module>} */
  1080. this.buildTimeExecutedModules = new WeakSet();
  1081. /** @type {Set<string>} */
  1082. this.emittedAssets = new Set();
  1083. /** @type {Set<string>} */
  1084. this.comparedForEmitAssets = new Set();
  1085. /** @type {LazySet<string>} */
  1086. this.fileDependencies = new LazySet();
  1087. /** @type {LazySet<string>} */
  1088. this.contextDependencies = new LazySet();
  1089. /** @type {LazySet<string>} */
  1090. this.missingDependencies = new LazySet();
  1091. /** @type {LazySet<string>} */
  1092. this.buildDependencies = new LazySet();
  1093. // TODO webpack 6 remove
  1094. this.compilationDependencies = {
  1095. add: util.deprecate(
  1096. /**
  1097. * @param {string} item item
  1098. * @returns {LazySet<string>} file dependencies
  1099. */
  1100. item => this.fileDependencies.add(item),
  1101. "Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)",
  1102. "DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES"
  1103. )
  1104. };
  1105. this._modulesCache = this.getCache("Compilation/modules");
  1106. this._assetsCache = this.getCache("Compilation/assets");
  1107. this._codeGenerationCache = this.getCache("Compilation/codeGeneration");
  1108. const unsafeCache = options.module.unsafeCache;
  1109. this._unsafeCache = Boolean(unsafeCache);
  1110. this._unsafeCachePredicate =
  1111. typeof unsafeCache === "function" ? unsafeCache : () => true;
  1112. }
  1113. getStats() {
  1114. return new Stats(this);
  1115. }
  1116. /**
  1117. * @param {string | boolean | StatsOptions | undefined} optionsOrPreset stats option value
  1118. * @param {CreateStatsOptionsContext=} context context
  1119. * @returns {NormalizedStatsOptions} normalized options
  1120. */
  1121. createStatsOptions(optionsOrPreset, context = {}) {
  1122. if (typeof optionsOrPreset === "boolean") {
  1123. optionsOrPreset = {
  1124. preset: optionsOrPreset === false ? "none" : "normal"
  1125. };
  1126. } else if (typeof optionsOrPreset === "string") {
  1127. optionsOrPreset = { preset: optionsOrPreset };
  1128. }
  1129. if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) {
  1130. // We use this method of shallow cloning this object to include
  1131. // properties in the prototype chain
  1132. /** @type {Partial<NormalizedStatsOptions>} */
  1133. const options = {};
  1134. for (const key in optionsOrPreset) {
  1135. options[key] = optionsOrPreset[/** @type {keyof StatsOptions} */ (key)];
  1136. }
  1137. if (options.preset !== undefined) {
  1138. this.hooks.statsPreset.for(options.preset).call(options, context);
  1139. }
  1140. this.hooks.statsNormalize.call(options, context);
  1141. return /** @type {NormalizedStatsOptions} */ (options);
  1142. }
  1143. /** @type {Partial<NormalizedStatsOptions>} */
  1144. const options = {};
  1145. this.hooks.statsNormalize.call(options, context);
  1146. return /** @type {NormalizedStatsOptions} */ (options);
  1147. }
  1148. /**
  1149. * @param {NormalizedStatsOptions} options options
  1150. * @returns {StatsFactory} the stats factory
  1151. */
  1152. createStatsFactory(options) {
  1153. const statsFactory = new StatsFactory();
  1154. this.hooks.statsFactory.call(statsFactory, options);
  1155. return statsFactory;
  1156. }
  1157. /**
  1158. * @param {NormalizedStatsOptions} options options
  1159. * @returns {StatsPrinter} the stats printer
  1160. */
  1161. createStatsPrinter(options) {
  1162. const statsPrinter = new StatsPrinter();
  1163. this.hooks.statsPrinter.call(statsPrinter, options);
  1164. return statsPrinter;
  1165. }
  1166. /**
  1167. * @param {string} name cache name
  1168. * @returns {CacheFacade} the cache facade instance
  1169. */
  1170. getCache(name) {
  1171. return this.compiler.getCache(name);
  1172. }
  1173. /**
  1174. * @param {string | (() => string)} name name of the logger, or function called once to get the logger name
  1175. * @returns {Logger} a logger with that name
  1176. */
  1177. getLogger(name) {
  1178. if (!name) {
  1179. throw new TypeError("Compilation.getLogger(name) called without a name");
  1180. }
  1181. /** @type {LogEntry[] | undefined} */
  1182. let logEntries;
  1183. return new Logger(
  1184. (type, args) => {
  1185. if (typeof name === "function") {
  1186. name = name();
  1187. if (!name) {
  1188. throw new TypeError(
  1189. "Compilation.getLogger(name) called with a function not returning a name"
  1190. );
  1191. }
  1192. }
  1193. let trace;
  1194. switch (type) {
  1195. case LogType.warn:
  1196. case LogType.error:
  1197. case LogType.trace:
  1198. trace = ErrorHelpers.cutOffLoaderExecution(
  1199. /** @type {string} */ (new Error("Trace").stack)
  1200. )
  1201. .split("\n")
  1202. .slice(3);
  1203. break;
  1204. }
  1205. /** @type {LogEntry} */
  1206. const logEntry = {
  1207. time: Date.now(),
  1208. type,
  1209. args,
  1210. trace
  1211. };
  1212. /* eslint-disable no-console */
  1213. if (this.hooks.log.call(name, logEntry) === undefined) {
  1214. if (
  1215. logEntry.type === LogType.profileEnd &&
  1216. typeof console.profileEnd === "function"
  1217. ) {
  1218. console.profileEnd(
  1219. `[${name}] ${/** @type {NonNullable<LogEntry["args"]>} */ (logEntry.args)[0]}`
  1220. );
  1221. }
  1222. if (logEntries === undefined) {
  1223. logEntries = this.logging.get(name);
  1224. if (logEntries === undefined) {
  1225. logEntries = [];
  1226. this.logging.set(name, logEntries);
  1227. }
  1228. }
  1229. logEntries.push(logEntry);
  1230. if (
  1231. logEntry.type === LogType.profile &&
  1232. typeof console.profile === "function"
  1233. ) {
  1234. console.profile(
  1235. `[${name}] ${
  1236. /** @type {NonNullable<LogEntry["args"]>} */
  1237. (logEntry.args)[0]
  1238. }`
  1239. );
  1240. }
  1241. /* eslint-enable no-console */
  1242. }
  1243. },
  1244. childName => {
  1245. if (typeof name === "function") {
  1246. if (typeof childName === "function") {
  1247. return this.getLogger(() => {
  1248. if (typeof name === "function") {
  1249. name = name();
  1250. if (!name) {
  1251. throw new TypeError(
  1252. "Compilation.getLogger(name) called with a function not returning a name"
  1253. );
  1254. }
  1255. }
  1256. if (typeof childName === "function") {
  1257. childName = childName();
  1258. if (!childName) {
  1259. throw new TypeError(
  1260. "Logger.getChildLogger(name) called with a function not returning a name"
  1261. );
  1262. }
  1263. }
  1264. return `${name}/${childName}`;
  1265. });
  1266. }
  1267. return this.getLogger(() => {
  1268. if (typeof name === "function") {
  1269. name = name();
  1270. if (!name) {
  1271. throw new TypeError(
  1272. "Compilation.getLogger(name) called with a function not returning a name"
  1273. );
  1274. }
  1275. }
  1276. return `${name}/${childName}`;
  1277. });
  1278. }
  1279. if (typeof childName === "function") {
  1280. return this.getLogger(() => {
  1281. if (typeof childName === "function") {
  1282. childName = childName();
  1283. if (!childName) {
  1284. throw new TypeError(
  1285. "Logger.getChildLogger(name) called with a function not returning a name"
  1286. );
  1287. }
  1288. }
  1289. return `${name}/${childName}`;
  1290. });
  1291. }
  1292. return this.getLogger(`${name}/${childName}`);
  1293. }
  1294. );
  1295. }
  1296. /**
  1297. * @param {Module} module module to be added that was created
  1298. * @param {ModuleCallback} callback returns the module in the compilation,
  1299. * it could be the passed one (if new), or an already existing in the compilation
  1300. * @returns {void}
  1301. */
  1302. addModule(module, callback) {
  1303. this.addModuleQueue.add(module, callback);
  1304. }
  1305. /**
  1306. * @param {Module} module module to be added that was created
  1307. * @param {ModuleCallback} callback returns the module in the compilation,
  1308. * it could be the passed one (if new), or an already existing in the compilation
  1309. * @returns {void}
  1310. */
  1311. _addModule(module, callback) {
  1312. const identifier = module.identifier();
  1313. const alreadyAddedModule = this._modules.get(identifier);
  1314. if (alreadyAddedModule) {
  1315. return callback(null, alreadyAddedModule);
  1316. }
  1317. const currentProfile = this.profile
  1318. ? this.moduleGraph.getProfile(module)
  1319. : undefined;
  1320. if (currentProfile !== undefined) {
  1321. currentProfile.markRestoringStart();
  1322. }
  1323. this._modulesCache.get(identifier, null, (err, cacheModule) => {
  1324. if (err) return callback(new ModuleRestoreError(module, err));
  1325. if (currentProfile !== undefined) {
  1326. currentProfile.markRestoringEnd();
  1327. currentProfile.markIntegrationStart();
  1328. }
  1329. if (cacheModule) {
  1330. cacheModule.updateCacheModule(module);
  1331. module = cacheModule;
  1332. }
  1333. this._modules.set(identifier, module);
  1334. this.modules.add(module);
  1335. if (this._backCompat) {
  1336. ModuleGraph.setModuleGraphForModule(module, this.moduleGraph);
  1337. }
  1338. if (currentProfile !== undefined) {
  1339. currentProfile.markIntegrationEnd();
  1340. }
  1341. callback(null, module);
  1342. });
  1343. }
  1344. /**
  1345. * Fetches a module from a compilation by its identifier
  1346. * @param {Module} module the module provided
  1347. * @returns {Module} the module requested
  1348. */
  1349. getModule(module) {
  1350. const identifier = module.identifier();
  1351. return /** @type {Module} */ (this._modules.get(identifier));
  1352. }
  1353. /**
  1354. * Attempts to search for a module by its identifier
  1355. * @param {string} identifier identifier (usually path) for module
  1356. * @returns {Module|undefined} attempt to search for module and return it, else undefined
  1357. */
  1358. findModule(identifier) {
  1359. return this._modules.get(identifier);
  1360. }
  1361. /**
  1362. * Schedules a build of the module object
  1363. * @param {Module} module module to be built
  1364. * @param {ModuleCallback} callback the callback
  1365. * @returns {void}
  1366. */
  1367. buildModule(module, callback) {
  1368. this.buildQueue.add(module, callback);
  1369. }
  1370. /**
  1371. * Builds the module object
  1372. * @param {Module} module module to be built
  1373. * @param {ModuleCallback} callback the callback
  1374. * @returns {void}
  1375. */
  1376. _buildModule(module, callback) {
  1377. const currentProfile = this.profile
  1378. ? this.moduleGraph.getProfile(module)
  1379. : undefined;
  1380. if (currentProfile !== undefined) {
  1381. currentProfile.markBuildingStart();
  1382. }
  1383. module.needBuild(
  1384. {
  1385. compilation: this,
  1386. fileSystemInfo: this.fileSystemInfo,
  1387. valueCacheVersions: this.valueCacheVersions
  1388. },
  1389. (err, needBuild) => {
  1390. if (err) return callback(err);
  1391. if (!needBuild) {
  1392. if (currentProfile !== undefined) {
  1393. currentProfile.markBuildingEnd();
  1394. }
  1395. this.hooks.stillValidModule.call(module);
  1396. return callback();
  1397. }
  1398. this.hooks.buildModule.call(module);
  1399. this.builtModules.add(module);
  1400. module.build(
  1401. this.options,
  1402. this,
  1403. this.resolverFactory.get("normal", module.resolveOptions),
  1404. /** @type {InputFileSystem} */
  1405. (this.inputFileSystem),
  1406. err => {
  1407. if (currentProfile !== undefined) {
  1408. currentProfile.markBuildingEnd();
  1409. }
  1410. if (err) {
  1411. this.hooks.failedModule.call(module, err);
  1412. return callback(err);
  1413. }
  1414. if (currentProfile !== undefined) {
  1415. currentProfile.markStoringStart();
  1416. }
  1417. this._modulesCache.store(module.identifier(), null, module, err => {
  1418. if (currentProfile !== undefined) {
  1419. currentProfile.markStoringEnd();
  1420. }
  1421. if (err) {
  1422. this.hooks.failedModule.call(
  1423. module,
  1424. /** @type {WebpackError} */ (err)
  1425. );
  1426. return callback(new ModuleStoreError(module, err));
  1427. }
  1428. this.hooks.succeedModule.call(module);
  1429. return callback();
  1430. });
  1431. }
  1432. );
  1433. }
  1434. );
  1435. }
  1436. /**
  1437. * @param {Module} module to be processed for deps
  1438. * @param {ModuleCallback} callback callback to be triggered
  1439. * @returns {void}
  1440. */
  1441. processModuleDependencies(module, callback) {
  1442. this.processDependenciesQueue.add(module, callback);
  1443. }
  1444. /**
  1445. * @param {Module} module to be processed for deps
  1446. * @returns {void}
  1447. */
  1448. processModuleDependenciesNonRecursive(module) {
  1449. /**
  1450. * @param {DependenciesBlock} block block
  1451. */
  1452. const processDependenciesBlock = block => {
  1453. if (block.dependencies) {
  1454. let i = 0;
  1455. for (const dep of block.dependencies) {
  1456. this.moduleGraph.setParents(dep, block, module, i++);
  1457. }
  1458. }
  1459. if (block.blocks) {
  1460. for (const b of block.blocks) processDependenciesBlock(b);
  1461. }
  1462. };
  1463. processDependenciesBlock(module);
  1464. }
  1465. /**
  1466. * @param {Module} module to be processed for deps
  1467. * @param {ModuleCallback} callback callback to be triggered
  1468. * @returns {void}
  1469. */
  1470. _processModuleDependencies(module, callback) {
  1471. /** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], context: string|undefined, originModule: Module|null}>} */
  1472. const sortedDependencies = [];
  1473. /** @type {DependenciesBlock} */
  1474. let currentBlock;
  1475. /** @type {Map<ModuleFactory, Map<string, Dependency[]>>} */
  1476. let dependencies;
  1477. /** @type {DepConstructor} */
  1478. let factoryCacheKey;
  1479. /** @type {ModuleFactory} */
  1480. let factoryCacheKey2;
  1481. /** @typedef {Map<string, Dependency[]>} FactoryCacheValue */
  1482. /** @type {FactoryCacheValue | undefined} */
  1483. let factoryCacheValue;
  1484. /** @type {string} */
  1485. let listCacheKey1;
  1486. /** @type {string} */
  1487. let listCacheKey2;
  1488. /** @type {Dependency[]} */
  1489. let listCacheValue;
  1490. let inProgressSorting = 1;
  1491. let inProgressTransitive = 1;
  1492. /**
  1493. * @param {WebpackError=} err error
  1494. * @returns {void}
  1495. */
  1496. const onDependenciesSorted = err => {
  1497. if (err) return callback(err);
  1498. // early exit without changing parallelism back and forth
  1499. if (sortedDependencies.length === 0 && inProgressTransitive === 1) {
  1500. return callback();
  1501. }
  1502. // This is nested so we need to allow one additional task
  1503. this.processDependenciesQueue.increaseParallelism();
  1504. for (const item of sortedDependencies) {
  1505. inProgressTransitive++;
  1506. // eslint-disable-next-line no-loop-func
  1507. this.handleModuleCreation(item, err => {
  1508. // In V8, the Error objects keep a reference to the functions on the stack. These warnings &
  1509. // errors are created inside closures that keep a reference to the Compilation, so errors are
  1510. // leaking the Compilation object.
  1511. if (err && this.bail) {
  1512. if (inProgressTransitive <= 0) return;
  1513. inProgressTransitive = -1;
  1514. // eslint-disable-next-line no-self-assign
  1515. err.stack = err.stack;
  1516. onTransitiveTasksFinished(err);
  1517. return;
  1518. }
  1519. if (--inProgressTransitive === 0) onTransitiveTasksFinished();
  1520. });
  1521. }
  1522. if (--inProgressTransitive === 0) onTransitiveTasksFinished();
  1523. };
  1524. /**
  1525. * @param {WebpackError=} err error
  1526. * @returns {void}
  1527. */
  1528. const onTransitiveTasksFinished = err => {
  1529. if (err) return callback(err);
  1530. this.processDependenciesQueue.decreaseParallelism();
  1531. return callback();
  1532. };
  1533. /**
  1534. * @param {Dependency} dep dependency
  1535. * @param {number} index index in block
  1536. * @returns {void}
  1537. */
  1538. const processDependency = (dep, index) => {
  1539. this.moduleGraph.setParents(dep, currentBlock, module, index);
  1540. if (this._unsafeCache) {
  1541. try {
  1542. const unsafeCachedModule = unsafeCacheDependencies.get(dep);
  1543. if (unsafeCachedModule === null) return;
  1544. if (unsafeCachedModule !== undefined) {
  1545. if (
  1546. this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule)
  1547. ) {
  1548. this._handleExistingModuleFromUnsafeCache(
  1549. module,
  1550. dep,
  1551. unsafeCachedModule
  1552. );
  1553. return;
  1554. }
  1555. const identifier = unsafeCachedModule.identifier();
  1556. const cachedModule =
  1557. this._restoredUnsafeCacheEntries.get(identifier);
  1558. if (cachedModule !== undefined) {
  1559. // update unsafe cache to new module
  1560. unsafeCacheDependencies.set(dep, cachedModule);
  1561. this._handleExistingModuleFromUnsafeCache(
  1562. module,
  1563. dep,
  1564. cachedModule
  1565. );
  1566. return;
  1567. }
  1568. inProgressSorting++;
  1569. this._modulesCache.get(identifier, null, (err, cachedModule) => {
  1570. if (err) {
  1571. if (inProgressSorting <= 0) return;
  1572. inProgressSorting = -1;
  1573. onDependenciesSorted(/** @type {WebpackError} */ (err));
  1574. return;
  1575. }
  1576. try {
  1577. if (!this._restoredUnsafeCacheEntries.has(identifier)) {
  1578. const data = unsafeCacheData.get(cachedModule);
  1579. if (data === undefined) {
  1580. processDependencyForResolving(dep);
  1581. if (--inProgressSorting === 0) onDependenciesSorted();
  1582. return;
  1583. }
  1584. if (cachedModule !== unsafeCachedModule) {
  1585. unsafeCacheDependencies.set(dep, cachedModule);
  1586. }
  1587. cachedModule.restoreFromUnsafeCache(
  1588. data,
  1589. this.params.normalModuleFactory,
  1590. this.params
  1591. );
  1592. this._restoredUnsafeCacheEntries.set(
  1593. identifier,
  1594. cachedModule
  1595. );
  1596. this._restoredUnsafeCacheModuleEntries.add(cachedModule);
  1597. if (!this.modules.has(cachedModule)) {
  1598. inProgressTransitive++;
  1599. this._handleNewModuleFromUnsafeCache(
  1600. module,
  1601. dep,
  1602. cachedModule,
  1603. err => {
  1604. if (err) {
  1605. if (inProgressTransitive <= 0) return;
  1606. inProgressTransitive = -1;
  1607. onTransitiveTasksFinished(err);
  1608. }
  1609. if (--inProgressTransitive === 0) {
  1610. return onTransitiveTasksFinished();
  1611. }
  1612. }
  1613. );
  1614. if (--inProgressSorting === 0) onDependenciesSorted();
  1615. return;
  1616. }
  1617. }
  1618. if (unsafeCachedModule !== cachedModule) {
  1619. unsafeCacheDependencies.set(dep, cachedModule);
  1620. }
  1621. this._handleExistingModuleFromUnsafeCache(
  1622. module,
  1623. dep,
  1624. cachedModule
  1625. ); // a3
  1626. } catch (err) {
  1627. if (inProgressSorting <= 0) return;
  1628. inProgressSorting = -1;
  1629. onDependenciesSorted(/** @type {WebpackError} */ (err));
  1630. return;
  1631. }
  1632. if (--inProgressSorting === 0) onDependenciesSorted();
  1633. });
  1634. return;
  1635. }
  1636. } catch (err) {
  1637. // eslint-disable-next-line no-console
  1638. console.error(err);
  1639. }
  1640. }
  1641. processDependencyForResolving(dep);
  1642. };
  1643. /**
  1644. * @param {Dependency} dep dependency
  1645. * @returns {void}
  1646. */
  1647. const processDependencyForResolving = dep => {
  1648. const resourceIdent = dep.getResourceIdentifier();
  1649. if (resourceIdent !== undefined && resourceIdent !== null) {
  1650. const category = dep.category;
  1651. const constructor = /** @type {DepConstructor} */ (dep.constructor);
  1652. if (factoryCacheKey === constructor) {
  1653. // Fast path 1: same constructor as prev item
  1654. if (listCacheKey1 === category && listCacheKey2 === resourceIdent) {
  1655. // Super fast path 1: also same resource
  1656. listCacheValue.push(dep);
  1657. return;
  1658. }
  1659. } else {
  1660. const factory = this.dependencyFactories.get(constructor);
  1661. if (factory === undefined) {
  1662. throw new Error(
  1663. `No module factory available for dependency type: ${constructor.name}`
  1664. );
  1665. }
  1666. if (factoryCacheKey2 === factory) {
  1667. // Fast path 2: same factory as prev item
  1668. factoryCacheKey = constructor;
  1669. if (listCacheKey1 === category && listCacheKey2 === resourceIdent) {
  1670. // Super fast path 2: also same resource
  1671. listCacheValue.push(dep);
  1672. return;
  1673. }
  1674. } else {
  1675. // Slow path
  1676. if (factoryCacheKey2 !== undefined) {
  1677. // Archive last cache entry
  1678. if (dependencies === undefined) dependencies = new Map();
  1679. dependencies.set(
  1680. factoryCacheKey2,
  1681. /** @type {FactoryCacheValue} */ (factoryCacheValue)
  1682. );
  1683. factoryCacheValue = dependencies.get(factory);
  1684. if (factoryCacheValue === undefined) {
  1685. factoryCacheValue = new Map();
  1686. }
  1687. } else {
  1688. factoryCacheValue = new Map();
  1689. }
  1690. factoryCacheKey = constructor;
  1691. factoryCacheKey2 = factory;
  1692. }
  1693. }
  1694. // Here webpack is using heuristic that assumes
  1695. // mostly esm dependencies would be used
  1696. // so we don't allocate extra string for them
  1697. const cacheKey =
  1698. category === esmDependencyCategory
  1699. ? resourceIdent
  1700. : `${category}${resourceIdent}`;
  1701. let list = /** @type {FactoryCacheValue} */ (factoryCacheValue).get(
  1702. cacheKey
  1703. );
  1704. if (list === undefined) {
  1705. /** @type {FactoryCacheValue} */
  1706. (factoryCacheValue).set(cacheKey, (list = []));
  1707. sortedDependencies.push({
  1708. factory: factoryCacheKey2,
  1709. dependencies: list,
  1710. context: dep.getContext(),
  1711. originModule: module
  1712. });
  1713. }
  1714. list.push(dep);
  1715. listCacheKey1 = category;
  1716. listCacheKey2 = resourceIdent;
  1717. listCacheValue = list;
  1718. }
  1719. };
  1720. try {
  1721. /** @type {DependenciesBlock[]} */
  1722. const queue = [module];
  1723. do {
  1724. const block = /** @type {DependenciesBlock} */ (queue.pop());
  1725. if (block.dependencies) {
  1726. currentBlock = block;
  1727. let i = 0;
  1728. for (const dep of block.dependencies) processDependency(dep, i++);
  1729. }
  1730. if (block.blocks) {
  1731. for (const b of block.blocks) queue.push(b);
  1732. }
  1733. } while (queue.length !== 0);
  1734. } catch (err) {
  1735. return callback(/** @type {WebpackError} */ (err));
  1736. }
  1737. if (--inProgressSorting === 0) onDependenciesSorted();
  1738. }
  1739. /**
  1740. * @private
  1741. * @param {Module} originModule original module
  1742. * @param {Dependency} dependency dependency
  1743. * @param {Module} module cached module
  1744. * @param {Callback} callback callback
  1745. */
  1746. _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) {
  1747. const moduleGraph = this.moduleGraph;
  1748. moduleGraph.setResolvedModule(originModule, dependency, module);
  1749. moduleGraph.setIssuerIfUnset(
  1750. module,
  1751. originModule !== undefined ? originModule : null
  1752. );
  1753. this._modules.set(module.identifier(), module);
  1754. this.modules.add(module);
  1755. if (this._backCompat) {
  1756. ModuleGraph.setModuleGraphForModule(module, this.moduleGraph);
  1757. }
  1758. this._handleModuleBuildAndDependencies(
  1759. originModule,
  1760. module,
  1761. true,
  1762. false,
  1763. callback
  1764. );
  1765. }
  1766. /**
  1767. * @private
  1768. * @param {Module} originModule original modules
  1769. * @param {Dependency} dependency dependency
  1770. * @param {Module} module cached module
  1771. */
  1772. _handleExistingModuleFromUnsafeCache(originModule, dependency, module) {
  1773. const moduleGraph = this.moduleGraph;
  1774. moduleGraph.setResolvedModule(originModule, dependency, module);
  1775. }
  1776. /**
  1777. * @typedef {object} HandleModuleCreationOptions
  1778. * @property {ModuleFactory} factory
  1779. * @property {Dependency[]} dependencies
  1780. * @property {Module | null} originModule
  1781. * @property {Partial<ModuleFactoryCreateDataContextInfo>=} contextInfo
  1782. * @property {string=} context
  1783. * @property {boolean=} recursive recurse into dependencies of the created module
  1784. * @property {boolean=} connectOrigin connect the resolved module with the origin module
  1785. * @property {boolean=} checkCycle check the cycle dependencies of the created module
  1786. */
  1787. /**
  1788. * @param {HandleModuleCreationOptions} options options object
  1789. * @param {ModuleCallback} callback callback
  1790. * @returns {void}
  1791. */
  1792. handleModuleCreation(
  1793. {
  1794. factory,
  1795. dependencies,
  1796. originModule,
  1797. contextInfo,
  1798. context,
  1799. recursive = true,
  1800. connectOrigin = recursive,
  1801. checkCycle = !recursive
  1802. },
  1803. callback
  1804. ) {
  1805. const moduleGraph = this.moduleGraph;
  1806. const currentProfile = this.profile ? new ModuleProfile() : undefined;
  1807. this.factorizeModule(
  1808. {
  1809. currentProfile,
  1810. factory,
  1811. dependencies,
  1812. factoryResult: true,
  1813. originModule,
  1814. contextInfo,
  1815. context
  1816. },
  1817. (err, factoryResult) => {
  1818. const applyFactoryResultDependencies = () => {
  1819. const { fileDependencies, contextDependencies, missingDependencies } =
  1820. /** @type {ModuleFactoryResult} */ (factoryResult);
  1821. if (fileDependencies) {
  1822. this.fileDependencies.addAll(fileDependencies);
  1823. }
  1824. if (contextDependencies) {
  1825. this.contextDependencies.addAll(contextDependencies);
  1826. }
  1827. if (missingDependencies) {
  1828. this.missingDependencies.addAll(missingDependencies);
  1829. }
  1830. };
  1831. if (err) {
  1832. if (factoryResult) applyFactoryResultDependencies();
  1833. if (dependencies.every(d => d.optional)) {
  1834. this.warnings.push(err);
  1835. return callback();
  1836. }
  1837. this.errors.push(err);
  1838. return callback(err);
  1839. }
  1840. const newModule =
  1841. /** @type {ModuleFactoryResult} */
  1842. (factoryResult).module;
  1843. if (!newModule) {
  1844. applyFactoryResultDependencies();
  1845. return callback();
  1846. }
  1847. if (currentProfile !== undefined) {
  1848. moduleGraph.setProfile(newModule, currentProfile);
  1849. }
  1850. this.addModule(newModule, (err, _module) => {
  1851. if (err) {
  1852. applyFactoryResultDependencies();
  1853. if (!err.module) {
  1854. err.module = _module;
  1855. }
  1856. this.errors.push(err);
  1857. return callback(err);
  1858. }
  1859. const module =
  1860. /** @type {ModuleWithRestoreFromUnsafeCache} */
  1861. (_module);
  1862. if (
  1863. this._unsafeCache &&
  1864. /** @type {ModuleFactoryResult} */
  1865. (factoryResult).cacheable !== false &&
  1866. module.restoreFromUnsafeCache &&
  1867. this._unsafeCachePredicate(module)
  1868. ) {
  1869. const unsafeCacheableModule =
  1870. /** @type {ModuleWithRestoreFromUnsafeCache} */
  1871. (module);
  1872. for (const dependency of dependencies) {
  1873. moduleGraph.setResolvedModule(
  1874. connectOrigin ? originModule : null,
  1875. dependency,
  1876. unsafeCacheableModule
  1877. );
  1878. unsafeCacheDependencies.set(dependency, unsafeCacheableModule);
  1879. }
  1880. if (!unsafeCacheData.has(unsafeCacheableModule)) {
  1881. unsafeCacheData.set(
  1882. unsafeCacheableModule,
  1883. unsafeCacheableModule.getUnsafeCacheData()
  1884. );
  1885. }
  1886. } else {
  1887. applyFactoryResultDependencies();
  1888. for (const dependency of dependencies) {
  1889. moduleGraph.setResolvedModule(
  1890. connectOrigin ? originModule : null,
  1891. dependency,
  1892. module
  1893. );
  1894. }
  1895. }
  1896. moduleGraph.setIssuerIfUnset(
  1897. module,
  1898. originModule !== undefined ? originModule : null
  1899. );
  1900. if (module !== newModule && currentProfile !== undefined) {
  1901. const otherProfile = moduleGraph.getProfile(module);
  1902. if (otherProfile !== undefined) {
  1903. currentProfile.mergeInto(otherProfile);
  1904. } else {
  1905. moduleGraph.setProfile(module, currentProfile);
  1906. }
  1907. }
  1908. this._handleModuleBuildAndDependencies(
  1909. originModule,
  1910. module,
  1911. recursive,
  1912. checkCycle,
  1913. callback
  1914. );
  1915. });
  1916. }
  1917. );
  1918. }
  1919. /**
  1920. * @private
  1921. * @param {Module | null} originModule original module
  1922. * @param {Module} module module
  1923. * @param {boolean} recursive true if make it recursive, otherwise false
  1924. * @param {boolean} checkCycle true if need to check cycle, otherwise false
  1925. * @param {ModuleCallback} callback callback
  1926. * @returns {void}
  1927. */
  1928. _handleModuleBuildAndDependencies(
  1929. originModule,
  1930. module,
  1931. recursive,
  1932. checkCycle,
  1933. callback
  1934. ) {
  1935. // Check for cycles when build is trigger inside another build
  1936. /** @type {Set<Module> | undefined} */
  1937. let creatingModuleDuringBuildSet;
  1938. if (
  1939. checkCycle &&
  1940. this.buildQueue.isProcessing(/** @type {Module} */ (originModule))
  1941. ) {
  1942. // Track build dependency
  1943. creatingModuleDuringBuildSet = this.creatingModuleDuringBuild.get(
  1944. /** @type {Module} */
  1945. (originModule)
  1946. );
  1947. if (creatingModuleDuringBuildSet === undefined) {
  1948. creatingModuleDuringBuildSet = new Set();
  1949. this.creatingModuleDuringBuild.set(
  1950. /** @type {Module} */
  1951. (originModule),
  1952. creatingModuleDuringBuildSet
  1953. );
  1954. }
  1955. creatingModuleDuringBuildSet.add(module);
  1956. // When building is blocked by another module
  1957. // search for a cycle, cancel the cycle by throwing
  1958. // an error (otherwise this would deadlock)
  1959. const blockReasons = this.creatingModuleDuringBuild.get(module);
  1960. if (blockReasons !== undefined) {
  1961. const set = new Set(blockReasons);
  1962. for (const item of set) {
  1963. const blockReasons = this.creatingModuleDuringBuild.get(item);
  1964. if (blockReasons !== undefined) {
  1965. for (const m of blockReasons) {
  1966. if (m === module) {
  1967. return callback(new BuildCycleError(module));
  1968. }
  1969. set.add(m);
  1970. }
  1971. }
  1972. }
  1973. }
  1974. }
  1975. this.buildModule(module, err => {
  1976. if (creatingModuleDuringBuildSet !== undefined) {
  1977. creatingModuleDuringBuildSet.delete(module);
  1978. }
  1979. if (err) {
  1980. if (!err.module) {
  1981. err.module = module;
  1982. }
  1983. this.errors.push(err);
  1984. return callback(err);
  1985. }
  1986. if (!recursive) {
  1987. this.processModuleDependenciesNonRecursive(module);
  1988. callback(null, module);
  1989. return;
  1990. }
  1991. // This avoids deadlocks for circular dependencies
  1992. if (this.processDependenciesQueue.isProcessing(module)) {
  1993. return callback(null, module);
  1994. }
  1995. this.processModuleDependencies(module, err => {
  1996. if (err) {
  1997. return callback(err);
  1998. }
  1999. callback(null, module);
  2000. });
  2001. });
  2002. }
  2003. /**
  2004. * @param {FactorizeModuleOptions} options options object
  2005. * @param {ModuleOrFactoryResultCallback} callback callback
  2006. * @returns {void}
  2007. */
  2008. _factorizeModule(
  2009. {
  2010. currentProfile,
  2011. factory,
  2012. dependencies,
  2013. originModule,
  2014. factoryResult,
  2015. contextInfo,
  2016. context
  2017. },
  2018. callback
  2019. ) {
  2020. if (currentProfile !== undefined) {
  2021. currentProfile.markFactoryStart();
  2022. }
  2023. factory.create(
  2024. {
  2025. contextInfo: {
  2026. issuer: originModule
  2027. ? /** @type {string} */ (originModule.nameForCondition())
  2028. : "",
  2029. issuerLayer: originModule ? originModule.layer : null,
  2030. compiler: /** @type {string} */ (this.compiler.name),
  2031. ...contextInfo
  2032. },
  2033. resolveOptions: originModule ? originModule.resolveOptions : undefined,
  2034. context:
  2035. context ||
  2036. (originModule
  2037. ? /** @type {string} */ (originModule.context)
  2038. : /** @type {string} */ (this.compiler.context)),
  2039. dependencies
  2040. },
  2041. (err, result) => {
  2042. if (result) {
  2043. // TODO webpack 6: remove
  2044. // For backward-compat
  2045. if (result.module === undefined && result instanceof Module) {
  2046. result = {
  2047. module: result
  2048. };
  2049. }
  2050. if (!factoryResult) {
  2051. const {
  2052. fileDependencies,
  2053. contextDependencies,
  2054. missingDependencies
  2055. } = result;
  2056. if (fileDependencies) {
  2057. this.fileDependencies.addAll(fileDependencies);
  2058. }
  2059. if (contextDependencies) {
  2060. this.contextDependencies.addAll(contextDependencies);
  2061. }
  2062. if (missingDependencies) {
  2063. this.missingDependencies.addAll(missingDependencies);
  2064. }
  2065. }
  2066. }
  2067. if (err) {
  2068. const notFoundError = new ModuleNotFoundError(
  2069. originModule,
  2070. err,
  2071. /** @type {DependencyLocation} */
  2072. (dependencies.map(d => d.loc).find(Boolean))
  2073. );
  2074. return callback(notFoundError, factoryResult ? result : undefined);
  2075. }
  2076. if (!result) {
  2077. return callback();
  2078. }
  2079. if (currentProfile !== undefined) {
  2080. currentProfile.markFactoryEnd();
  2081. }
  2082. callback(null, factoryResult ? result : result.module);
  2083. }
  2084. );
  2085. }
  2086. /**
  2087. * @param {string} context context string path
  2088. * @param {Dependency} dependency dependency used to create Module chain
  2089. * @param {ModuleCallback} callback callback for when module chain is complete
  2090. * @returns {void} will throw if dependency instance is not a valid Dependency
  2091. */
  2092. addModuleChain(context, dependency, callback) {
  2093. return this.addModuleTree({ context, dependency }, callback);
  2094. }
  2095. /**
  2096. * @param {object} options options
  2097. * @param {string} options.context context string path
  2098. * @param {Dependency} options.dependency dependency used to create Module chain
  2099. * @param {Partial<ModuleFactoryCreateDataContextInfo>=} options.contextInfo additional context info for the root module
  2100. * @param {ModuleCallback} callback callback for when module chain is complete
  2101. * @returns {void} will throw if dependency instance is not a valid Dependency
  2102. */
  2103. addModuleTree({ context, dependency, contextInfo }, callback) {
  2104. if (
  2105. typeof dependency !== "object" ||
  2106. dependency === null ||
  2107. !dependency.constructor
  2108. ) {
  2109. return callback(
  2110. new WebpackError("Parameter 'dependency' must be a Dependency")
  2111. );
  2112. }
  2113. const Dep = /** @type {DepConstructor} */ (dependency.constructor);
  2114. const moduleFactory = this.dependencyFactories.get(Dep);
  2115. if (!moduleFactory) {
  2116. return callback(
  2117. new WebpackError(
  2118. `No dependency factory available for this dependency type: ${dependency.constructor.name}`
  2119. )
  2120. );
  2121. }
  2122. this.handleModuleCreation(
  2123. {
  2124. factory: moduleFactory,
  2125. dependencies: [dependency],
  2126. originModule: null,
  2127. contextInfo,
  2128. context
  2129. },
  2130. (err, result) => {
  2131. if (err && this.bail) {
  2132. callback(err);
  2133. this.buildQueue.stop();
  2134. this.rebuildQueue.stop();
  2135. this.processDependenciesQueue.stop();
  2136. this.factorizeQueue.stop();
  2137. } else if (!err && result) {
  2138. callback(null, result);
  2139. } else {
  2140. callback();
  2141. }
  2142. }
  2143. );
  2144. }
  2145. /**
  2146. * @param {string} context context path for entry
  2147. * @param {Dependency} entry entry dependency that should be followed
  2148. * @param {string | EntryOptions} optionsOrName options or deprecated name of entry
  2149. * @param {ModuleCallback} callback callback function
  2150. * @returns {void} returns
  2151. */
  2152. addEntry(context, entry, optionsOrName, callback) {
  2153. // TODO webpack 6 remove
  2154. const options =
  2155. typeof optionsOrName === "object"
  2156. ? optionsOrName
  2157. : { name: optionsOrName };
  2158. this._addEntryItem(context, entry, "dependencies", options, callback);
  2159. }
  2160. /**
  2161. * @param {string} context context path for entry
  2162. * @param {Dependency} dependency dependency that should be followed
  2163. * @param {EntryOptions} options options
  2164. * @param {ModuleCallback} callback callback function
  2165. * @returns {void} returns
  2166. */
  2167. addInclude(context, dependency, options, callback) {
  2168. this._addEntryItem(
  2169. context,
  2170. dependency,
  2171. "includeDependencies",
  2172. options,
  2173. callback
  2174. );
  2175. }
  2176. /**
  2177. * @param {string} context context path for entry
  2178. * @param {Dependency} entry entry dependency that should be followed
  2179. * @param {"dependencies" | "includeDependencies"} target type of entry
  2180. * @param {EntryOptions} options options
  2181. * @param {ModuleCallback} callback callback function
  2182. * @returns {void} returns
  2183. */
  2184. _addEntryItem(context, entry, target, options, callback) {
  2185. const { name } = options;
  2186. /** @type {EntryData | undefined} */
  2187. let entryData =
  2188. name !== undefined ? this.entries.get(name) : this.globalEntry;
  2189. if (entryData === undefined) {
  2190. entryData = {
  2191. dependencies: [],
  2192. includeDependencies: [],
  2193. options: {
  2194. name: undefined,
  2195. ...options
  2196. }
  2197. };
  2198. entryData[target].push(entry);
  2199. this.entries.set(
  2200. /** @type {NonNullable<EntryOptions["name"]>} */
  2201. (name),
  2202. entryData
  2203. );
  2204. } else {
  2205. entryData[target].push(entry);
  2206. for (const _key of Object.keys(options)) {
  2207. const key = /** @type {keyof EntryOptions} */ (_key);
  2208. if (options[key] === undefined) continue;
  2209. if (entryData.options[key] === options[key]) continue;
  2210. if (
  2211. Array.isArray(entryData.options[key]) &&
  2212. Array.isArray(options[key]) &&
  2213. arrayEquals(entryData.options[key], options[key])
  2214. ) {
  2215. continue;
  2216. }
  2217. if (entryData.options[key] === undefined) {
  2218. /** @type {TODO} */
  2219. (entryData.options)[key] =
  2220. /** @type {NonNullable<EntryOptions[keyof EntryOptions]>} */
  2221. (options[key]);
  2222. } else {
  2223. return callback(
  2224. new WebpackError(
  2225. `Conflicting entry option ${key} = ${entryData.options[key]} vs ${options[key]}`
  2226. )
  2227. );
  2228. }
  2229. }
  2230. }
  2231. this.hooks.addEntry.call(entry, options);
  2232. this.addModuleTree(
  2233. {
  2234. context,
  2235. dependency: entry,
  2236. contextInfo: entryData.options.layer
  2237. ? { issuerLayer: entryData.options.layer }
  2238. : undefined
  2239. },
  2240. (err, module) => {
  2241. if (err) {
  2242. this.hooks.failedEntry.call(entry, options, err);
  2243. return callback(err);
  2244. }
  2245. this.hooks.succeedEntry.call(
  2246. entry,
  2247. options,
  2248. /** @type {Module} */
  2249. (module)
  2250. );
  2251. return callback(null, module);
  2252. }
  2253. );
  2254. }
  2255. /**
  2256. * @param {Module} module module to be rebuilt
  2257. * @param {ModuleCallback} callback callback when module finishes rebuilding
  2258. * @returns {void}
  2259. */
  2260. rebuildModule(module, callback) {
  2261. this.rebuildQueue.add(module, callback);
  2262. }
  2263. /**
  2264. * @param {Module} module module to be rebuilt
  2265. * @param {ModuleCallback} callback callback when module finishes rebuilding
  2266. * @returns {void}
  2267. */
  2268. _rebuildModule(module, callback) {
  2269. this.hooks.rebuildModule.call(module);
  2270. const oldDependencies = [...module.dependencies];
  2271. const oldBlocks = [...module.blocks];
  2272. module.invalidateBuild();
  2273. this.buildQueue.invalidate(module);
  2274. this.buildModule(module, err => {
  2275. if (err) {
  2276. return this.hooks.finishRebuildingModule.callAsync(module, err2 => {
  2277. if (err2) {
  2278. callback(
  2279. makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule")
  2280. );
  2281. return;
  2282. }
  2283. callback(err);
  2284. });
  2285. }
  2286. this.processDependenciesQueue.invalidate(module);
  2287. this.moduleGraph.unfreeze();
  2288. this.processModuleDependencies(module, err => {
  2289. if (err) return callback(err);
  2290. this.removeReasonsOfDependencyBlock(module, {
  2291. dependencies: oldDependencies,
  2292. blocks: oldBlocks
  2293. });
  2294. this.hooks.finishRebuildingModule.callAsync(module, err2 => {
  2295. if (err2) {
  2296. callback(
  2297. makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule")
  2298. );
  2299. return;
  2300. }
  2301. callback(null, module);
  2302. });
  2303. });
  2304. });
  2305. }
  2306. /**
  2307. * @private
  2308. * @param {Set<Module>} modules modules
  2309. */
  2310. _computeAffectedModules(modules) {
  2311. const moduleMemCacheCache = this.compiler.moduleMemCaches;
  2312. if (!moduleMemCacheCache) return;
  2313. if (!this.moduleMemCaches) {
  2314. this.moduleMemCaches = new Map();
  2315. this.moduleGraph.setModuleMemCaches(this.moduleMemCaches);
  2316. }
  2317. const { moduleGraph, moduleMemCaches } = this;
  2318. const affectedModules = new Set();
  2319. const infectedModules = new Set();
  2320. let statNew = 0;
  2321. let statChanged = 0;
  2322. let statUnchanged = 0;
  2323. let statReferencesChanged = 0;
  2324. let statWithoutBuild = 0;
  2325. /**
  2326. * @param {Module} module module
  2327. * @returns {WeakReferences | undefined} references
  2328. */
  2329. const computeReferences = module => {
  2330. /** @type {WeakReferences | undefined} */
  2331. let references;
  2332. for (const connection of moduleGraph.getOutgoingConnections(module)) {
  2333. const d = connection.dependency;
  2334. const m = connection.module;
  2335. if (!d || !m || unsafeCacheDependencies.has(d)) continue;
  2336. if (references === undefined) references = new WeakMap();
  2337. references.set(d, m);
  2338. }
  2339. return references;
  2340. };
  2341. /**
  2342. * @param {Module} module the module
  2343. * @param {WeakReferences | undefined} references references
  2344. * @returns {boolean} true, when the references differ
  2345. */
  2346. const compareReferences = (module, references) => {
  2347. if (references === undefined) return true;
  2348. for (const connection of moduleGraph.getOutgoingConnections(module)) {
  2349. const d = connection.dependency;
  2350. if (!d) continue;
  2351. const entry = references.get(d);
  2352. if (entry === undefined) continue;
  2353. if (entry !== connection.module) return false;
  2354. }
  2355. return true;
  2356. };
  2357. const modulesWithoutCache = new Set(modules);
  2358. for (const [module, cachedMemCache] of moduleMemCacheCache) {
  2359. if (modulesWithoutCache.has(module)) {
  2360. const buildInfo = module.buildInfo;
  2361. if (buildInfo) {
  2362. if (cachedMemCache.buildInfo !== buildInfo) {
  2363. // use a new one
  2364. /** @type {MemCache} */
  2365. const memCache = new WeakTupleMap();
  2366. moduleMemCaches.set(module, memCache);
  2367. affectedModules.add(module);
  2368. cachedMemCache.buildInfo = buildInfo;
  2369. cachedMemCache.references = computeReferences(module);
  2370. cachedMemCache.memCache = memCache;
  2371. statChanged++;
  2372. } else if (!compareReferences(module, cachedMemCache.references)) {
  2373. // use a new one
  2374. /** @type {MemCache} */
  2375. const memCache = new WeakTupleMap();
  2376. moduleMemCaches.set(module, memCache);
  2377. affectedModules.add(module);
  2378. cachedMemCache.references = computeReferences(module);
  2379. cachedMemCache.memCache = memCache;
  2380. statReferencesChanged++;
  2381. } else {
  2382. // keep the old mem cache
  2383. moduleMemCaches.set(module, cachedMemCache.memCache);
  2384. statUnchanged++;
  2385. }
  2386. } else {
  2387. infectedModules.add(module);
  2388. moduleMemCacheCache.delete(module);
  2389. statWithoutBuild++;
  2390. }
  2391. modulesWithoutCache.delete(module);
  2392. } else {
  2393. moduleMemCacheCache.delete(module);
  2394. }
  2395. }
  2396. for (const module of modulesWithoutCache) {
  2397. const buildInfo = module.buildInfo;
  2398. if (buildInfo) {
  2399. // create a new entry
  2400. const memCache = new WeakTupleMap();
  2401. moduleMemCacheCache.set(module, {
  2402. buildInfo,
  2403. references: computeReferences(module),
  2404. memCache
  2405. });
  2406. moduleMemCaches.set(module, memCache);
  2407. affectedModules.add(module);
  2408. statNew++;
  2409. } else {
  2410. infectedModules.add(module);
  2411. statWithoutBuild++;
  2412. }
  2413. }
  2414. /**
  2415. * @param {readonly ModuleGraphConnection[]} connections connections
  2416. * @returns {symbol|boolean} result
  2417. */
  2418. const reduceAffectType = connections => {
  2419. let affected = false;
  2420. for (const { dependency } of connections) {
  2421. if (!dependency) continue;
  2422. const type = dependency.couldAffectReferencingModule();
  2423. if (type === Dependency.TRANSITIVE) return Dependency.TRANSITIVE;
  2424. if (type === false) continue;
  2425. affected = true;
  2426. }
  2427. return affected;
  2428. };
  2429. const directOnlyInfectedModules = new Set();
  2430. for (const module of infectedModules) {
  2431. for (const [
  2432. referencingModule,
  2433. connections
  2434. ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) {
  2435. if (!referencingModule) continue;
  2436. if (infectedModules.has(referencingModule)) continue;
  2437. const type = reduceAffectType(connections);
  2438. if (!type) continue;
  2439. if (type === true) {
  2440. directOnlyInfectedModules.add(referencingModule);
  2441. } else {
  2442. infectedModules.add(referencingModule);
  2443. }
  2444. }
  2445. }
  2446. for (const module of directOnlyInfectedModules) infectedModules.add(module);
  2447. const directOnlyAffectModules = new Set();
  2448. for (const module of affectedModules) {
  2449. for (const [
  2450. referencingModule,
  2451. connections
  2452. ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) {
  2453. if (!referencingModule) continue;
  2454. if (infectedModules.has(referencingModule)) continue;
  2455. if (affectedModules.has(referencingModule)) continue;
  2456. const type = reduceAffectType(connections);
  2457. if (!type) continue;
  2458. if (type === true) {
  2459. directOnlyAffectModules.add(referencingModule);
  2460. } else {
  2461. affectedModules.add(referencingModule);
  2462. }
  2463. /** @type {MemCache} */
  2464. const memCache = new WeakTupleMap();
  2465. const cache =
  2466. /** @type {ModuleMemCachesItem} */
  2467. (moduleMemCacheCache.get(referencingModule));
  2468. cache.memCache = memCache;
  2469. moduleMemCaches.set(referencingModule, memCache);
  2470. }
  2471. }
  2472. for (const module of directOnlyAffectModules) affectedModules.add(module);
  2473. this.logger.log(
  2474. `${Math.round(
  2475. (100 * (affectedModules.size + infectedModules.size)) /
  2476. this.modules.size
  2477. )}% (${affectedModules.size} affected + ${
  2478. infectedModules.size
  2479. } infected of ${
  2480. this.modules.size
  2481. }) modules flagged as affected (${statNew} new modules, ${statChanged} changed, ${statReferencesChanged} references changed, ${statUnchanged} unchanged, ${statWithoutBuild} were not built)`
  2482. );
  2483. }
  2484. _computeAffectedModulesWithChunkGraph() {
  2485. const { moduleMemCaches } = this;
  2486. if (!moduleMemCaches) return;
  2487. const moduleMemCaches2 = (this.moduleMemCaches2 = new Map());
  2488. const { moduleGraph, chunkGraph } = this;
  2489. const key = "memCache2";
  2490. let statUnchanged = 0;
  2491. let statChanged = 0;
  2492. let statNew = 0;
  2493. /**
  2494. * @param {Module} module module
  2495. * @returns {References} references
  2496. */
  2497. const computeReferences = module => {
  2498. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
  2499. /** @type {Map<Module, string | number | undefined> | undefined} */
  2500. let modules;
  2501. /** @type {(string | number | null)[] | undefined} */
  2502. let blocks;
  2503. const outgoing = moduleGraph.getOutgoingConnectionsByModule(module);
  2504. if (outgoing !== undefined) {
  2505. for (const m of outgoing.keys()) {
  2506. if (!m) continue;
  2507. if (modules === undefined) modules = new Map();
  2508. modules.set(m, /** @type {ModuleId} */ (chunkGraph.getModuleId(m)));
  2509. }
  2510. }
  2511. if (module.blocks.length > 0) {
  2512. blocks = [];
  2513. const queue = [...module.blocks];
  2514. for (const block of queue) {
  2515. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  2516. if (chunkGroup) {
  2517. for (const chunk of chunkGroup.chunks) {
  2518. blocks.push(chunk.id);
  2519. }
  2520. } else {
  2521. blocks.push(null);
  2522. }
  2523. // eslint-disable-next-line prefer-spread
  2524. queue.push.apply(queue, block.blocks);
  2525. }
  2526. }
  2527. return { id, modules, blocks };
  2528. };
  2529. /**
  2530. * @param {Module} module module
  2531. * @param {object} references references
  2532. * @param {string | number} references.id id
  2533. * @param {Map<Module, string | number | undefined>=} references.modules modules
  2534. * @param {(string | number | null)[]=} references.blocks blocks
  2535. * @returns {boolean} ok?
  2536. */
  2537. const compareReferences = (module, { id, modules, blocks }) => {
  2538. if (id !== chunkGraph.getModuleId(module)) return false;
  2539. if (modules !== undefined) {
  2540. for (const [module, id] of modules) {
  2541. if (chunkGraph.getModuleId(module) !== id) return false;
  2542. }
  2543. }
  2544. if (blocks !== undefined) {
  2545. const queue = [...module.blocks];
  2546. let i = 0;
  2547. for (const block of queue) {
  2548. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  2549. if (chunkGroup) {
  2550. for (const chunk of chunkGroup.chunks) {
  2551. if (i >= blocks.length || blocks[i++] !== chunk.id) return false;
  2552. }
  2553. } else if (i >= blocks.length || blocks[i++] !== null) {
  2554. return false;
  2555. }
  2556. // eslint-disable-next-line prefer-spread
  2557. queue.push.apply(queue, block.blocks);
  2558. }
  2559. if (i !== blocks.length) return false;
  2560. }
  2561. return true;
  2562. };
  2563. for (const [module, memCache] of moduleMemCaches) {
  2564. /** @type {{ references: References, memCache: MemCache } | undefined} */
  2565. const cache = memCache.get(key);
  2566. if (cache === undefined) {
  2567. /** @type {WeakTupleMap<Module[], RuntimeRequirements | null> | undefined} */
  2568. const memCache2 = new WeakTupleMap();
  2569. memCache.set(key, {
  2570. references: computeReferences(module),
  2571. memCache: memCache2
  2572. });
  2573. moduleMemCaches2.set(module, memCache2);
  2574. statNew++;
  2575. } else if (!compareReferences(module, cache.references)) {
  2576. /** @type {WeakTupleMap<Module[], RuntimeRequirements | null> | undefined} */
  2577. const memCache = new WeakTupleMap();
  2578. cache.references = computeReferences(module);
  2579. cache.memCache = memCache;
  2580. moduleMemCaches2.set(module, memCache);
  2581. statChanged++;
  2582. } else {
  2583. moduleMemCaches2.set(module, cache.memCache);
  2584. statUnchanged++;
  2585. }
  2586. }
  2587. this.logger.log(
  2588. `${Math.round(
  2589. (100 * statChanged) / (statNew + statChanged + statUnchanged)
  2590. )}% modules flagged as affected by chunk graph (${statNew} new modules, ${statChanged} changed, ${statUnchanged} unchanged)`
  2591. );
  2592. }
  2593. /**
  2594. * @param {Callback} callback callback
  2595. */
  2596. finish(callback) {
  2597. this.factorizeQueue.clear();
  2598. if (this.profile) {
  2599. this.logger.time("finish module profiles");
  2600. const ParallelismFactorCalculator = require("./util/ParallelismFactorCalculator");
  2601. const p = new ParallelismFactorCalculator();
  2602. const moduleGraph = this.moduleGraph;
  2603. /** @type {Map<Module, ModuleProfile>} */
  2604. const modulesWithProfiles = new Map();
  2605. for (const module of this.modules) {
  2606. const profile = moduleGraph.getProfile(module);
  2607. if (!profile) continue;
  2608. modulesWithProfiles.set(module, profile);
  2609. p.range(
  2610. profile.buildingStartTime,
  2611. profile.buildingEndTime,
  2612. f => (profile.buildingParallelismFactor = f)
  2613. );
  2614. p.range(
  2615. profile.factoryStartTime,
  2616. profile.factoryEndTime,
  2617. f => (profile.factoryParallelismFactor = f)
  2618. );
  2619. p.range(
  2620. profile.integrationStartTime,
  2621. profile.integrationEndTime,
  2622. f => (profile.integrationParallelismFactor = f)
  2623. );
  2624. p.range(
  2625. profile.storingStartTime,
  2626. profile.storingEndTime,
  2627. f => (profile.storingParallelismFactor = f)
  2628. );
  2629. p.range(
  2630. profile.restoringStartTime,
  2631. profile.restoringEndTime,
  2632. f => (profile.restoringParallelismFactor = f)
  2633. );
  2634. if (profile.additionalFactoryTimes) {
  2635. for (const { start, end } of profile.additionalFactoryTimes) {
  2636. const influence = (end - start) / profile.additionalFactories;
  2637. p.range(
  2638. start,
  2639. end,
  2640. f =>
  2641. (profile.additionalFactoriesParallelismFactor += f * influence)
  2642. );
  2643. }
  2644. }
  2645. }
  2646. p.calculate();
  2647. const logger = this.getLogger("webpack.Compilation.ModuleProfile");
  2648. // Avoid coverage problems due indirect changes
  2649. /**
  2650. * @param {number} value value
  2651. * @param {string} msg message
  2652. */
  2653. /* istanbul ignore next */
  2654. const logByValue = (value, msg) => {
  2655. if (value > 1000) {
  2656. logger.error(msg);
  2657. } else if (value > 500) {
  2658. logger.warn(msg);
  2659. } else if (value > 200) {
  2660. logger.info(msg);
  2661. } else if (value > 30) {
  2662. logger.log(msg);
  2663. } else {
  2664. logger.debug(msg);
  2665. }
  2666. };
  2667. /**
  2668. * @param {string} category a category
  2669. * @param {(profile: ModuleProfile) => number} getDuration get duration callback
  2670. * @param {(profile: ModuleProfile) => number} getParallelism get parallelism callback
  2671. */
  2672. const logNormalSummary = (category, getDuration, getParallelism) => {
  2673. let sum = 0;
  2674. let max = 0;
  2675. for (const [module, profile] of modulesWithProfiles) {
  2676. const p = getParallelism(profile);
  2677. const d = getDuration(profile);
  2678. if (d === 0 || p === 0) continue;
  2679. const t = d / p;
  2680. sum += t;
  2681. if (t <= 10) continue;
  2682. logByValue(
  2683. t,
  2684. ` | ${Math.round(t)} ms${
  2685. p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : ""
  2686. } ${category} > ${module.readableIdentifier(this.requestShortener)}`
  2687. );
  2688. max = Math.max(max, t);
  2689. }
  2690. if (sum <= 10) return;
  2691. logByValue(
  2692. Math.max(sum / 10, max),
  2693. `${Math.round(sum)} ms ${category}`
  2694. );
  2695. };
  2696. /**
  2697. * @param {string} category a category
  2698. * @param {(profile: ModuleProfile) => number} getDuration get duration callback
  2699. * @param {(profile: ModuleProfile) => number} getParallelism get parallelism callback
  2700. */
  2701. const logByLoadersSummary = (category, getDuration, getParallelism) => {
  2702. const map = new Map();
  2703. for (const [module, profile] of modulesWithProfiles) {
  2704. const list = getOrInsert(
  2705. map,
  2706. `${module.type}!${module.identifier().replace(/(!|^)[^!]*$/, "")}`,
  2707. () => []
  2708. );
  2709. list.push({ module, profile });
  2710. }
  2711. let sum = 0;
  2712. let max = 0;
  2713. for (const [key, modules] of map) {
  2714. let innerSum = 0;
  2715. let innerMax = 0;
  2716. for (const { module, profile } of modules) {
  2717. const p = getParallelism(profile);
  2718. const d = getDuration(profile);
  2719. if (d === 0 || p === 0) continue;
  2720. const t = d / p;
  2721. innerSum += t;
  2722. if (t <= 10) continue;
  2723. logByValue(
  2724. t,
  2725. ` | | ${Math.round(t)} ms${
  2726. p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : ""
  2727. } ${category} > ${module.readableIdentifier(
  2728. this.requestShortener
  2729. )}`
  2730. );
  2731. innerMax = Math.max(innerMax, t);
  2732. }
  2733. sum += innerSum;
  2734. if (innerSum <= 10) continue;
  2735. const idx = key.indexOf("!");
  2736. const loaders = key.slice(idx + 1);
  2737. const moduleType = key.slice(0, idx);
  2738. const t = Math.max(innerSum / 10, innerMax);
  2739. logByValue(
  2740. t,
  2741. ` | ${Math.round(innerSum)} ms ${category} > ${
  2742. loaders
  2743. ? `${
  2744. modules.length
  2745. } x ${moduleType} with ${this.requestShortener.shorten(
  2746. loaders
  2747. )}`
  2748. : `${modules.length} x ${moduleType}`
  2749. }`
  2750. );
  2751. max = Math.max(max, t);
  2752. }
  2753. if (sum <= 10) return;
  2754. logByValue(
  2755. Math.max(sum / 10, max),
  2756. `${Math.round(sum)} ms ${category}`
  2757. );
  2758. };
  2759. logNormalSummary(
  2760. "resolve to new modules",
  2761. p => p.factory,
  2762. p => p.factoryParallelismFactor
  2763. );
  2764. logNormalSummary(
  2765. "resolve to existing modules",
  2766. p => p.additionalFactories,
  2767. p => p.additionalFactoriesParallelismFactor
  2768. );
  2769. logNormalSummary(
  2770. "integrate modules",
  2771. p => p.restoring,
  2772. p => p.restoringParallelismFactor
  2773. );
  2774. logByLoadersSummary(
  2775. "build modules",
  2776. p => p.building,
  2777. p => p.buildingParallelismFactor
  2778. );
  2779. logNormalSummary(
  2780. "store modules",
  2781. p => p.storing,
  2782. p => p.storingParallelismFactor
  2783. );
  2784. logNormalSummary(
  2785. "restore modules",
  2786. p => p.restoring,
  2787. p => p.restoringParallelismFactor
  2788. );
  2789. this.logger.timeEnd("finish module profiles");
  2790. }
  2791. this.logger.time("compute affected modules");
  2792. this._computeAffectedModules(this.modules);
  2793. this.logger.timeEnd("compute affected modules");
  2794. this.logger.time("finish modules");
  2795. const { modules, moduleMemCaches } = this;
  2796. this.hooks.finishModules.callAsync(modules, err => {
  2797. this.logger.timeEnd("finish modules");
  2798. if (err) return callback(/** @type {WebpackError} */ (err));
  2799. // extract warnings and errors from modules
  2800. this.moduleGraph.freeze("dependency errors");
  2801. // TODO keep a cacheToken (= {}) for each module in the graph
  2802. // create a new one per compilation and flag all updated files
  2803. // and parents with it
  2804. this.logger.time("report dependency errors and warnings");
  2805. for (const module of modules) {
  2806. // TODO only run for modules with changed cacheToken
  2807. // global WeakMap<CacheToken, WeakSet<Module>> to keep modules without errors/warnings
  2808. const memCache = moduleMemCaches && moduleMemCaches.get(module);
  2809. if (memCache && memCache.get("noWarningsOrErrors")) continue;
  2810. let hasProblems = this.reportDependencyErrorsAndWarnings(module, [
  2811. module
  2812. ]);
  2813. const errors = module.getErrors();
  2814. if (errors !== undefined) {
  2815. for (const error of errors) {
  2816. if (!error.module) {
  2817. error.module = module;
  2818. }
  2819. this.errors.push(error);
  2820. hasProblems = true;
  2821. }
  2822. }
  2823. const warnings = module.getWarnings();
  2824. if (warnings !== undefined) {
  2825. for (const warning of warnings) {
  2826. if (!warning.module) {
  2827. warning.module = module;
  2828. }
  2829. this.warnings.push(warning);
  2830. hasProblems = true;
  2831. }
  2832. }
  2833. if (!hasProblems && memCache) memCache.set("noWarningsOrErrors", true);
  2834. }
  2835. this.moduleGraph.unfreeze();
  2836. this.logger.timeEnd("report dependency errors and warnings");
  2837. callback();
  2838. });
  2839. }
  2840. unseal() {
  2841. this.hooks.unseal.call();
  2842. this.chunks.clear();
  2843. this.chunkGroups.length = 0;
  2844. this.namedChunks.clear();
  2845. this.namedChunkGroups.clear();
  2846. this.entrypoints.clear();
  2847. this.additionalChunkAssets.length = 0;
  2848. this.assets = {};
  2849. this.assetsInfo.clear();
  2850. this.moduleGraph.removeAllModuleAttributes();
  2851. this.moduleGraph.unfreeze();
  2852. this.moduleMemCaches2 = undefined;
  2853. }
  2854. /**
  2855. * @param {Callback} callback signals when the call finishes
  2856. * @returns {void}
  2857. */
  2858. seal(callback) {
  2859. /**
  2860. * @param {WebpackError=} err err
  2861. * @returns {void}
  2862. */
  2863. const finalCallback = err => {
  2864. this.factorizeQueue.clear();
  2865. this.buildQueue.clear();
  2866. this.rebuildQueue.clear();
  2867. this.processDependenciesQueue.clear();
  2868. this.addModuleQueue.clear();
  2869. return callback(err);
  2870. };
  2871. const chunkGraph = new ChunkGraph(
  2872. this.moduleGraph,
  2873. this.outputOptions.hashFunction
  2874. );
  2875. this.chunkGraph = chunkGraph;
  2876. if (this._backCompat) {
  2877. for (const module of this.modules) {
  2878. ChunkGraph.setChunkGraphForModule(module, chunkGraph);
  2879. }
  2880. }
  2881. this.hooks.seal.call();
  2882. this.logger.time("optimize dependencies");
  2883. while (this.hooks.optimizeDependencies.call(this.modules)) {
  2884. /* empty */
  2885. }
  2886. this.hooks.afterOptimizeDependencies.call(this.modules);
  2887. this.logger.timeEnd("optimize dependencies");
  2888. this.logger.time("create chunks");
  2889. this.hooks.beforeChunks.call();
  2890. this.moduleGraph.freeze("seal");
  2891. /** @type {Map<Entrypoint, Module[]>} */
  2892. const chunkGraphInit = new Map();
  2893. for (const [name, { dependencies, includeDependencies, options }] of this
  2894. .entries) {
  2895. const chunk = this.addChunk(name);
  2896. if (options.filename) {
  2897. chunk.filenameTemplate = options.filename;
  2898. }
  2899. const entrypoint = new Entrypoint(options);
  2900. if (!options.dependOn && !options.runtime) {
  2901. entrypoint.setRuntimeChunk(chunk);
  2902. }
  2903. entrypoint.setEntrypointChunk(chunk);
  2904. this.namedChunkGroups.set(name, entrypoint);
  2905. this.entrypoints.set(name, entrypoint);
  2906. this.chunkGroups.push(entrypoint);
  2907. connectChunkGroupAndChunk(entrypoint, chunk);
  2908. const entryModules = new Set();
  2909. for (const dep of [...this.globalEntry.dependencies, ...dependencies]) {
  2910. entrypoint.addOrigin(
  2911. null,
  2912. { name },
  2913. /** @type {Dependency & { request: string }} */
  2914. (dep).request
  2915. );
  2916. const module = this.moduleGraph.getModule(dep);
  2917. if (module) {
  2918. chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint);
  2919. entryModules.add(module);
  2920. const modulesList = chunkGraphInit.get(entrypoint);
  2921. if (modulesList === undefined) {
  2922. chunkGraphInit.set(entrypoint, [module]);
  2923. } else {
  2924. modulesList.push(module);
  2925. }
  2926. }
  2927. }
  2928. this.assignDepths(entryModules);
  2929. /**
  2930. * @param {Dependency[]} deps deps
  2931. * @returns {Module[]} sorted deps
  2932. */
  2933. const mapAndSort = deps =>
  2934. /** @type {Module[]} */
  2935. (deps.map(dep => this.moduleGraph.getModule(dep)).filter(Boolean)).sort(
  2936. compareModulesByIdentifier
  2937. );
  2938. const includedModules = [
  2939. ...mapAndSort(this.globalEntry.includeDependencies),
  2940. ...mapAndSort(includeDependencies)
  2941. ];
  2942. let modulesList = chunkGraphInit.get(entrypoint);
  2943. if (modulesList === undefined) {
  2944. chunkGraphInit.set(entrypoint, (modulesList = []));
  2945. }
  2946. for (const module of includedModules) {
  2947. this.assignDepth(module);
  2948. modulesList.push(module);
  2949. }
  2950. }
  2951. const runtimeChunks = new Set();
  2952. outer: for (const [
  2953. name,
  2954. {
  2955. options: { dependOn, runtime }
  2956. }
  2957. ] of this.entries) {
  2958. if (dependOn && runtime) {
  2959. const err =
  2960. new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid.
  2961. Entrypoints that depend on other entrypoints do not have their own runtime.
  2962. They will use the runtime(s) from referenced entrypoints instead.
  2963. Remove the 'runtime' option from the entrypoint.`);
  2964. const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name));
  2965. err.chunk = entry.getEntrypointChunk();
  2966. this.errors.push(err);
  2967. }
  2968. if (dependOn) {
  2969. const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name));
  2970. const referencedChunks = entry
  2971. .getEntrypointChunk()
  2972. .getAllReferencedChunks();
  2973. const dependOnEntries = [];
  2974. for (const dep of dependOn) {
  2975. const dependency = this.entrypoints.get(dep);
  2976. if (!dependency) {
  2977. throw new Error(
  2978. `Entry ${name} depends on ${dep}, but this entry was not found`
  2979. );
  2980. }
  2981. if (referencedChunks.has(dependency.getEntrypointChunk())) {
  2982. const err = new WebpackError(
  2983. `Entrypoints '${name}' and '${dep}' use 'dependOn' to depend on each other in a circular way.`
  2984. );
  2985. const entryChunk = entry.getEntrypointChunk();
  2986. err.chunk = entryChunk;
  2987. this.errors.push(err);
  2988. entry.setRuntimeChunk(entryChunk);
  2989. continue outer;
  2990. }
  2991. dependOnEntries.push(dependency);
  2992. }
  2993. for (const dependency of dependOnEntries) {
  2994. connectChunkGroupParentAndChild(dependency, entry);
  2995. }
  2996. } else if (runtime) {
  2997. const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name));
  2998. let chunk = this.namedChunks.get(runtime);
  2999. if (chunk) {
  3000. if (!runtimeChunks.has(chunk)) {
  3001. const err =
  3002. new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'.
  3003. It's not valid to use other entrypoints as runtime chunk.
  3004. Did you mean to use 'dependOn: ${JSON.stringify(
  3005. runtime
  3006. )}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used.
  3007. Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`);
  3008. const entryChunk =
  3009. /** @type {Chunk} */
  3010. (entry.getEntrypointChunk());
  3011. err.chunk = entryChunk;
  3012. this.errors.push(err);
  3013. entry.setRuntimeChunk(entryChunk);
  3014. continue;
  3015. }
  3016. } else {
  3017. chunk = this.addChunk(runtime);
  3018. chunk.preventIntegration = true;
  3019. runtimeChunks.add(chunk);
  3020. }
  3021. entry.unshiftChunk(chunk);
  3022. chunk.addGroup(entry);
  3023. entry.setRuntimeChunk(chunk);
  3024. }
  3025. }
  3026. buildChunkGraph(this, chunkGraphInit);
  3027. this.hooks.afterChunks.call(this.chunks);
  3028. this.logger.timeEnd("create chunks");
  3029. this.logger.time("optimize");
  3030. this.hooks.optimize.call();
  3031. while (this.hooks.optimizeModules.call(this.modules)) {
  3032. /* empty */
  3033. }
  3034. this.hooks.afterOptimizeModules.call(this.modules);
  3035. while (this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups)) {
  3036. /* empty */
  3037. }
  3038. this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups);
  3039. this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => {
  3040. if (err) {
  3041. return finalCallback(
  3042. makeWebpackError(err, "Compilation.hooks.optimizeTree")
  3043. );
  3044. }
  3045. this.hooks.afterOptimizeTree.call(this.chunks, this.modules);
  3046. this.hooks.optimizeChunkModules.callAsync(
  3047. this.chunks,
  3048. this.modules,
  3049. err => {
  3050. if (err) {
  3051. return finalCallback(
  3052. makeWebpackError(err, "Compilation.hooks.optimizeChunkModules")
  3053. );
  3054. }
  3055. this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules);
  3056. const shouldRecord = this.hooks.shouldRecord.call() !== false;
  3057. this.hooks.reviveModules.call(
  3058. this.modules,
  3059. /** @type {Records} */
  3060. (this.records)
  3061. );
  3062. this.hooks.beforeModuleIds.call(this.modules);
  3063. this.hooks.moduleIds.call(this.modules);
  3064. this.hooks.optimizeModuleIds.call(this.modules);
  3065. this.hooks.afterOptimizeModuleIds.call(this.modules);
  3066. this.hooks.reviveChunks.call(
  3067. this.chunks,
  3068. /** @type {Records} */
  3069. (this.records)
  3070. );
  3071. this.hooks.beforeChunkIds.call(this.chunks);
  3072. this.hooks.chunkIds.call(this.chunks);
  3073. this.hooks.optimizeChunkIds.call(this.chunks);
  3074. this.hooks.afterOptimizeChunkIds.call(this.chunks);
  3075. this.assignRuntimeIds();
  3076. this.logger.time("compute affected modules with chunk graph");
  3077. this._computeAffectedModulesWithChunkGraph();
  3078. this.logger.timeEnd("compute affected modules with chunk graph");
  3079. this.sortItemsWithChunkIds();
  3080. if (shouldRecord) {
  3081. this.hooks.recordModules.call(
  3082. this.modules,
  3083. /** @type {Records} */
  3084. (this.records)
  3085. );
  3086. this.hooks.recordChunks.call(
  3087. this.chunks,
  3088. /** @type {Records} */
  3089. (this.records)
  3090. );
  3091. }
  3092. this.hooks.optimizeCodeGeneration.call(this.modules);
  3093. this.logger.timeEnd("optimize");
  3094. this.logger.time("module hashing");
  3095. this.hooks.beforeModuleHash.call();
  3096. this.createModuleHashes();
  3097. this.hooks.afterModuleHash.call();
  3098. this.logger.timeEnd("module hashing");
  3099. this.logger.time("code generation");
  3100. this.hooks.beforeCodeGeneration.call();
  3101. this.codeGeneration(err => {
  3102. if (err) {
  3103. return finalCallback(err);
  3104. }
  3105. this.hooks.afterCodeGeneration.call();
  3106. this.logger.timeEnd("code generation");
  3107. this.logger.time("runtime requirements");
  3108. this.hooks.beforeRuntimeRequirements.call();
  3109. this.processRuntimeRequirements();
  3110. this.hooks.afterRuntimeRequirements.call();
  3111. this.logger.timeEnd("runtime requirements");
  3112. this.logger.time("hashing");
  3113. this.hooks.beforeHash.call();
  3114. const codeGenerationJobs = this.createHash();
  3115. this.hooks.afterHash.call();
  3116. this.logger.timeEnd("hashing");
  3117. this._runCodeGenerationJobs(codeGenerationJobs, err => {
  3118. if (err) {
  3119. return finalCallback(err);
  3120. }
  3121. if (shouldRecord) {
  3122. this.logger.time("record hash");
  3123. this.hooks.recordHash.call(
  3124. /** @type {Records} */
  3125. (this.records)
  3126. );
  3127. this.logger.timeEnd("record hash");
  3128. }
  3129. this.logger.time("module assets");
  3130. this.clearAssets();
  3131. this.hooks.beforeModuleAssets.call();
  3132. this.createModuleAssets();
  3133. this.logger.timeEnd("module assets");
  3134. const cont = () => {
  3135. this.logger.time("process assets");
  3136. this.hooks.processAssets.callAsync(this.assets, err => {
  3137. if (err) {
  3138. return finalCallback(
  3139. makeWebpackError(err, "Compilation.hooks.processAssets")
  3140. );
  3141. }
  3142. this.hooks.afterProcessAssets.call(this.assets);
  3143. this.logger.timeEnd("process assets");
  3144. this.assets =
  3145. /** @type {CompilationAssets} */
  3146. (
  3147. this._backCompat
  3148. ? soonFrozenObjectDeprecation(
  3149. this.assets,
  3150. "Compilation.assets",
  3151. "DEP_WEBPACK_COMPILATION_ASSETS",
  3152. `BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
  3153. Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
  3154. Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.`
  3155. )
  3156. : Object.freeze(this.assets)
  3157. );
  3158. this.summarizeDependencies();
  3159. if (shouldRecord) {
  3160. this.hooks.record.call(
  3161. this,
  3162. /** @type {Records} */
  3163. (this.records)
  3164. );
  3165. }
  3166. if (this.hooks.needAdditionalSeal.call()) {
  3167. this.unseal();
  3168. return this.seal(callback);
  3169. }
  3170. return this.hooks.afterSeal.callAsync(err => {
  3171. if (err) {
  3172. return finalCallback(
  3173. makeWebpackError(err, "Compilation.hooks.afterSeal")
  3174. );
  3175. }
  3176. this.fileSystemInfo.logStatistics();
  3177. finalCallback();
  3178. });
  3179. });
  3180. };
  3181. this.logger.time("create chunk assets");
  3182. if (this.hooks.shouldGenerateChunkAssets.call() !== false) {
  3183. this.hooks.beforeChunkAssets.call();
  3184. this.createChunkAssets(err => {
  3185. this.logger.timeEnd("create chunk assets");
  3186. if (err) {
  3187. return finalCallback(err);
  3188. }
  3189. cont();
  3190. });
  3191. } else {
  3192. this.logger.timeEnd("create chunk assets");
  3193. cont();
  3194. }
  3195. });
  3196. });
  3197. }
  3198. );
  3199. });
  3200. }
  3201. /**
  3202. * @param {Module} module module to report from
  3203. * @param {DependenciesBlock[]} blocks blocks to report from
  3204. * @returns {boolean} true, when it has warnings or errors
  3205. */
  3206. reportDependencyErrorsAndWarnings(module, blocks) {
  3207. let hasProblems = false;
  3208. for (const block of blocks) {
  3209. const dependencies = block.dependencies;
  3210. for (const d of dependencies) {
  3211. const warnings = d.getWarnings(this.moduleGraph);
  3212. if (warnings) {
  3213. for (const w of warnings) {
  3214. const warning = new ModuleDependencyWarning(module, w, d.loc);
  3215. this.warnings.push(warning);
  3216. hasProblems = true;
  3217. }
  3218. }
  3219. const errors = d.getErrors(this.moduleGraph);
  3220. if (errors) {
  3221. for (const e of errors) {
  3222. const error = new ModuleDependencyError(module, e, d.loc);
  3223. this.errors.push(error);
  3224. hasProblems = true;
  3225. }
  3226. }
  3227. }
  3228. if (this.reportDependencyErrorsAndWarnings(module, block.blocks)) {
  3229. hasProblems = true;
  3230. }
  3231. }
  3232. return hasProblems;
  3233. }
  3234. /**
  3235. * @param {Callback} callback callback
  3236. */
  3237. codeGeneration(callback) {
  3238. const { chunkGraph } = this;
  3239. this.codeGenerationResults = new CodeGenerationResults(
  3240. this.outputOptions.hashFunction
  3241. );
  3242. /** @type {CodeGenerationJobs} */
  3243. const jobs = [];
  3244. for (const module of this.modules) {
  3245. const runtimes = chunkGraph.getModuleRuntimes(module);
  3246. if (runtimes.size === 1) {
  3247. for (const runtime of runtimes) {
  3248. const hash = chunkGraph.getModuleHash(module, runtime);
  3249. jobs.push({ module, hash, runtime, runtimes: [runtime] });
  3250. }
  3251. } else if (runtimes.size > 1) {
  3252. /** @type {Map<string, { runtimes: RuntimeSpec[] }>} */
  3253. const map = new Map();
  3254. for (const runtime of runtimes) {
  3255. const hash = chunkGraph.getModuleHash(module, runtime);
  3256. const job = map.get(hash);
  3257. if (job === undefined) {
  3258. const newJob = { module, hash, runtime, runtimes: [runtime] };
  3259. jobs.push(newJob);
  3260. map.set(hash, newJob);
  3261. } else {
  3262. job.runtimes.push(runtime);
  3263. }
  3264. }
  3265. }
  3266. }
  3267. this._runCodeGenerationJobs(jobs, callback);
  3268. }
  3269. /**
  3270. * @private
  3271. * @param {CodeGenerationJobs} jobs code generation jobs
  3272. * @param {Callback} callback callback
  3273. * @returns {void}
  3274. */
  3275. _runCodeGenerationJobs(jobs, callback) {
  3276. if (jobs.length === 0) {
  3277. return callback();
  3278. }
  3279. let statModulesFromCache = 0;
  3280. let statModulesGenerated = 0;
  3281. const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } =
  3282. this;
  3283. const results = this.codeGenerationResults;
  3284. /** @type {WebpackError[]} */
  3285. const errors = [];
  3286. /** @type {NotCodeGeneratedModules | undefined} */
  3287. let notCodeGeneratedModules;
  3288. const runIteration = () => {
  3289. /** @type {CodeGenerationJobs} */
  3290. let delayedJobs = [];
  3291. let delayedModules = new Set();
  3292. asyncLib.eachLimit(
  3293. jobs,
  3294. /** @type {number} */
  3295. (this.options.parallelism),
  3296. (job, callback) => {
  3297. const { module } = job;
  3298. const { codeGenerationDependencies } = module;
  3299. if (
  3300. codeGenerationDependencies !== undefined &&
  3301. (notCodeGeneratedModules === undefined ||
  3302. codeGenerationDependencies.some(dep => {
  3303. const referencedModule = /** @type {Module} */ (
  3304. moduleGraph.getModule(dep)
  3305. );
  3306. return /** @type {NotCodeGeneratedModules} */ (
  3307. notCodeGeneratedModules
  3308. ).has(referencedModule);
  3309. }))
  3310. ) {
  3311. delayedJobs.push(job);
  3312. delayedModules.add(module);
  3313. return callback();
  3314. }
  3315. const { hash, runtime, runtimes } = job;
  3316. this._codeGenerationModule(
  3317. module,
  3318. runtime,
  3319. runtimes,
  3320. hash,
  3321. dependencyTemplates,
  3322. chunkGraph,
  3323. moduleGraph,
  3324. runtimeTemplate,
  3325. errors,
  3326. results,
  3327. (err, codeGenerated) => {
  3328. if (codeGenerated) statModulesGenerated++;
  3329. else statModulesFromCache++;
  3330. callback(err);
  3331. }
  3332. );
  3333. },
  3334. err => {
  3335. if (err) return callback(err);
  3336. if (delayedJobs.length > 0) {
  3337. if (delayedJobs.length === jobs.length) {
  3338. return callback(
  3339. /** @type {WebpackError} */ (
  3340. new Error(
  3341. `Unable to make progress during code generation because of circular code generation dependency: ${Array.from(
  3342. delayedModules,
  3343. m => m.identifier()
  3344. ).join(", ")}`
  3345. )
  3346. )
  3347. );
  3348. }
  3349. jobs = delayedJobs;
  3350. delayedJobs = [];
  3351. notCodeGeneratedModules = delayedModules;
  3352. delayedModules = new Set();
  3353. return runIteration();
  3354. }
  3355. if (errors.length > 0) {
  3356. errors.sort(
  3357. compareSelect(err => err.module, compareModulesByIdentifier)
  3358. );
  3359. for (const error of errors) {
  3360. this.errors.push(error);
  3361. }
  3362. }
  3363. this.logger.log(
  3364. `${Math.round(
  3365. (100 * statModulesGenerated) /
  3366. (statModulesGenerated + statModulesFromCache)
  3367. )}% code generated (${statModulesGenerated} generated, ${statModulesFromCache} from cache)`
  3368. );
  3369. callback();
  3370. }
  3371. );
  3372. };
  3373. runIteration();
  3374. }
  3375. /**
  3376. * @param {Module} module module
  3377. * @param {RuntimeSpec} runtime runtime
  3378. * @param {RuntimeSpec[]} runtimes runtimes
  3379. * @param {string} hash hash
  3380. * @param {DependencyTemplates} dependencyTemplates dependencyTemplates
  3381. * @param {ChunkGraph} chunkGraph chunkGraph
  3382. * @param {ModuleGraph} moduleGraph moduleGraph
  3383. * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate
  3384. * @param {WebpackError[]} errors errors
  3385. * @param {CodeGenerationResults} results results
  3386. * @param {(err?: WebpackError | null, result?: boolean) => void} callback callback
  3387. */
  3388. _codeGenerationModule(
  3389. module,
  3390. runtime,
  3391. runtimes,
  3392. hash,
  3393. dependencyTemplates,
  3394. chunkGraph,
  3395. moduleGraph,
  3396. runtimeTemplate,
  3397. errors,
  3398. results,
  3399. callback
  3400. ) {
  3401. let codeGenerated = false;
  3402. const cache = new MultiItemCache(
  3403. runtimes.map(runtime =>
  3404. this._codeGenerationCache.getItemCache(
  3405. `${module.identifier()}|${getRuntimeKey(runtime)}`,
  3406. `${hash}|${dependencyTemplates.getHash()}`
  3407. )
  3408. )
  3409. );
  3410. cache.get((err, cachedResult) => {
  3411. if (err) return callback(/** @type {WebpackError} */ (err));
  3412. let result;
  3413. if (!cachedResult) {
  3414. try {
  3415. codeGenerated = true;
  3416. this.codeGeneratedModules.add(module);
  3417. result = module.codeGeneration({
  3418. chunkGraph,
  3419. moduleGraph,
  3420. dependencyTemplates,
  3421. runtimeTemplate,
  3422. runtime,
  3423. codeGenerationResults: results,
  3424. compilation: this
  3425. });
  3426. } catch (err) {
  3427. errors.push(
  3428. new CodeGenerationError(module, /** @type {Error} */ (err))
  3429. );
  3430. result = cachedResult = {
  3431. sources: new Map(),
  3432. runtimeRequirements: null
  3433. };
  3434. }
  3435. } else {
  3436. result = cachedResult;
  3437. }
  3438. for (const runtime of runtimes) {
  3439. results.add(module, runtime, result);
  3440. }
  3441. if (!cachedResult) {
  3442. cache.store(result, err =>
  3443. callback(/** @type {WebpackError} */ (err), codeGenerated)
  3444. );
  3445. } else {
  3446. callback(null, codeGenerated);
  3447. }
  3448. });
  3449. }
  3450. _getChunkGraphEntries() {
  3451. /** @type {Set<Chunk>} */
  3452. const treeEntries = new Set();
  3453. for (const ep of this.entrypoints.values()) {
  3454. const chunk = ep.getRuntimeChunk();
  3455. if (chunk) treeEntries.add(chunk);
  3456. }
  3457. for (const ep of this.asyncEntrypoints) {
  3458. const chunk = ep.getRuntimeChunk();
  3459. if (chunk) treeEntries.add(chunk);
  3460. }
  3461. return treeEntries;
  3462. }
  3463. /**
  3464. * @param {object} options options
  3465. * @param {ChunkGraph=} options.chunkGraph the chunk graph
  3466. * @param {Iterable<Module>=} options.modules modules
  3467. * @param {Iterable<Chunk>=} options.chunks chunks
  3468. * @param {CodeGenerationResults=} options.codeGenerationResults codeGenerationResults
  3469. * @param {Iterable<Chunk>=} options.chunkGraphEntries chunkGraphEntries
  3470. * @returns {void}
  3471. */
  3472. processRuntimeRequirements({
  3473. chunkGraph = this.chunkGraph,
  3474. modules = this.modules,
  3475. chunks = this.chunks,
  3476. codeGenerationResults = this.codeGenerationResults,
  3477. chunkGraphEntries = this._getChunkGraphEntries()
  3478. } = {}) {
  3479. const context = { chunkGraph, codeGenerationResults };
  3480. const { moduleMemCaches2 } = this;
  3481. this.logger.time("runtime requirements.modules");
  3482. const additionalModuleRuntimeRequirements =
  3483. this.hooks.additionalModuleRuntimeRequirements;
  3484. const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule;
  3485. for (const module of modules) {
  3486. if (chunkGraph.getNumberOfModuleChunks(module) > 0) {
  3487. const memCache = moduleMemCaches2 && moduleMemCaches2.get(module);
  3488. for (const runtime of chunkGraph.getModuleRuntimes(module)) {
  3489. if (memCache) {
  3490. const cached = memCache.get(
  3491. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`
  3492. );
  3493. if (cached !== undefined) {
  3494. if (cached !== null) {
  3495. chunkGraph.addModuleRuntimeRequirements(
  3496. module,
  3497. runtime,
  3498. /** @type {RuntimeRequirements} */
  3499. (cached),
  3500. false
  3501. );
  3502. }
  3503. continue;
  3504. }
  3505. }
  3506. let set;
  3507. const runtimeRequirements =
  3508. codeGenerationResults.getRuntimeRequirements(module, runtime);
  3509. if (runtimeRequirements && runtimeRequirements.size > 0) {
  3510. set = new Set(runtimeRequirements);
  3511. } else if (additionalModuleRuntimeRequirements.isUsed()) {
  3512. set = new Set();
  3513. } else {
  3514. if (memCache) {
  3515. memCache.set(
  3516. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`,
  3517. null
  3518. );
  3519. }
  3520. continue;
  3521. }
  3522. additionalModuleRuntimeRequirements.call(module, set, context);
  3523. for (const r of set) {
  3524. const hook = runtimeRequirementInModule.get(r);
  3525. if (hook !== undefined) hook.call(module, set, context);
  3526. }
  3527. if (set.size === 0) {
  3528. if (memCache) {
  3529. memCache.set(
  3530. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`,
  3531. null
  3532. );
  3533. }
  3534. } else if (memCache) {
  3535. memCache.set(
  3536. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`,
  3537. set
  3538. );
  3539. chunkGraph.addModuleRuntimeRequirements(
  3540. module,
  3541. runtime,
  3542. set,
  3543. false
  3544. );
  3545. } else {
  3546. chunkGraph.addModuleRuntimeRequirements(module, runtime, set);
  3547. }
  3548. }
  3549. }
  3550. }
  3551. this.logger.timeEnd("runtime requirements.modules");
  3552. this.logger.time("runtime requirements.chunks");
  3553. for (const chunk of chunks) {
  3554. const set = new Set();
  3555. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  3556. const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements(
  3557. module,
  3558. chunk.runtime
  3559. );
  3560. for (const r of runtimeRequirements) set.add(r);
  3561. }
  3562. this.hooks.additionalChunkRuntimeRequirements.call(chunk, set, context);
  3563. for (const r of set) {
  3564. this.hooks.runtimeRequirementInChunk.for(r).call(chunk, set, context);
  3565. }
  3566. chunkGraph.addChunkRuntimeRequirements(chunk, set);
  3567. }
  3568. this.logger.timeEnd("runtime requirements.chunks");
  3569. this.logger.time("runtime requirements.entries");
  3570. for (const treeEntry of chunkGraphEntries) {
  3571. const set = new Set();
  3572. for (const chunk of treeEntry.getAllReferencedChunks()) {
  3573. const runtimeRequirements =
  3574. chunkGraph.getChunkRuntimeRequirements(chunk);
  3575. for (const r of runtimeRequirements) set.add(r);
  3576. }
  3577. this.hooks.additionalTreeRuntimeRequirements.call(
  3578. treeEntry,
  3579. set,
  3580. context
  3581. );
  3582. for (const r of set) {
  3583. this.hooks.runtimeRequirementInTree
  3584. .for(r)
  3585. .call(treeEntry, set, context);
  3586. }
  3587. chunkGraph.addTreeRuntimeRequirements(treeEntry, set);
  3588. }
  3589. this.logger.timeEnd("runtime requirements.entries");
  3590. }
  3591. // TODO webpack 6 make chunkGraph argument non-optional
  3592. /**
  3593. * @param {Chunk} chunk target chunk
  3594. * @param {RuntimeModule} module runtime module
  3595. * @param {ChunkGraph} chunkGraph the chunk graph
  3596. * @returns {void}
  3597. */
  3598. addRuntimeModule(chunk, module, chunkGraph = this.chunkGraph) {
  3599. // Deprecated ModuleGraph association
  3600. if (this._backCompat) {
  3601. ModuleGraph.setModuleGraphForModule(module, this.moduleGraph);
  3602. }
  3603. // add it to the list
  3604. this.modules.add(module);
  3605. this._modules.set(module.identifier(), module);
  3606. // connect to the chunk graph
  3607. chunkGraph.connectChunkAndModule(chunk, module);
  3608. chunkGraph.connectChunkAndRuntimeModule(chunk, module);
  3609. if (module.fullHash) {
  3610. chunkGraph.addFullHashModuleToChunk(chunk, module);
  3611. } else if (module.dependentHash) {
  3612. chunkGraph.addDependentHashModuleToChunk(chunk, module);
  3613. }
  3614. // attach runtime module
  3615. module.attach(this, chunk, chunkGraph);
  3616. // Setup internals
  3617. const exportsInfo = this.moduleGraph.getExportsInfo(module);
  3618. exportsInfo.setHasProvideInfo();
  3619. if (typeof chunk.runtime === "string") {
  3620. exportsInfo.setUsedForSideEffectsOnly(chunk.runtime);
  3621. } else if (chunk.runtime === undefined) {
  3622. exportsInfo.setUsedForSideEffectsOnly(undefined);
  3623. } else {
  3624. for (const runtime of chunk.runtime) {
  3625. exportsInfo.setUsedForSideEffectsOnly(runtime);
  3626. }
  3627. }
  3628. chunkGraph.addModuleRuntimeRequirements(
  3629. module,
  3630. chunk.runtime,
  3631. new Set([RuntimeGlobals.requireScope])
  3632. );
  3633. // runtime modules don't need ids
  3634. chunkGraph.setModuleId(module, "");
  3635. // Call hook
  3636. this.hooks.runtimeModule.call(module, chunk);
  3637. }
  3638. /**
  3639. * If `module` is passed, `loc` and `request` must also be passed.
  3640. * @param {string | ChunkGroupOptions} groupOptions options for the chunk group
  3641. * @param {Module=} module the module the references the chunk group
  3642. * @param {DependencyLocation=} loc the location from with the chunk group is referenced (inside of module)
  3643. * @param {string=} request the request from which the the chunk group is referenced
  3644. * @returns {ChunkGroup} the new or existing chunk group
  3645. */
  3646. addChunkInGroup(groupOptions, module, loc, request) {
  3647. if (typeof groupOptions === "string") {
  3648. groupOptions = { name: groupOptions };
  3649. }
  3650. const name = groupOptions.name;
  3651. if (name) {
  3652. const chunkGroup = this.namedChunkGroups.get(name);
  3653. if (chunkGroup !== undefined) {
  3654. if (module) {
  3655. chunkGroup.addOrigin(
  3656. module,
  3657. /** @type {DependencyLocation} */
  3658. (loc),
  3659. /** @type {string} */
  3660. (request)
  3661. );
  3662. }
  3663. return chunkGroup;
  3664. }
  3665. }
  3666. const chunkGroup = new ChunkGroup(groupOptions);
  3667. if (module) {
  3668. chunkGroup.addOrigin(
  3669. module,
  3670. /** @type {DependencyLocation} */
  3671. (loc),
  3672. /** @type {string} */
  3673. (request)
  3674. );
  3675. }
  3676. const chunk = this.addChunk(name);
  3677. connectChunkGroupAndChunk(chunkGroup, chunk);
  3678. this.chunkGroups.push(chunkGroup);
  3679. if (name) {
  3680. this.namedChunkGroups.set(name, chunkGroup);
  3681. }
  3682. return chunkGroup;
  3683. }
  3684. /**
  3685. * @param {EntryOptions} options options for the entrypoint
  3686. * @param {Module} module the module the references the chunk group
  3687. * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module)
  3688. * @param {string} request the request from which the the chunk group is referenced
  3689. * @returns {Entrypoint} the new or existing entrypoint
  3690. */
  3691. addAsyncEntrypoint(options, module, loc, request) {
  3692. const name = options.name;
  3693. if (name) {
  3694. const entrypoint = this.namedChunkGroups.get(name);
  3695. if (entrypoint instanceof Entrypoint) {
  3696. if (entrypoint !== undefined) {
  3697. if (module) {
  3698. entrypoint.addOrigin(module, loc, request);
  3699. }
  3700. return entrypoint;
  3701. }
  3702. } else if (entrypoint) {
  3703. throw new Error(
  3704. `Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name`
  3705. );
  3706. }
  3707. }
  3708. const chunk = this.addChunk(name);
  3709. if (options.filename) {
  3710. chunk.filenameTemplate = options.filename;
  3711. }
  3712. const entrypoint = new Entrypoint(options, false);
  3713. entrypoint.setRuntimeChunk(chunk);
  3714. entrypoint.setEntrypointChunk(chunk);
  3715. if (name) {
  3716. this.namedChunkGroups.set(name, entrypoint);
  3717. }
  3718. this.chunkGroups.push(entrypoint);
  3719. this.asyncEntrypoints.push(entrypoint);
  3720. connectChunkGroupAndChunk(entrypoint, chunk);
  3721. if (module) {
  3722. entrypoint.addOrigin(module, loc, request);
  3723. }
  3724. return entrypoint;
  3725. }
  3726. /**
  3727. * This method first looks to see if a name is provided for a new chunk,
  3728. * and first looks to see if any named chunks already exist and reuse that chunk instead.
  3729. * @param {ChunkName=} name optional chunk name to be provided
  3730. * @returns {Chunk} create a chunk (invoked during seal event)
  3731. */
  3732. addChunk(name) {
  3733. if (name) {
  3734. const chunk = this.namedChunks.get(name);
  3735. if (chunk !== undefined) {
  3736. return chunk;
  3737. }
  3738. }
  3739. const chunk = new Chunk(name, this._backCompat);
  3740. this.chunks.add(chunk);
  3741. if (this._backCompat) {
  3742. ChunkGraph.setChunkGraphForChunk(chunk, this.chunkGraph);
  3743. }
  3744. if (name) {
  3745. this.namedChunks.set(name, chunk);
  3746. }
  3747. return chunk;
  3748. }
  3749. /**
  3750. * @deprecated
  3751. * @param {Module} module module to assign depth
  3752. * @returns {void}
  3753. */
  3754. assignDepth(module) {
  3755. const moduleGraph = this.moduleGraph;
  3756. const queue = new Set([module]);
  3757. /** @type {number} */
  3758. let depth;
  3759. moduleGraph.setDepth(module, 0);
  3760. /**
  3761. * @param {Module} module module for processing
  3762. * @returns {void}
  3763. */
  3764. const processModule = module => {
  3765. if (!moduleGraph.setDepthIfLower(module, depth)) return;
  3766. queue.add(module);
  3767. };
  3768. for (module of queue) {
  3769. queue.delete(module);
  3770. depth = /** @type {number} */ (moduleGraph.getDepth(module)) + 1;
  3771. for (const connection of moduleGraph.getOutgoingConnections(module)) {
  3772. const refModule = connection.module;
  3773. if (refModule) {
  3774. processModule(refModule);
  3775. }
  3776. }
  3777. }
  3778. }
  3779. /**
  3780. * @param {Set<Module>} modules module to assign depth
  3781. * @returns {void}
  3782. */
  3783. assignDepths(modules) {
  3784. const moduleGraph = this.moduleGraph;
  3785. /** @type {Set<Module>} */
  3786. const queue = new Set(modules);
  3787. // Track these in local variables so that queue only has one data type
  3788. let nextDepthAt = queue.size;
  3789. let depth = 0;
  3790. let i = 0;
  3791. for (const module of queue) {
  3792. moduleGraph.setDepth(module, depth);
  3793. // Some of these results come from cache, which speeds this up
  3794. const connections = moduleGraph.getOutgoingConnectionsByModule(module);
  3795. // connections will be undefined if there are no outgoing connections
  3796. if (connections) {
  3797. for (const refModule of connections.keys()) {
  3798. if (refModule) queue.add(refModule);
  3799. }
  3800. }
  3801. i++;
  3802. // Since this is a breadth-first search, all modules added to the queue
  3803. // while at depth N will be depth N+1
  3804. if (i >= nextDepthAt) {
  3805. depth++;
  3806. nextDepthAt = queue.size;
  3807. }
  3808. }
  3809. }
  3810. /**
  3811. * @param {Dependency} dependency the dependency
  3812. * @param {RuntimeSpec} runtime the runtime
  3813. * @returns {(string[] | ReferencedExport)[]} referenced exports
  3814. */
  3815. getDependencyReferencedExports(dependency, runtime) {
  3816. const referencedExports = dependency.getReferencedExports(
  3817. this.moduleGraph,
  3818. runtime
  3819. );
  3820. return this.hooks.dependencyReferencedExports.call(
  3821. referencedExports,
  3822. dependency,
  3823. runtime
  3824. );
  3825. }
  3826. /**
  3827. * @param {Module} module module relationship for removal
  3828. * @param {DependenciesBlockLike} block dependencies block
  3829. * @returns {void}
  3830. */
  3831. removeReasonsOfDependencyBlock(module, block) {
  3832. if (block.blocks) {
  3833. for (const b of block.blocks) {
  3834. this.removeReasonsOfDependencyBlock(module, b);
  3835. }
  3836. }
  3837. if (block.dependencies) {
  3838. for (const dep of block.dependencies) {
  3839. const originalModule = this.moduleGraph.getModule(dep);
  3840. if (originalModule) {
  3841. this.moduleGraph.removeConnection(dep);
  3842. if (this.chunkGraph) {
  3843. for (const chunk of this.chunkGraph.getModuleChunks(
  3844. originalModule
  3845. )) {
  3846. this.patchChunksAfterReasonRemoval(originalModule, chunk);
  3847. }
  3848. }
  3849. }
  3850. }
  3851. }
  3852. }
  3853. /**
  3854. * @param {Module} module module to patch tie
  3855. * @param {Chunk} chunk chunk to patch tie
  3856. * @returns {void}
  3857. */
  3858. patchChunksAfterReasonRemoval(module, chunk) {
  3859. if (!module.hasReasons(this.moduleGraph, chunk.runtime)) {
  3860. this.removeReasonsOfDependencyBlock(module, module);
  3861. }
  3862. if (
  3863. !module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph) &&
  3864. this.chunkGraph.isModuleInChunk(module, chunk)
  3865. ) {
  3866. this.chunkGraph.disconnectChunkAndModule(chunk, module);
  3867. this.removeChunkFromDependencies(module, chunk);
  3868. }
  3869. }
  3870. /**
  3871. * @param {DependenciesBlock} block block tie for Chunk
  3872. * @param {Chunk} chunk chunk to remove from dep
  3873. * @returns {void}
  3874. */
  3875. removeChunkFromDependencies(block, chunk) {
  3876. /**
  3877. * @param {Dependency} d dependency to (maybe) patch up
  3878. */
  3879. const iteratorDependency = d => {
  3880. const depModule = this.moduleGraph.getModule(d);
  3881. if (!depModule) {
  3882. return;
  3883. }
  3884. this.patchChunksAfterReasonRemoval(depModule, chunk);
  3885. };
  3886. const blocks = block.blocks;
  3887. for (const asyncBlock of blocks) {
  3888. const chunkGroup =
  3889. /** @type {ChunkGroup} */
  3890. (this.chunkGraph.getBlockChunkGroup(asyncBlock));
  3891. // Grab all chunks from the first Block's AsyncDepBlock
  3892. const chunks = chunkGroup.chunks;
  3893. // For each chunk in chunkGroup
  3894. for (const iteratedChunk of chunks) {
  3895. chunkGroup.removeChunk(iteratedChunk);
  3896. // Recurse
  3897. this.removeChunkFromDependencies(block, iteratedChunk);
  3898. }
  3899. }
  3900. if (block.dependencies) {
  3901. for (const dep of block.dependencies) iteratorDependency(dep);
  3902. }
  3903. }
  3904. assignRuntimeIds() {
  3905. const { chunkGraph } = this;
  3906. /**
  3907. * @param {Entrypoint} ep an entrypoint
  3908. */
  3909. const processEntrypoint = ep => {
  3910. const runtime = /** @type {string} */ (ep.options.runtime || ep.name);
  3911. const chunk = /** @type {Chunk} */ (ep.getRuntimeChunk());
  3912. chunkGraph.setRuntimeId(runtime, /** @type {ChunkId} */ (chunk.id));
  3913. };
  3914. for (const ep of this.entrypoints.values()) {
  3915. processEntrypoint(ep);
  3916. }
  3917. for (const ep of this.asyncEntrypoints) {
  3918. processEntrypoint(ep);
  3919. }
  3920. }
  3921. sortItemsWithChunkIds() {
  3922. for (const chunkGroup of this.chunkGroups) {
  3923. chunkGroup.sortItems();
  3924. }
  3925. this.errors.sort(compareErrors);
  3926. this.warnings.sort(compareErrors);
  3927. this.children.sort(byNameOrHash);
  3928. }
  3929. summarizeDependencies() {
  3930. for (const child of this.children) {
  3931. this.fileDependencies.addAll(child.fileDependencies);
  3932. this.contextDependencies.addAll(child.contextDependencies);
  3933. this.missingDependencies.addAll(child.missingDependencies);
  3934. this.buildDependencies.addAll(child.buildDependencies);
  3935. }
  3936. for (const module of this.modules) {
  3937. module.addCacheDependencies(
  3938. this.fileDependencies,
  3939. this.contextDependencies,
  3940. this.missingDependencies,
  3941. this.buildDependencies
  3942. );
  3943. }
  3944. }
  3945. createModuleHashes() {
  3946. let statModulesHashed = 0;
  3947. let statModulesFromCache = 0;
  3948. const { chunkGraph, runtimeTemplate, moduleMemCaches2 } = this;
  3949. const { hashFunction, hashDigest, hashDigestLength } = this.outputOptions;
  3950. /** @type {WebpackError[]} */
  3951. const errors = [];
  3952. for (const module of this.modules) {
  3953. const memCache = moduleMemCaches2 && moduleMemCaches2.get(module);
  3954. for (const runtime of chunkGraph.getModuleRuntimes(module)) {
  3955. if (memCache) {
  3956. const digest =
  3957. /** @type {string} */
  3958. (memCache.get(`moduleHash-${getRuntimeKey(runtime)}`));
  3959. if (digest !== undefined) {
  3960. chunkGraph.setModuleHashes(
  3961. module,
  3962. runtime,
  3963. digest,
  3964. digest.slice(0, hashDigestLength)
  3965. );
  3966. statModulesFromCache++;
  3967. continue;
  3968. }
  3969. }
  3970. statModulesHashed++;
  3971. const digest = this._createModuleHash(
  3972. module,
  3973. chunkGraph,
  3974. runtime,
  3975. hashFunction,
  3976. runtimeTemplate,
  3977. hashDigest,
  3978. hashDigestLength,
  3979. errors
  3980. );
  3981. if (memCache) {
  3982. memCache.set(`moduleHash-${getRuntimeKey(runtime)}`, digest);
  3983. }
  3984. }
  3985. }
  3986. if (errors.length > 0) {
  3987. errors.sort(compareSelect(err => err.module, compareModulesByIdentifier));
  3988. for (const error of errors) {
  3989. this.errors.push(error);
  3990. }
  3991. }
  3992. this.logger.log(
  3993. `${statModulesHashed} modules hashed, ${statModulesFromCache} from cache (${
  3994. Math.round(
  3995. (100 * (statModulesHashed + statModulesFromCache)) / this.modules.size
  3996. ) / 100
  3997. } variants per module in average)`
  3998. );
  3999. }
  4000. /**
  4001. * @private
  4002. * @param {Module} module module
  4003. * @param {ChunkGraph} chunkGraph the chunk graph
  4004. * @param {RuntimeSpec} runtime runtime
  4005. * @param {OutputOptions["hashFunction"]} hashFunction hash function
  4006. * @param {RuntimeTemplate} runtimeTemplate runtime template
  4007. * @param {OutputOptions["hashDigest"]} hashDigest hash digest
  4008. * @param {OutputOptions["hashDigestLength"]} hashDigestLength hash digest length
  4009. * @param {WebpackError[]} errors errors
  4010. * @returns {string} module hash digest
  4011. */
  4012. _createModuleHash(
  4013. module,
  4014. chunkGraph,
  4015. runtime,
  4016. hashFunction,
  4017. runtimeTemplate,
  4018. hashDigest,
  4019. hashDigestLength,
  4020. errors
  4021. ) {
  4022. let moduleHashDigest;
  4023. try {
  4024. const moduleHash = createHash(/** @type {HashFunction} */ (hashFunction));
  4025. module.updateHash(moduleHash, {
  4026. chunkGraph,
  4027. runtime,
  4028. runtimeTemplate
  4029. });
  4030. moduleHashDigest = /** @type {string} */ (moduleHash.digest(hashDigest));
  4031. } catch (err) {
  4032. errors.push(new ModuleHashingError(module, /** @type {Error} */ (err)));
  4033. moduleHashDigest = "XXXXXX";
  4034. }
  4035. chunkGraph.setModuleHashes(
  4036. module,
  4037. runtime,
  4038. moduleHashDigest,
  4039. moduleHashDigest.slice(0, hashDigestLength)
  4040. );
  4041. return moduleHashDigest;
  4042. }
  4043. createHash() {
  4044. this.logger.time("hashing: initialize hash");
  4045. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  4046. const runtimeTemplate = this.runtimeTemplate;
  4047. const outputOptions = this.outputOptions;
  4048. const hashFunction = outputOptions.hashFunction;
  4049. const hashDigest = outputOptions.hashDigest;
  4050. const hashDigestLength = outputOptions.hashDigestLength;
  4051. const hash = createHash(/** @type {HashFunction} */ (hashFunction));
  4052. if (outputOptions.hashSalt) {
  4053. hash.update(outputOptions.hashSalt);
  4054. }
  4055. this.logger.timeEnd("hashing: initialize hash");
  4056. if (this.children.length > 0) {
  4057. this.logger.time("hashing: hash child compilations");
  4058. for (const child of this.children) {
  4059. hash.update(/** @type {string} */ (child.hash));
  4060. }
  4061. this.logger.timeEnd("hashing: hash child compilations");
  4062. }
  4063. if (this.warnings.length > 0) {
  4064. this.logger.time("hashing: hash warnings");
  4065. for (const warning of this.warnings) {
  4066. hash.update(`${warning.message}`);
  4067. }
  4068. this.logger.timeEnd("hashing: hash warnings");
  4069. }
  4070. if (this.errors.length > 0) {
  4071. this.logger.time("hashing: hash errors");
  4072. for (const error of this.errors) {
  4073. hash.update(`${error.message}`);
  4074. }
  4075. this.logger.timeEnd("hashing: hash errors");
  4076. }
  4077. this.logger.time("hashing: sort chunks");
  4078. /*
  4079. * all non-runtime chunks need to be hashes first,
  4080. * since runtime chunk might use their hashes.
  4081. * runtime chunks need to be hashed in the correct order
  4082. * since they may depend on each other (for async entrypoints).
  4083. * So we put all non-runtime chunks first and hash them in any order.
  4084. * And order runtime chunks according to referenced between each other.
  4085. * Chunks need to be in deterministic order since we add hashes to full chunk
  4086. * during these hashing.
  4087. */
  4088. /** @type {Chunk[]} */
  4089. const unorderedRuntimeChunks = [];
  4090. /** @type {Chunk[]} */
  4091. const initialChunks = [];
  4092. /** @type {Chunk[]} */
  4093. const asyncChunks = [];
  4094. for (const c of this.chunks) {
  4095. if (c.hasRuntime()) {
  4096. unorderedRuntimeChunks.push(c);
  4097. } else if (c.canBeInitial()) {
  4098. initialChunks.push(c);
  4099. } else {
  4100. asyncChunks.push(c);
  4101. }
  4102. }
  4103. unorderedRuntimeChunks.sort(byId);
  4104. initialChunks.sort(byId);
  4105. asyncChunks.sort(byId);
  4106. /** @typedef {{ chunk: Chunk, referencedBy: RuntimeChunkInfo[], remaining: number }} RuntimeChunkInfo */
  4107. /** @type {Map<Chunk, RuntimeChunkInfo>} */
  4108. const runtimeChunksMap = new Map();
  4109. for (const chunk of unorderedRuntimeChunks) {
  4110. runtimeChunksMap.set(chunk, {
  4111. chunk,
  4112. referencedBy: [],
  4113. remaining: 0
  4114. });
  4115. }
  4116. let remaining = 0;
  4117. for (const info of runtimeChunksMap.values()) {
  4118. for (const other of new Set(
  4119. [...info.chunk.getAllReferencedAsyncEntrypoints()].map(
  4120. e => e.chunks[e.chunks.length - 1]
  4121. )
  4122. )) {
  4123. const otherInfo =
  4124. /** @type {RuntimeChunkInfo} */
  4125. (runtimeChunksMap.get(other));
  4126. otherInfo.referencedBy.push(info);
  4127. info.remaining++;
  4128. remaining++;
  4129. }
  4130. }
  4131. /** @type {Chunk[]} */
  4132. const runtimeChunks = [];
  4133. for (const info of runtimeChunksMap.values()) {
  4134. if (info.remaining === 0) {
  4135. runtimeChunks.push(info.chunk);
  4136. }
  4137. }
  4138. // If there are any references between chunks
  4139. // make sure to follow these chains
  4140. if (remaining > 0) {
  4141. const readyChunks = [];
  4142. for (const chunk of runtimeChunks) {
  4143. const hasFullHashModules =
  4144. chunkGraph.getNumberOfChunkFullHashModules(chunk) !== 0;
  4145. const info =
  4146. /** @type {RuntimeChunkInfo} */
  4147. (runtimeChunksMap.get(chunk));
  4148. for (const otherInfo of info.referencedBy) {
  4149. if (hasFullHashModules) {
  4150. chunkGraph.upgradeDependentToFullHashModules(otherInfo.chunk);
  4151. }
  4152. remaining--;
  4153. if (--otherInfo.remaining === 0) {
  4154. readyChunks.push(otherInfo.chunk);
  4155. }
  4156. }
  4157. if (readyChunks.length > 0) {
  4158. // This ensures deterministic ordering, since referencedBy is non-deterministic
  4159. readyChunks.sort(byId);
  4160. for (const c of readyChunks) runtimeChunks.push(c);
  4161. readyChunks.length = 0;
  4162. }
  4163. }
  4164. }
  4165. // If there are still remaining references we have cycles and want to create a warning
  4166. if (remaining > 0) {
  4167. const circularRuntimeChunkInfo = [];
  4168. for (const info of runtimeChunksMap.values()) {
  4169. if (info.remaining !== 0) {
  4170. circularRuntimeChunkInfo.push(info);
  4171. }
  4172. }
  4173. circularRuntimeChunkInfo.sort(compareSelect(i => i.chunk, byId));
  4174. const err =
  4175. new WebpackError(`Circular dependency between chunks with runtime (${Array.from(
  4176. circularRuntimeChunkInfo,
  4177. c => c.chunk.name || c.chunk.id
  4178. ).join(", ")})
  4179. This prevents using hashes of each other and should be avoided.`);
  4180. err.chunk = circularRuntimeChunkInfo[0].chunk;
  4181. this.warnings.push(err);
  4182. for (const i of circularRuntimeChunkInfo) runtimeChunks.push(i.chunk);
  4183. }
  4184. this.logger.timeEnd("hashing: sort chunks");
  4185. const fullHashChunks = new Set();
  4186. /** @type {CodeGenerationJobs} */
  4187. const codeGenerationJobs = [];
  4188. /** @type {Map<string, Map<Module, CodeGenerationJob>>} */
  4189. const codeGenerationJobsMap = new Map();
  4190. /** @type {WebpackError[]} */
  4191. const errors = [];
  4192. /**
  4193. * @param {Chunk} chunk chunk
  4194. */
  4195. const processChunk = chunk => {
  4196. // Last minute module hash generation for modules that depend on chunk hashes
  4197. this.logger.time("hashing: hash runtime modules");
  4198. const runtime = chunk.runtime;
  4199. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  4200. if (!chunkGraph.hasModuleHashes(module, runtime)) {
  4201. const hash = this._createModuleHash(
  4202. module,
  4203. chunkGraph,
  4204. runtime,
  4205. hashFunction,
  4206. runtimeTemplate,
  4207. hashDigest,
  4208. hashDigestLength,
  4209. errors
  4210. );
  4211. let hashMap = codeGenerationJobsMap.get(hash);
  4212. if (hashMap) {
  4213. const moduleJob = hashMap.get(module);
  4214. if (moduleJob) {
  4215. moduleJob.runtimes.push(runtime);
  4216. continue;
  4217. }
  4218. } else {
  4219. hashMap = new Map();
  4220. codeGenerationJobsMap.set(hash, hashMap);
  4221. }
  4222. const job = {
  4223. module,
  4224. hash,
  4225. runtime,
  4226. runtimes: [runtime]
  4227. };
  4228. hashMap.set(module, job);
  4229. codeGenerationJobs.push(job);
  4230. }
  4231. }
  4232. this.logger.timeAggregate("hashing: hash runtime modules");
  4233. try {
  4234. this.logger.time("hashing: hash chunks");
  4235. const chunkHash = createHash(
  4236. /** @type {HashFunction} */ (hashFunction)
  4237. );
  4238. if (outputOptions.hashSalt) {
  4239. chunkHash.update(outputOptions.hashSalt);
  4240. }
  4241. chunk.updateHash(chunkHash, chunkGraph);
  4242. this.hooks.chunkHash.call(chunk, chunkHash, {
  4243. chunkGraph,
  4244. codeGenerationResults: this.codeGenerationResults,
  4245. moduleGraph: this.moduleGraph,
  4246. runtimeTemplate: this.runtimeTemplate
  4247. });
  4248. const chunkHashDigest = /** @type {string} */ (
  4249. chunkHash.digest(hashDigest)
  4250. );
  4251. hash.update(chunkHashDigest);
  4252. chunk.hash = chunkHashDigest;
  4253. chunk.renderedHash = chunk.hash.slice(0, hashDigestLength);
  4254. const fullHashModules =
  4255. chunkGraph.getChunkFullHashModulesIterable(chunk);
  4256. if (fullHashModules) {
  4257. fullHashChunks.add(chunk);
  4258. } else {
  4259. this.hooks.contentHash.call(chunk);
  4260. }
  4261. } catch (err) {
  4262. this.errors.push(
  4263. new ChunkRenderError(chunk, "", /** @type {Error} */ (err))
  4264. );
  4265. }
  4266. this.logger.timeAggregate("hashing: hash chunks");
  4267. };
  4268. for (const chunk of asyncChunks) processChunk(chunk);
  4269. for (const chunk of runtimeChunks) processChunk(chunk);
  4270. for (const chunk of initialChunks) processChunk(chunk);
  4271. if (errors.length > 0) {
  4272. errors.sort(compareSelect(err => err.module, compareModulesByIdentifier));
  4273. for (const error of errors) {
  4274. this.errors.push(error);
  4275. }
  4276. }
  4277. this.logger.timeAggregateEnd("hashing: hash runtime modules");
  4278. this.logger.timeAggregateEnd("hashing: hash chunks");
  4279. this.logger.time("hashing: hash digest");
  4280. this.hooks.fullHash.call(hash);
  4281. this.fullHash = /** @type {string} */ (hash.digest(hashDigest));
  4282. this.hash = this.fullHash.slice(0, hashDigestLength);
  4283. this.logger.timeEnd("hashing: hash digest");
  4284. this.logger.time("hashing: process full hash modules");
  4285. for (const chunk of fullHashChunks) {
  4286. for (const module of /** @type {Iterable<RuntimeModule>} */ (
  4287. chunkGraph.getChunkFullHashModulesIterable(chunk)
  4288. )) {
  4289. const moduleHash = createHash(
  4290. /** @type {HashFunction} */ (hashFunction)
  4291. );
  4292. module.updateHash(moduleHash, {
  4293. chunkGraph,
  4294. runtime: chunk.runtime,
  4295. runtimeTemplate
  4296. });
  4297. const moduleHashDigest = /** @type {string} */ (
  4298. moduleHash.digest(hashDigest)
  4299. );
  4300. const oldHash = chunkGraph.getModuleHash(module, chunk.runtime);
  4301. chunkGraph.setModuleHashes(
  4302. module,
  4303. chunk.runtime,
  4304. moduleHashDigest,
  4305. moduleHashDigest.slice(0, hashDigestLength)
  4306. );
  4307. /** @type {CodeGenerationJob} */
  4308. (
  4309. /** @type {Map<Module, CodeGenerationJob>} */
  4310. (codeGenerationJobsMap.get(oldHash)).get(module)
  4311. ).hash = moduleHashDigest;
  4312. }
  4313. const chunkHash = createHash(/** @type {HashFunction} */ (hashFunction));
  4314. chunkHash.update(chunk.hash);
  4315. chunkHash.update(this.hash);
  4316. const chunkHashDigest =
  4317. /** @type {string} */
  4318. (chunkHash.digest(hashDigest));
  4319. chunk.hash = chunkHashDigest;
  4320. chunk.renderedHash = chunk.hash.slice(0, hashDigestLength);
  4321. this.hooks.contentHash.call(chunk);
  4322. }
  4323. this.logger.timeEnd("hashing: process full hash modules");
  4324. return codeGenerationJobs;
  4325. }
  4326. /**
  4327. * @param {string} file file name
  4328. * @param {Source} source asset source
  4329. * @param {AssetInfo} assetInfo extra asset information
  4330. * @returns {void}
  4331. */
  4332. emitAsset(file, source, assetInfo = {}) {
  4333. if (this.assets[file]) {
  4334. if (!isSourceEqual(this.assets[file], source)) {
  4335. this.errors.push(
  4336. new WebpackError(
  4337. `Conflict: Multiple assets emit different content to the same filename ${file}${
  4338. assetInfo.sourceFilename
  4339. ? `. Original source ${assetInfo.sourceFilename}`
  4340. : ""
  4341. }`
  4342. )
  4343. );
  4344. this.assets[file] = source;
  4345. this._setAssetInfo(file, assetInfo);
  4346. return;
  4347. }
  4348. const oldInfo = this.assetsInfo.get(file);
  4349. const newInfo = { ...oldInfo, ...assetInfo };
  4350. this._setAssetInfo(file, newInfo, oldInfo);
  4351. return;
  4352. }
  4353. this.assets[file] = source;
  4354. this._setAssetInfo(file, assetInfo, undefined);
  4355. }
  4356. /**
  4357. * @private
  4358. * @param {string} file file name
  4359. * @param {AssetInfo=} newInfo new asset information
  4360. * @param {AssetInfo=} oldInfo old asset information
  4361. */
  4362. _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) {
  4363. if (newInfo === undefined) {
  4364. this.assetsInfo.delete(file);
  4365. } else {
  4366. this.assetsInfo.set(file, newInfo);
  4367. }
  4368. const oldRelated = oldInfo && oldInfo.related;
  4369. const newRelated = newInfo && newInfo.related;
  4370. if (oldRelated) {
  4371. for (const key of Object.keys(oldRelated)) {
  4372. /**
  4373. * @param {string} name name
  4374. */
  4375. const remove = name => {
  4376. const relatedIn = this._assetsRelatedIn.get(name);
  4377. if (relatedIn === undefined) return;
  4378. const entry = relatedIn.get(key);
  4379. if (entry === undefined) return;
  4380. entry.delete(file);
  4381. if (entry.size !== 0) return;
  4382. relatedIn.delete(key);
  4383. if (relatedIn.size === 0) this._assetsRelatedIn.delete(name);
  4384. };
  4385. const entry = oldRelated[key];
  4386. if (Array.isArray(entry)) {
  4387. for (const name of entry) {
  4388. remove(name);
  4389. }
  4390. } else if (entry) {
  4391. remove(entry);
  4392. }
  4393. }
  4394. }
  4395. if (newRelated) {
  4396. for (const key of Object.keys(newRelated)) {
  4397. /**
  4398. * @param {string} name name
  4399. */
  4400. const add = name => {
  4401. let relatedIn = this._assetsRelatedIn.get(name);
  4402. if (relatedIn === undefined) {
  4403. this._assetsRelatedIn.set(name, (relatedIn = new Map()));
  4404. }
  4405. let entry = relatedIn.get(key);
  4406. if (entry === undefined) {
  4407. relatedIn.set(key, (entry = new Set()));
  4408. }
  4409. entry.add(file);
  4410. };
  4411. const entry = newRelated[key];
  4412. if (Array.isArray(entry)) {
  4413. for (const name of entry) {
  4414. add(name);
  4415. }
  4416. } else if (entry) {
  4417. add(entry);
  4418. }
  4419. }
  4420. }
  4421. }
  4422. /**
  4423. * @param {string} file file name
  4424. * @param {Source | ((source: Source) => Source)} newSourceOrFunction new asset source or function converting old to new
  4425. * @param {(AssetInfo | ((assetInfo?: AssetInfo) => AssetInfo | undefined)) | undefined} assetInfoUpdateOrFunction new asset info or function converting old to new
  4426. */
  4427. updateAsset(
  4428. file,
  4429. newSourceOrFunction,
  4430. assetInfoUpdateOrFunction = undefined
  4431. ) {
  4432. if (!this.assets[file]) {
  4433. throw new Error(
  4434. `Called Compilation.updateAsset for not existing filename ${file}`
  4435. );
  4436. }
  4437. this.assets[file] =
  4438. typeof newSourceOrFunction === "function"
  4439. ? newSourceOrFunction(this.assets[file])
  4440. : newSourceOrFunction;
  4441. if (assetInfoUpdateOrFunction !== undefined) {
  4442. const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO;
  4443. if (typeof assetInfoUpdateOrFunction === "function") {
  4444. this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo);
  4445. } else {
  4446. this._setAssetInfo(
  4447. file,
  4448. cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction),
  4449. oldInfo
  4450. );
  4451. }
  4452. }
  4453. }
  4454. /**
  4455. * @param {string} file file name
  4456. * @param {string} newFile the new name of file
  4457. */
  4458. renameAsset(file, newFile) {
  4459. const source = this.assets[file];
  4460. if (!source) {
  4461. throw new Error(
  4462. `Called Compilation.renameAsset for not existing filename ${file}`
  4463. );
  4464. }
  4465. if (this.assets[newFile] && !isSourceEqual(this.assets[file], source)) {
  4466. this.errors.push(
  4467. new WebpackError(
  4468. `Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content`
  4469. )
  4470. );
  4471. }
  4472. const assetInfo = this.assetsInfo.get(file);
  4473. // Update related in all other assets
  4474. const relatedInInfo = this._assetsRelatedIn.get(file);
  4475. if (relatedInInfo) {
  4476. for (const [key, assets] of relatedInInfo) {
  4477. for (const name of assets) {
  4478. const info = this.assetsInfo.get(name);
  4479. if (!info) continue;
  4480. const related = info.related;
  4481. if (!related) continue;
  4482. const entry = related[key];
  4483. let newEntry;
  4484. if (Array.isArray(entry)) {
  4485. newEntry = entry.map(x => (x === file ? newFile : x));
  4486. } else if (entry === file) {
  4487. newEntry = newFile;
  4488. } else {
  4489. continue;
  4490. }
  4491. this.assetsInfo.set(name, {
  4492. ...info,
  4493. related: {
  4494. ...related,
  4495. [key]: newEntry
  4496. }
  4497. });
  4498. }
  4499. }
  4500. }
  4501. this._setAssetInfo(file, undefined, assetInfo);
  4502. this._setAssetInfo(newFile, assetInfo);
  4503. delete this.assets[file];
  4504. this.assets[newFile] = source;
  4505. for (const chunk of this.chunks) {
  4506. {
  4507. const size = chunk.files.size;
  4508. chunk.files.delete(file);
  4509. if (size !== chunk.files.size) {
  4510. chunk.files.add(newFile);
  4511. }
  4512. }
  4513. {
  4514. const size = chunk.auxiliaryFiles.size;
  4515. chunk.auxiliaryFiles.delete(file);
  4516. if (size !== chunk.auxiliaryFiles.size) {
  4517. chunk.auxiliaryFiles.add(newFile);
  4518. }
  4519. }
  4520. }
  4521. }
  4522. /**
  4523. * @param {string} file file name
  4524. */
  4525. deleteAsset(file) {
  4526. if (!this.assets[file]) {
  4527. return;
  4528. }
  4529. delete this.assets[file];
  4530. const assetInfo = this.assetsInfo.get(file);
  4531. this._setAssetInfo(file, undefined, assetInfo);
  4532. const related = assetInfo && assetInfo.related;
  4533. if (related) {
  4534. for (const key of Object.keys(related)) {
  4535. /**
  4536. * @param {string} file file
  4537. */
  4538. const checkUsedAndDelete = file => {
  4539. if (!this._assetsRelatedIn.has(file)) {
  4540. this.deleteAsset(file);
  4541. }
  4542. };
  4543. const items = related[key];
  4544. if (Array.isArray(items)) {
  4545. for (const file of items) {
  4546. checkUsedAndDelete(file);
  4547. }
  4548. } else if (items) {
  4549. checkUsedAndDelete(items);
  4550. }
  4551. }
  4552. }
  4553. // TODO If this becomes a performance problem
  4554. // store a reverse mapping from asset to chunk
  4555. for (const chunk of this.chunks) {
  4556. chunk.files.delete(file);
  4557. chunk.auxiliaryFiles.delete(file);
  4558. }
  4559. }
  4560. getAssets() {
  4561. /** @type {Readonly<Asset>[]} */
  4562. const array = [];
  4563. for (const assetName of Object.keys(this.assets)) {
  4564. if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) {
  4565. array.push({
  4566. name: assetName,
  4567. source: this.assets[assetName],
  4568. info: this.assetsInfo.get(assetName) || EMPTY_ASSET_INFO
  4569. });
  4570. }
  4571. }
  4572. return array;
  4573. }
  4574. /**
  4575. * @param {string} name the name of the asset
  4576. * @returns {Readonly<Asset> | undefined} the asset or undefined when not found
  4577. */
  4578. getAsset(name) {
  4579. if (!Object.prototype.hasOwnProperty.call(this.assets, name)) return;
  4580. return {
  4581. name,
  4582. source: this.assets[name],
  4583. info: this.assetsInfo.get(name) || EMPTY_ASSET_INFO
  4584. };
  4585. }
  4586. clearAssets() {
  4587. for (const chunk of this.chunks) {
  4588. chunk.files.clear();
  4589. chunk.auxiliaryFiles.clear();
  4590. }
  4591. }
  4592. createModuleAssets() {
  4593. const { chunkGraph } = this;
  4594. for (const module of this.modules) {
  4595. const buildInfo = /** @type {BuildInfo} */ (module.buildInfo);
  4596. if (buildInfo.assets) {
  4597. const assetsInfo = buildInfo.assetsInfo;
  4598. for (const assetName of Object.keys(buildInfo.assets)) {
  4599. const fileName = this.getPath(assetName, {
  4600. chunkGraph: this.chunkGraph,
  4601. module
  4602. });
  4603. for (const chunk of chunkGraph.getModuleChunksIterable(module)) {
  4604. chunk.auxiliaryFiles.add(fileName);
  4605. }
  4606. this.emitAsset(
  4607. fileName,
  4608. buildInfo.assets[assetName],
  4609. assetsInfo ? assetsInfo.get(assetName) : undefined
  4610. );
  4611. this.hooks.moduleAsset.call(module, fileName);
  4612. }
  4613. }
  4614. }
  4615. }
  4616. /**
  4617. * @param {RenderManifestOptions} options options object
  4618. * @returns {RenderManifestEntry[]} manifest entries
  4619. */
  4620. getRenderManifest(options) {
  4621. return this.hooks.renderManifest.call([], options);
  4622. }
  4623. /**
  4624. * @param {Callback} callback signals when the call finishes
  4625. * @returns {void}
  4626. */
  4627. createChunkAssets(callback) {
  4628. const outputOptions = this.outputOptions;
  4629. const cachedSourceMap = new WeakMap();
  4630. /** @type {Map<string, {hash: string, source: Source, chunk: Chunk}>} */
  4631. const alreadyWrittenFiles = new Map();
  4632. asyncLib.forEachLimit(
  4633. this.chunks,
  4634. 15,
  4635. (chunk, callback) => {
  4636. /** @type {RenderManifestEntry[]} */
  4637. let manifest;
  4638. try {
  4639. manifest = this.getRenderManifest({
  4640. chunk,
  4641. hash: /** @type {string} */ (this.hash),
  4642. fullHash: /** @type {string} */ (this.fullHash),
  4643. outputOptions,
  4644. codeGenerationResults: this.codeGenerationResults,
  4645. moduleTemplates: this.moduleTemplates,
  4646. dependencyTemplates: this.dependencyTemplates,
  4647. chunkGraph: this.chunkGraph,
  4648. moduleGraph: this.moduleGraph,
  4649. runtimeTemplate: this.runtimeTemplate
  4650. });
  4651. } catch (err) {
  4652. this.errors.push(
  4653. new ChunkRenderError(chunk, "", /** @type {Error} */ (err))
  4654. );
  4655. return callback();
  4656. }
  4657. asyncLib.each(
  4658. manifest,
  4659. (fileManifest, callback) => {
  4660. const ident = fileManifest.identifier;
  4661. const usedHash = /** @type {string} */ (fileManifest.hash);
  4662. const assetCacheItem = this._assetsCache.getItemCache(
  4663. ident,
  4664. usedHash
  4665. );
  4666. assetCacheItem.get((err, sourceFromCache) => {
  4667. /** @type {TemplatePath} */
  4668. let filenameTemplate;
  4669. /** @type {string} */
  4670. let file;
  4671. /** @type {AssetInfo} */
  4672. let assetInfo;
  4673. let inTry = true;
  4674. /**
  4675. * @param {Error} err error
  4676. * @returns {void}
  4677. */
  4678. const errorAndCallback = err => {
  4679. const filename =
  4680. file ||
  4681. (typeof file === "string"
  4682. ? file
  4683. : typeof filenameTemplate === "string"
  4684. ? filenameTemplate
  4685. : "");
  4686. this.errors.push(new ChunkRenderError(chunk, filename, err));
  4687. inTry = false;
  4688. return callback();
  4689. };
  4690. try {
  4691. if ("filename" in fileManifest) {
  4692. file = fileManifest.filename;
  4693. assetInfo = fileManifest.info;
  4694. } else {
  4695. filenameTemplate = fileManifest.filenameTemplate;
  4696. const pathAndInfo = this.getPathWithInfo(
  4697. filenameTemplate,
  4698. fileManifest.pathOptions
  4699. );
  4700. file = pathAndInfo.path;
  4701. assetInfo = fileManifest.info
  4702. ? {
  4703. ...pathAndInfo.info,
  4704. ...fileManifest.info
  4705. }
  4706. : pathAndInfo.info;
  4707. }
  4708. if (err) {
  4709. return errorAndCallback(err);
  4710. }
  4711. let source = sourceFromCache;
  4712. // check if the same filename was already written by another chunk
  4713. const alreadyWritten = alreadyWrittenFiles.get(file);
  4714. if (alreadyWritten !== undefined) {
  4715. if (alreadyWritten.hash !== usedHash) {
  4716. inTry = false;
  4717. return callback(
  4718. new WebpackError(
  4719. `Conflict: Multiple chunks emit assets to the same filename ${file}` +
  4720. ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})`
  4721. )
  4722. );
  4723. }
  4724. source = alreadyWritten.source;
  4725. } else if (!source) {
  4726. // render the asset
  4727. source = fileManifest.render();
  4728. // Ensure that source is a cached source to avoid additional cost because of repeated access
  4729. if (!(source instanceof CachedSource)) {
  4730. const cacheEntry = cachedSourceMap.get(source);
  4731. if (cacheEntry) {
  4732. source = cacheEntry;
  4733. } else {
  4734. const cachedSource = new CachedSource(source);
  4735. cachedSourceMap.set(source, cachedSource);
  4736. source = cachedSource;
  4737. }
  4738. }
  4739. }
  4740. this.emitAsset(file, source, assetInfo);
  4741. if (fileManifest.auxiliary) {
  4742. chunk.auxiliaryFiles.add(file);
  4743. } else {
  4744. chunk.files.add(file);
  4745. }
  4746. this.hooks.chunkAsset.call(chunk, file);
  4747. alreadyWrittenFiles.set(file, {
  4748. hash: usedHash,
  4749. source,
  4750. chunk
  4751. });
  4752. if (source !== sourceFromCache) {
  4753. assetCacheItem.store(source, err => {
  4754. if (err) return errorAndCallback(err);
  4755. inTry = false;
  4756. return callback();
  4757. });
  4758. } else {
  4759. inTry = false;
  4760. callback();
  4761. }
  4762. } catch (err) {
  4763. if (!inTry) throw err;
  4764. errorAndCallback(/** @type {Error} */ (err));
  4765. }
  4766. });
  4767. },
  4768. callback
  4769. );
  4770. },
  4771. callback
  4772. );
  4773. }
  4774. /**
  4775. * @param {TemplatePath} filename used to get asset path with hash
  4776. * @param {PathData} data context data
  4777. * @returns {string} interpolated path
  4778. */
  4779. getPath(filename, data = {}) {
  4780. if (!data.hash) {
  4781. data = {
  4782. hash: this.hash,
  4783. ...data
  4784. };
  4785. }
  4786. return this.getAssetPath(filename, data);
  4787. }
  4788. /**
  4789. * @param {TemplatePath} filename used to get asset path with hash
  4790. * @param {PathData} data context data
  4791. * @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info
  4792. */
  4793. getPathWithInfo(filename, data = {}) {
  4794. if (!data.hash) {
  4795. data = {
  4796. hash: this.hash,
  4797. ...data
  4798. };
  4799. }
  4800. return this.getAssetPathWithInfo(filename, data);
  4801. }
  4802. /**
  4803. * @param {TemplatePath} filename used to get asset path with hash
  4804. * @param {PathData} data context data
  4805. * @returns {string} interpolated path
  4806. */
  4807. getAssetPath(filename, data) {
  4808. return this.hooks.assetPath.call(
  4809. typeof filename === "function" ? filename(data) : filename,
  4810. data,
  4811. undefined
  4812. );
  4813. }
  4814. /**
  4815. * @param {TemplatePath} filename used to get asset path with hash
  4816. * @param {PathData} data context data
  4817. * @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info
  4818. */
  4819. getAssetPathWithInfo(filename, data) {
  4820. const assetInfo = {};
  4821. // TODO webpack 5: refactor assetPath hook to receive { path, info } object
  4822. const newPath = this.hooks.assetPath.call(
  4823. typeof filename === "function" ? filename(data, assetInfo) : filename,
  4824. data,
  4825. assetInfo
  4826. );
  4827. return { path: newPath, info: assetInfo };
  4828. }
  4829. getWarnings() {
  4830. return this.hooks.processWarnings.call(this.warnings);
  4831. }
  4832. getErrors() {
  4833. return this.hooks.processErrors.call(this.errors);
  4834. }
  4835. /**
  4836. * This function allows you to run another instance of webpack inside of webpack however as
  4837. * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins
  4838. * from parent (or top level compiler) and creates a child Compilation
  4839. * @param {string} name name of the child compiler
  4840. * @param {Partial<OutputOptions>=} outputOptions // Need to convert config schema to types for this
  4841. * @param {Array<WebpackPluginInstance | WebpackPluginFunction>=} plugins webpack plugins that will be applied
  4842. * @returns {Compiler} creates a child Compiler instance
  4843. */
  4844. createChildCompiler(name, outputOptions, plugins) {
  4845. const idx = this.childrenCounters[name] || 0;
  4846. this.childrenCounters[name] = idx + 1;
  4847. return this.compiler.createChildCompiler(
  4848. this,
  4849. name,
  4850. idx,
  4851. outputOptions,
  4852. plugins
  4853. );
  4854. }
  4855. /**
  4856. * @param {Module} module the module
  4857. * @param {ExecuteModuleOptions} options options
  4858. * @param {ExecuteModuleCallback} callback callback
  4859. */
  4860. executeModule(module, options, callback) {
  4861. // Aggregate all referenced modules and ensure they are ready
  4862. const modules = new Set([module]);
  4863. processAsyncTree(
  4864. modules,
  4865. 10,
  4866. (module, push, callback) => {
  4867. this.buildQueue.waitFor(module, err => {
  4868. if (err) return callback(err);
  4869. this.processDependenciesQueue.waitFor(module, err => {
  4870. if (err) return callback(err);
  4871. for (const { module: m } of this.moduleGraph.getOutgoingConnections(
  4872. module
  4873. )) {
  4874. const size = modules.size;
  4875. modules.add(m);
  4876. if (modules.size !== size) push(m);
  4877. }
  4878. callback();
  4879. });
  4880. });
  4881. },
  4882. err => {
  4883. if (err) return callback(/** @type {WebpackError} */ (err));
  4884. // Create new chunk graph, chunk and entrypoint for the build time execution
  4885. const chunkGraph = new ChunkGraph(
  4886. this.moduleGraph,
  4887. this.outputOptions.hashFunction
  4888. );
  4889. const runtime = "build time";
  4890. const { hashFunction, hashDigest, hashDigestLength } =
  4891. this.outputOptions;
  4892. const runtimeTemplate = this.runtimeTemplate;
  4893. const chunk = new Chunk("build time chunk", this._backCompat);
  4894. chunk.id = /** @type {ChunkId} */ (chunk.name);
  4895. chunk.ids = [chunk.id];
  4896. chunk.runtime = runtime;
  4897. const entrypoint = new Entrypoint({
  4898. runtime,
  4899. chunkLoading: false,
  4900. ...options.entryOptions
  4901. });
  4902. chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint);
  4903. connectChunkGroupAndChunk(entrypoint, chunk);
  4904. entrypoint.setRuntimeChunk(chunk);
  4905. entrypoint.setEntrypointChunk(chunk);
  4906. const chunks = new Set([chunk]);
  4907. // Assign ids to modules and modules to the chunk
  4908. for (const module of modules) {
  4909. const id = module.identifier();
  4910. chunkGraph.setModuleId(module, id);
  4911. chunkGraph.connectChunkAndModule(chunk, module);
  4912. }
  4913. /** @type {WebpackError[]} */
  4914. const errors = [];
  4915. // Hash modules
  4916. for (const module of modules) {
  4917. this._createModuleHash(
  4918. module,
  4919. chunkGraph,
  4920. runtime,
  4921. hashFunction,
  4922. runtimeTemplate,
  4923. hashDigest,
  4924. hashDigestLength,
  4925. errors
  4926. );
  4927. }
  4928. const codeGenerationResults = new CodeGenerationResults(
  4929. this.outputOptions.hashFunction
  4930. );
  4931. /**
  4932. * @param {Module} module the module
  4933. * @param {Callback} callback callback
  4934. * @returns {void}
  4935. */
  4936. const codeGen = (module, callback) => {
  4937. this._codeGenerationModule(
  4938. module,
  4939. runtime,
  4940. [runtime],
  4941. chunkGraph.getModuleHash(module, runtime),
  4942. this.dependencyTemplates,
  4943. chunkGraph,
  4944. this.moduleGraph,
  4945. runtimeTemplate,
  4946. errors,
  4947. codeGenerationResults,
  4948. (err, _codeGenerated) => {
  4949. callback(err);
  4950. }
  4951. );
  4952. };
  4953. const reportErrors = () => {
  4954. if (errors.length > 0) {
  4955. errors.sort(
  4956. compareSelect(err => err.module, compareModulesByIdentifier)
  4957. );
  4958. for (const error of errors) {
  4959. this.errors.push(error);
  4960. }
  4961. errors.length = 0;
  4962. }
  4963. };
  4964. // Generate code for all aggregated modules
  4965. asyncLib.eachLimit(modules, 10, codeGen, err => {
  4966. if (err) return callback(err);
  4967. reportErrors();
  4968. // for backward-compat temporary set the chunk graph
  4969. // TODO webpack 6
  4970. const old = this.chunkGraph;
  4971. this.chunkGraph = chunkGraph;
  4972. this.processRuntimeRequirements({
  4973. chunkGraph,
  4974. modules,
  4975. chunks,
  4976. codeGenerationResults,
  4977. chunkGraphEntries: chunks
  4978. });
  4979. this.chunkGraph = old;
  4980. const runtimeModules =
  4981. chunkGraph.getChunkRuntimeModulesIterable(chunk);
  4982. // Hash runtime modules
  4983. for (const module of runtimeModules) {
  4984. modules.add(module);
  4985. this._createModuleHash(
  4986. module,
  4987. chunkGraph,
  4988. runtime,
  4989. hashFunction,
  4990. runtimeTemplate,
  4991. hashDigest,
  4992. hashDigestLength,
  4993. errors
  4994. );
  4995. }
  4996. // Generate code for all runtime modules
  4997. asyncLib.eachLimit(runtimeModules, 10, codeGen, err => {
  4998. if (err) return callback(err);
  4999. reportErrors();
  5000. /** @type {Map<Module, ExecuteModuleArgument>} */
  5001. const moduleArgumentsMap = new Map();
  5002. /** @type {Map<string, ExecuteModuleArgument>} */
  5003. const moduleArgumentsById = new Map();
  5004. /** @type {ExecuteModuleResult["fileDependencies"]} */
  5005. const fileDependencies = new LazySet();
  5006. /** @type {ExecuteModuleResult["contextDependencies"]} */
  5007. const contextDependencies = new LazySet();
  5008. /** @type {ExecuteModuleResult["missingDependencies"]} */
  5009. const missingDependencies = new LazySet();
  5010. /** @type {ExecuteModuleResult["buildDependencies"]} */
  5011. const buildDependencies = new LazySet();
  5012. /** @type {ExecuteModuleResult["assets"]} */
  5013. const assets = new Map();
  5014. let cacheable = true;
  5015. /** @type {ExecuteModuleContext} */
  5016. const context = {
  5017. assets,
  5018. __webpack_require__: undefined,
  5019. chunk,
  5020. chunkGraph
  5021. };
  5022. // Prepare execution
  5023. asyncLib.eachLimit(
  5024. modules,
  5025. 10,
  5026. (module, callback) => {
  5027. const codeGenerationResult = codeGenerationResults.get(
  5028. module,
  5029. runtime
  5030. );
  5031. /** @type {ExecuteModuleArgument} */
  5032. const moduleArgument = {
  5033. module,
  5034. codeGenerationResult,
  5035. preparedInfo: undefined,
  5036. moduleObject: undefined
  5037. };
  5038. moduleArgumentsMap.set(module, moduleArgument);
  5039. moduleArgumentsById.set(module.identifier(), moduleArgument);
  5040. module.addCacheDependencies(
  5041. fileDependencies,
  5042. contextDependencies,
  5043. missingDependencies,
  5044. buildDependencies
  5045. );
  5046. if (
  5047. /** @type {BuildInfo} */ (module.buildInfo).cacheable ===
  5048. false
  5049. ) {
  5050. cacheable = false;
  5051. }
  5052. if (module.buildInfo && module.buildInfo.assets) {
  5053. const { assets: moduleAssets, assetsInfo } = module.buildInfo;
  5054. for (const assetName of Object.keys(moduleAssets)) {
  5055. assets.set(assetName, {
  5056. source: moduleAssets[assetName],
  5057. info: assetsInfo ? assetsInfo.get(assetName) : undefined
  5058. });
  5059. }
  5060. }
  5061. this.hooks.prepareModuleExecution.callAsync(
  5062. moduleArgument,
  5063. context,
  5064. callback
  5065. );
  5066. },
  5067. err => {
  5068. if (err) return callback(err);
  5069. /** @type {ExecuteModuleExports | undefined} */
  5070. let exports;
  5071. try {
  5072. const {
  5073. strictModuleErrorHandling,
  5074. strictModuleExceptionHandling
  5075. } = this.outputOptions;
  5076. /** @type {WebpackRequire} */
  5077. const __webpack_require__ = id => {
  5078. const cached = moduleCache[id];
  5079. if (cached !== undefined) {
  5080. if (cached.error) throw cached.error;
  5081. return cached.exports;
  5082. }
  5083. const moduleArgument = moduleArgumentsById.get(id);
  5084. return __webpack_require_module__(
  5085. /** @type {ExecuteModuleArgument} */
  5086. (moduleArgument),
  5087. id
  5088. );
  5089. };
  5090. const interceptModuleExecution = (__webpack_require__[
  5091. /** @type {"i"} */
  5092. (
  5093. RuntimeGlobals.interceptModuleExecution.replace(
  5094. `${RuntimeGlobals.require}.`,
  5095. ""
  5096. )
  5097. )
  5098. ] = /** @type {NonNullable<WebpackRequire["i"]>} */ ([]));
  5099. const moduleCache = (__webpack_require__[
  5100. /** @type {"c"} */ (
  5101. RuntimeGlobals.moduleCache.replace(
  5102. `${RuntimeGlobals.require}.`,
  5103. ""
  5104. )
  5105. )
  5106. ] = /** @type {NonNullable<WebpackRequire["c"]>} */ ({}));
  5107. context.__webpack_require__ = __webpack_require__;
  5108. /**
  5109. * @param {ExecuteModuleArgument} moduleArgument the module argument
  5110. * @param {string=} id id
  5111. * @returns {ExecuteModuleExports} exports
  5112. */
  5113. const __webpack_require_module__ = (moduleArgument, id) => {
  5114. /** @type {ExecuteOptions} */
  5115. const execOptions = {
  5116. id,
  5117. module: {
  5118. id,
  5119. exports: {},
  5120. loaded: false,
  5121. error: undefined
  5122. },
  5123. require: __webpack_require__
  5124. };
  5125. for (const handler of interceptModuleExecution) {
  5126. handler(execOptions);
  5127. }
  5128. const module = moduleArgument.module;
  5129. this.buildTimeExecutedModules.add(module);
  5130. const moduleObject = execOptions.module;
  5131. moduleArgument.moduleObject = moduleObject;
  5132. try {
  5133. if (id) moduleCache[id] = moduleObject;
  5134. tryRunOrWebpackError(
  5135. () =>
  5136. this.hooks.executeModule.call(
  5137. moduleArgument,
  5138. context
  5139. ),
  5140. "Compilation.hooks.executeModule"
  5141. );
  5142. moduleObject.loaded = true;
  5143. return moduleObject.exports;
  5144. } catch (execErr) {
  5145. if (strictModuleExceptionHandling) {
  5146. if (id) delete moduleCache[id];
  5147. } else if (strictModuleErrorHandling) {
  5148. moduleObject.error =
  5149. /** @type {WebpackError} */
  5150. (execErr);
  5151. }
  5152. if (!(/** @type {WebpackError} */ (execErr).module)) {
  5153. /** @type {WebpackError} */
  5154. (execErr).module = module;
  5155. }
  5156. throw execErr;
  5157. }
  5158. };
  5159. for (const runtimeModule of chunkGraph.getChunkRuntimeModulesInOrder(
  5160. chunk
  5161. )) {
  5162. __webpack_require_module__(
  5163. /** @type {ExecuteModuleArgument} */
  5164. (moduleArgumentsMap.get(runtimeModule))
  5165. );
  5166. }
  5167. exports = __webpack_require__(module.identifier());
  5168. } catch (execErr) {
  5169. const { message, stack, module } =
  5170. /** @type {WebpackError} */
  5171. (execErr);
  5172. const err = new WebpackError(
  5173. `Execution of module code from module graph (${
  5174. /** @type {Module} */
  5175. (module).readableIdentifier(this.requestShortener)
  5176. }) failed: ${message}`,
  5177. { cause: execErr }
  5178. );
  5179. err.stack = stack;
  5180. err.module = module;
  5181. return callback(err);
  5182. }
  5183. callback(null, {
  5184. exports,
  5185. assets,
  5186. cacheable,
  5187. fileDependencies,
  5188. contextDependencies,
  5189. missingDependencies,
  5190. buildDependencies
  5191. });
  5192. }
  5193. );
  5194. });
  5195. });
  5196. }
  5197. );
  5198. }
  5199. checkConstraints() {
  5200. const chunkGraph = this.chunkGraph;
  5201. /** @type {Set<number|string>} */
  5202. const usedIds = new Set();
  5203. for (const module of this.modules) {
  5204. if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) continue;
  5205. const moduleId = chunkGraph.getModuleId(module);
  5206. if (moduleId === null) continue;
  5207. if (usedIds.has(moduleId)) {
  5208. throw new Error(`checkConstraints: duplicate module id ${moduleId}`);
  5209. }
  5210. usedIds.add(moduleId);
  5211. }
  5212. for (const chunk of this.chunks) {
  5213. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  5214. if (!this.modules.has(module)) {
  5215. throw new Error(
  5216. "checkConstraints: module in chunk but not in compilation " +
  5217. ` ${chunk.debugId} ${module.debugId}`
  5218. );
  5219. }
  5220. }
  5221. for (const module of chunkGraph.getChunkEntryModulesIterable(chunk)) {
  5222. if (!this.modules.has(module)) {
  5223. throw new Error(
  5224. "checkConstraints: entry module in chunk but not in compilation " +
  5225. ` ${chunk.debugId} ${module.debugId}`
  5226. );
  5227. }
  5228. }
  5229. }
  5230. for (const chunkGroup of this.chunkGroups) {
  5231. chunkGroup.checkConstraints();
  5232. }
  5233. }
  5234. }
  5235. /**
  5236. * @typedef {object} FactorizeModuleOptions
  5237. * @property {ModuleProfile=} currentProfile
  5238. * @property {ModuleFactory} factory
  5239. * @property {Dependency[]} dependencies
  5240. * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module
  5241. * @property {Module | null} originModule
  5242. * @property {Partial<ModuleFactoryCreateDataContextInfo>=} contextInfo
  5243. * @property {string=} context
  5244. */
  5245. /**
  5246. * @param {FactorizeModuleOptions} options options object
  5247. * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback
  5248. * @returns {void}
  5249. */
  5250. // Workaround for typescript as it doesn't support function overloading in jsdoc within a class
  5251. /* eslint-disable jsdoc/require-asterisk-prefix */
  5252. Compilation.prototype.factorizeModule = /**
  5253. @type {{
  5254. (options: FactorizeModuleOptions & { factoryResult?: false }, callback: ModuleCallback): void;
  5255. (options: FactorizeModuleOptions & { factoryResult: true }, callback: ModuleFactoryResultCallback): void;
  5256. }} */ (
  5257. function factorizeModule(options, callback) {
  5258. this.factorizeQueue.add(options, /** @type {TODO} */ (callback));
  5259. }
  5260. );
  5261. /* eslint-enable jsdoc/require-asterisk-prefix */
  5262. // Hide from typescript
  5263. const compilationPrototype = Compilation.prototype;
  5264. // TODO webpack 6 remove
  5265. Object.defineProperty(compilationPrototype, "modifyHash", {
  5266. writable: false,
  5267. enumerable: false,
  5268. configurable: false,
  5269. value: () => {
  5270. throw new Error(
  5271. "Compilation.modifyHash was removed in favor of Compilation.hooks.fullHash"
  5272. );
  5273. }
  5274. });
  5275. // TODO webpack 6 remove
  5276. Object.defineProperty(compilationPrototype, "cache", {
  5277. enumerable: false,
  5278. configurable: false,
  5279. get: util.deprecate(
  5280. /**
  5281. * @this {Compilation} the compilation
  5282. * @returns {Cache} the cache
  5283. */
  5284. function cache() {
  5285. return this.compiler.cache;
  5286. },
  5287. "Compilation.cache was removed in favor of Compilation.getCache()",
  5288. "DEP_WEBPACK_COMPILATION_CACHE"
  5289. ),
  5290. set: util.deprecate(
  5291. /**
  5292. * @param {EXPECTED_ANY} _v value
  5293. */
  5294. _v => {},
  5295. "Compilation.cache was removed in favor of Compilation.getCache()",
  5296. "DEP_WEBPACK_COMPILATION_CACHE"
  5297. )
  5298. });
  5299. /**
  5300. * Add additional assets to the compilation.
  5301. */
  5302. Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL = -2000;
  5303. /**
  5304. * Basic preprocessing of assets.
  5305. */
  5306. Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS = -1000;
  5307. /**
  5308. * Derive new assets from existing assets.
  5309. * Existing assets should not be treated as complete.
  5310. */
  5311. Compilation.PROCESS_ASSETS_STAGE_DERIVED = -200;
  5312. /**
  5313. * Add additional sections to existing assets, like a banner or initialization code.
  5314. */
  5315. Compilation.PROCESS_ASSETS_STAGE_ADDITIONS = -100;
  5316. /**
  5317. * Optimize existing assets in a general way.
  5318. */
  5319. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE = 100;
  5320. /**
  5321. * Optimize the count of existing assets, e. g. by merging them.
  5322. * Only assets of the same type should be merged.
  5323. * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE.
  5324. */
  5325. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT = 200;
  5326. /**
  5327. * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes.
  5328. */
  5329. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY = 300;
  5330. /**
  5331. * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace.
  5332. */
  5333. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE = 400;
  5334. /**
  5335. * Add development tooling to assets, e. g. by extracting a SourceMap.
  5336. */
  5337. Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING = 500;
  5338. /**
  5339. * Optimize the count of existing assets, e. g. by inlining assets of into other assets.
  5340. * Only assets of different types should be inlined.
  5341. * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT.
  5342. */
  5343. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE = 700;
  5344. /**
  5345. * Summarize the list of existing assets
  5346. * e. g. creating an assets manifest of Service Workers.
  5347. */
  5348. Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE = 1000;
  5349. /**
  5350. * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content.
  5351. */
  5352. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH = 2500;
  5353. /**
  5354. * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset.
  5355. */
  5356. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER = 3000;
  5357. /**
  5358. * Analyse existing assets.
  5359. */
  5360. Compilation.PROCESS_ASSETS_STAGE_ANALYSE = 4000;
  5361. /**
  5362. * Creating assets for reporting purposes.
  5363. */
  5364. Compilation.PROCESS_ASSETS_STAGE_REPORT = 5000;
  5365. module.exports = Compilation;