LoaderRunner.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { readFile } = require("fs");
  7. const { parseResource } = require("../util/identifier");
  8. const loadLoader = require("./loadLoader");
  9. // Set on a loader context to have each loader's own run measured. Absent
  10. // unless something asked for the measurement, and read once per loader.
  11. const LOADER_TIMING = Symbol("loader timing");
  12. /** @typedef {string | ({ loader: string } & Record<string, EXPECTED_ANY>)} LoaderItemInput */
  13. /**
  14. * @typedef {object} ProcessOptions
  15. * @property {Buffer | null} resourceBuffer the raw resource buffer
  16. * @property {(loaderContext: EXPECTED_ANY, resource: string, callback: (err: Error | null, ...args: EXPECTED_ANY[]) => void) => void} processResource read and process the resource
  17. */
  18. /**
  19. * @typedef {object} RunLoaderOptions
  20. * @property {string=} resource the resource (with query and fragment)
  21. * @property {LoaderItemInput[]=} loaders the loaders to run
  22. * @property {EXPECTED_ANY=} context the loader context to augment and pass to loaders
  23. * @property {ProcessOptions["processResource"]=} processResource custom resource reader/processor
  24. * @property {((path: string, callback: (err: Error | null, result?: Buffer) => void) => void)=} readResource custom file reader
  25. */
  26. /**
  27. * @typedef {object} RunLoaderResult
  28. * @property {EXPECTED_ANY=} result the loader pipeline result
  29. * @property {Buffer | null=} resourceBuffer the raw resource buffer
  30. * @property {boolean} cacheable whether the request is cacheable
  31. * @property {string[]} notCacheableReasons reasons why the request is not cacheable (e.g. paths of loaders that marked it)
  32. * @property {string[]} fileDependencies file dependencies
  33. * @property {string[]} contextDependencies context (directory) dependencies
  34. * @property {string[]} missingDependencies missing dependencies
  35. */
  36. /** @typedef {(...args: EXPECTED_ANY[]) => void} LoaderCallback */
  37. /** @typedef {import("../../declarations/LoaderContext").LoaderRunnerLoaderContext<EXPECTED_ANY>} LoaderRunnerLoaderContext */
  38. /**
  39. * The loader context as the runner sees and mutates it: the canonical
  40. * `LoaderRunnerLoaderContext` shape (not re-declared here), with only the fields
  41. * the runner assigns internally before a loader runs widened to their mutable
  42. * form (nullable `context`/`callback`/`async`, `LoaderObject` loaders).
  43. * @typedef {Omit<LoaderRunnerLoaderContext, "context" | "callback" | "async" | "loaders"> & { context: string | null, callback: LoaderCallback | null, async: (() => LoaderCallback | undefined) | null, loaders: LoaderObject[] }} LoaderContext
  44. */
  45. const HASH_ESCAPE_REGEXP = /#/g;
  46. // UTF-8 encoding of the BOM: EF BB BF
  47. const UTF8_BOM_0 = 0xef;
  48. const UTF8_BOM_1 = 0xbb;
  49. const UTF8_BOM_2 = 0xbf;
  50. /**
  51. * @param {Buffer} buf buffer
  52. * @returns {string} string, with a leading UTF-8 BOM skipped at the buffer level
  53. */
  54. function utf8BufferToString(buf) {
  55. if (
  56. buf.length >= 3 &&
  57. buf[0] === UTF8_BOM_0 &&
  58. buf[1] === UTF8_BOM_1 &&
  59. buf[2] === UTF8_BOM_2
  60. ) {
  61. return buf.toString("utf8", 3);
  62. }
  63. return buf.toString("utf8");
  64. }
  65. /**
  66. * Escape `#` with a preceding `\0` byte; short-circuits when there is no `#`.
  67. * @param {string} str input string
  68. * @returns {string} escaped string
  69. */
  70. function escapeHash(str) {
  71. return str.includes("#") ? str.replace(HASH_ESCAPE_REGEXP, "\0#") : str;
  72. }
  73. /**
  74. * @param {string} path path
  75. * @returns {string} directory name
  76. */
  77. function dirname(path) {
  78. if (path === "/") return "/";
  79. const i = path.lastIndexOf("/");
  80. const j = path.lastIndexOf("\\");
  81. const i2 = path.indexOf("/");
  82. const j2 = path.indexOf("\\");
  83. const idx = i > j ? i : j;
  84. const idx2 = i > j ? i2 : j2;
  85. if (idx < 0) return path;
  86. if (idx === idx2) return path.slice(0, idx + 1);
  87. return path.slice(0, idx);
  88. }
  89. /**
  90. * A single loader in the pipeline. `request` is an accessor: reading it
  91. * serializes path/query/fragment; assigning a string or descriptor parses it.
  92. */
  93. class LoaderObject {
  94. /**
  95. * @param {LoaderItemInput} loader loader request or descriptor
  96. */
  97. constructor(loader) {
  98. /** @type {string} */
  99. this.path = "";
  100. /** @type {string} */
  101. this.query = "";
  102. /** @type {string} */
  103. this.fragment = "";
  104. /** @type {string | { [key: string]: EXPECTED_ANY } | null=} */
  105. this.options = null;
  106. /** @type {string | null=} */
  107. this.ident = null;
  108. /** @type {string=} */
  109. this.type = undefined;
  110. /** @type {EXPECTED_FUNCTION | null=} */
  111. this.normal = null;
  112. /** @type {EXPECTED_FUNCTION | null=} */
  113. this.pitch = null;
  114. /** @type {boolean | null=} */
  115. this.raw = null;
  116. /** @type {EXPECTED_OBJECT | null=} */
  117. this.data = null;
  118. this.pitchExecuted = false;
  119. this.normalExecuted = false;
  120. // enumerable own accessor: class getters are non-enumerable and would be
  121. // dropped when the loader object is serialized (loaders rely on `request`)
  122. Object.defineProperty(this, "request", REQUEST_DESCRIPTOR);
  123. this.request = loader;
  124. Object.preventExtensions(this);
  125. }
  126. /**
  127. * @returns {string} the loader request (path + query + fragment)
  128. */
  129. get request() {
  130. return escapeHash(this.path) + escapeHash(this.query) + this.fragment;
  131. }
  132. /**
  133. * @param {LoaderItemInput} value loader request or descriptor
  134. */
  135. set request(value) {
  136. if (typeof value === "string") {
  137. const { path, query, fragment } = parseResource(value);
  138. this.path = path;
  139. this.query = query;
  140. this.fragment = fragment;
  141. this.options = undefined;
  142. this.ident = undefined;
  143. return;
  144. }
  145. if (!value.loader) {
  146. throw new Error(
  147. `request should be a string or object with loader and options (${JSON.stringify(
  148. value
  149. )})`
  150. );
  151. }
  152. const { loader: path, fragment, type, options, ident } = value;
  153. this.path = path;
  154. this.fragment = fragment || "";
  155. this.type = type;
  156. this.options = options;
  157. this.ident = ident;
  158. if (options === null || options === undefined) {
  159. this.query = "";
  160. } else if (typeof options === "string") {
  161. this.query = `?${options}`;
  162. } else if (ident) {
  163. this.query = `??${ident}`;
  164. } else if (typeof options === "object" && options.ident) {
  165. this.query = `??${options.ident}`;
  166. } else {
  167. this.query = `?${JSON.stringify(options)}`;
  168. }
  169. }
  170. }
  171. // Shared enumerable descriptor reusing the prototype's `request` accessor.
  172. const REQUEST_DESCRIPTOR = {
  173. .../** @type {PropertyDescriptor} */ (
  174. Object.getOwnPropertyDescriptor(LoaderObject.prototype, "request")
  175. ),
  176. enumerable: true
  177. };
  178. /**
  179. * @param {EXPECTED_FUNCTION} fn the loader function
  180. * @param {LoaderContext} context the loader context
  181. * @param {EXPECTED_ANY[]} args arguments
  182. * @param {LoaderCallback} callback callback
  183. * @returns {void}
  184. */
  185. function runSyncOrAsync(fn, context, args, callback) {
  186. let isSync = true;
  187. let isDone = false;
  188. let isError = false; // internal error
  189. let reportedError = false;
  190. /**
  191. * @param {...EXPECTED_ANY} callbackArgs callback args
  192. * @returns {void}
  193. */
  194. function innerCallback(...callbackArgs) {
  195. if (isDone) {
  196. if (reportedError) return; // ignore
  197. throw new Error("callback(): The callback was already called.");
  198. }
  199. isDone = true;
  200. isSync = false;
  201. try {
  202. callback(...callbackArgs);
  203. } catch (err) {
  204. isError = true;
  205. throw err;
  206. }
  207. }
  208. context.callback = innerCallback;
  209. context.async = function async() {
  210. if (isDone) {
  211. if (reportedError) return; // ignore
  212. throw new Error("async(): The callback was already called.");
  213. }
  214. isSync = false;
  215. return innerCallback;
  216. };
  217. const timing =
  218. /** @type {{ [LOADER_TIMING]?: (loader: EXPECTED_ANY, run: () => EXPECTED_ANY) => EXPECTED_ANY }} */
  219. (context)[LOADER_TIMING];
  220. try {
  221. const result = (function LOADER_EXECUTION() {
  222. return timing
  223. ? timing(context.loaders[context.loaderIndex], () =>
  224. fn.apply(context, args)
  225. )
  226. : fn.apply(context, args);
  227. })();
  228. if (isSync) {
  229. isDone = true;
  230. if (result === undefined) return callback(null);
  231. if (
  232. result &&
  233. typeof result === "object" &&
  234. typeof result.then === "function"
  235. ) {
  236. return result.then((/** @type {EXPECTED_ANY} */ r) => {
  237. callback(null, r);
  238. }, callback);
  239. }
  240. return callback(null, result);
  241. }
  242. } catch (err) {
  243. if (isError) throw err;
  244. if (isDone) {
  245. // loader already finished; print the error since the callback is spent.
  246. if (typeof err === "object" && /** @type {Error} */ (err).stack) {
  247. // eslint-disable-next-line no-console
  248. console.error(/** @type {Error} */ (err).stack);
  249. } else {
  250. // eslint-disable-next-line no-console
  251. console.error(err);
  252. }
  253. return;
  254. }
  255. isDone = true;
  256. reportedError = true;
  257. callback(/** @type {Error} */ (err));
  258. }
  259. }
  260. /**
  261. * @param {EXPECTED_ANY[]} args arguments
  262. * @param {boolean | null=} raw whether the loader wants a Buffer
  263. * @returns {void}
  264. */
  265. function convertArgs(args, raw) {
  266. if (!raw && Buffer.isBuffer(args[0])) {
  267. args[0] = utf8BufferToString(args[0]);
  268. } else if (raw && typeof args[0] === "string") {
  269. args[0] = Buffer.from(args[0], "utf8");
  270. }
  271. }
  272. /**
  273. * @param {ProcessOptions} options process options
  274. * @param {LoaderContext} loaderContext the loader context
  275. * @param {EXPECTED_ANY[]} args arguments
  276. * @param {(err: Error | null, args?: EXPECTED_ANY[]) => void} callback callback
  277. * @returns {void}
  278. */
  279. function iterateNormalLoaders(options, loaderContext, args, callback) {
  280. while (loaderContext.loaderIndex >= 0) {
  281. const currentLoaderObject =
  282. loaderContext.loaders[loaderContext.loaderIndex];
  283. if (currentLoaderObject.normalExecuted) {
  284. loaderContext.loaderIndex--;
  285. continue;
  286. }
  287. const fn = currentLoaderObject.normal;
  288. currentLoaderObject.normalExecuted = true;
  289. if (!fn) {
  290. loaderContext.loaderIndex--;
  291. continue;
  292. }
  293. convertArgs(args, currentLoaderObject.raw);
  294. return runSyncOrAsync(fn, loaderContext, args, (err, ...nextArgs) => {
  295. if (err) return callback(err);
  296. iterateNormalLoaders(options, loaderContext, nextArgs, callback);
  297. });
  298. }
  299. return callback(null, args);
  300. }
  301. /**
  302. * @param {ProcessOptions} options process options
  303. * @param {LoaderContext} loaderContext the loader context
  304. * @param {(err: Error | null, args?: EXPECTED_ANY[]) => void} callback callback
  305. * @returns {void}
  306. */
  307. function processResource(options, loaderContext, callback) {
  308. // set loader index to last loader
  309. loaderContext.loaderIndex = loaderContext.loaders.length - 1;
  310. const { resourcePath } = loaderContext;
  311. if (!resourcePath) {
  312. return iterateNormalLoaders(options, loaderContext, [null], callback);
  313. }
  314. options.processResource(loaderContext, resourcePath, (err, ...args) => {
  315. if (err) return callback(err);
  316. options.resourceBuffer = args[0];
  317. iterateNormalLoaders(options, loaderContext, args, callback);
  318. });
  319. }
  320. /**
  321. * @param {ProcessOptions} options process options
  322. * @param {LoaderContext} loaderContext the loader context
  323. * @param {(err: Error | null, args?: EXPECTED_ANY[]) => void} callback callback
  324. * @returns {void}
  325. */
  326. function iteratePitchingLoaders(options, loaderContext, callback) {
  327. // Iterative walk over already-pitched loaders without recursion.
  328. while (loaderContext.loaderIndex < loaderContext.loaders.length) {
  329. const currentLoaderObject =
  330. loaderContext.loaders[loaderContext.loaderIndex];
  331. if (currentLoaderObject.pitchExecuted) {
  332. loaderContext.loaderIndex++;
  333. continue;
  334. }
  335. return loadLoader(currentLoaderObject, (err) => {
  336. if (err) {
  337. loaderContext.cacheable(false);
  338. return callback(err);
  339. }
  340. const fn = currentLoaderObject.pitch;
  341. currentLoaderObject.pitchExecuted = true;
  342. if (!fn) return iteratePitchingLoaders(options, loaderContext, callback);
  343. runSyncOrAsync(
  344. fn,
  345. loaderContext,
  346. [
  347. loaderContext.remainingRequest,
  348. loaderContext.previousRequest,
  349. (currentLoaderObject.data = {})
  350. ],
  351. (pitchErr, ...args) => {
  352. if (pitchErr) return callback(pitchErr);
  353. // Continue pitching unless the pitch yielded a value (checked by
  354. // value, not arity, to support sync and async usage).
  355. let hasArg = false;
  356. for (let i = 0; i < args.length; i++) {
  357. if (args[i] !== undefined) {
  358. hasArg = true;
  359. break;
  360. }
  361. }
  362. if (hasArg) {
  363. loaderContext.loaderIndex--;
  364. iterateNormalLoaders(options, loaderContext, args, callback);
  365. } else {
  366. iteratePitchingLoaders(options, loaderContext, callback);
  367. }
  368. }
  369. );
  370. });
  371. }
  372. // Reached the end: move on to processing the resource itself.
  373. return processResource(options, loaderContext, callback);
  374. }
  375. /**
  376. * Join loader requests into a single `!`-separated string for a range of indices.
  377. * @param {LoaderObject[]} loaders loader objects
  378. * @param {number} start inclusive start index
  379. * @param {number} end exclusive end index
  380. * @param {string} resource resource string
  381. * @returns {string} joined request
  382. */
  383. function joinRequests(loaders, start, end, resource) {
  384. let result = "";
  385. for (let i = start; i < end; i++) {
  386. result += `${loaders[i].request}!`;
  387. }
  388. return result + resource;
  389. }
  390. module.exports.LOADER_TIMING = LOADER_TIMING;
  391. module.exports.LoaderObject = LoaderObject;
  392. module.exports.createLoaderContext = createLoaderContext;
  393. /**
  394. * @param {string} resource resource
  395. * @returns {string} the context (directory) of the resource
  396. */
  397. module.exports.getContext = function getContext(resource) {
  398. return dirname(parseResource(resource).path);
  399. };
  400. /**
  401. * @typedef {object} LoaderState
  402. * @property {boolean} cacheable whether the request is cacheable
  403. * @property {string[]} notCacheableReasons reasons why the request is not cacheable (e.g. paths of loaders that marked it)
  404. * @property {string[]} fileDependencies collected file dependencies
  405. * @property {string[]} contextDependencies collected context dependencies
  406. * @property {string[]} missingDependencies collected missing dependencies
  407. */
  408. // Carries the mutable result state off the loader-visible surface, so loaders
  409. // and JSON serialization of the context never see it.
  410. const LOADER_STATE = Symbol("loader context state");
  411. /**
  412. * @param {LoaderContext} loaderContext loader context
  413. * @returns {LoaderState} the hidden mutable state carried under `LOADER_STATE`
  414. */
  415. function getState(loaderContext) {
  416. return /** @type {EXPECTED_ANY} */ (loaderContext)[LOADER_STATE];
  417. }
  418. /**
  419. * Phase 1 of loader-context construction (the single place the context shape is
  420. * defined): augments `base` in place with fresh result state and the dependency
  421. * methods. Phase 2 lives in `runLoaders`, which sets the resource-derived fields
  422. * and the `request` accessors once host hooks have populated the context, then
  423. * freezes it — the accessors are added last so V8 keeps the context in
  424. * fast-properties mode. Returned unfrozen.
  425. * @param {EXPECTED_ANY=} base object to augment (the caller's context), if any
  426. * @returns {LoaderContext} the loader context
  427. */
  428. function createLoaderContext(base) {
  429. /** @type {LoaderState} */
  430. const state = {
  431. cacheable: true,
  432. notCacheableReasons: [],
  433. fileDependencies: [],
  434. contextDependencies: [],
  435. missingDependencies: []
  436. };
  437. const loaderContext = /** @type {LoaderContext} */ (base || {});
  438. // resource-derived fields and loaders are set by runLoaders (after hooks)
  439. loaderContext.context = null;
  440. loaderContext.loaderIndex = 0;
  441. loaderContext.loaders = [];
  442. loaderContext.resourcePath = "";
  443. loaderContext.resourceQuery = "";
  444. loaderContext.resourceFragment = "";
  445. loaderContext.async = null;
  446. loaderContext.callback = null;
  447. // closures over `state` (not `this`-based): loaders pass these as detached
  448. // callbacks, e.g. `deps.forEach(this.addDependency)`, so they must not rely on
  449. // the receiver
  450. loaderContext.cacheable = (flag) => {
  451. if (flag === false) {
  452. state.cacheable = false;
  453. // attribute the flag to the running loader; absent when the host marks
  454. // the request outside the loader run (e.g. in a beforeLoaders hook)
  455. const currentLoader = loaderContext.loaders[loaderContext.loaderIndex];
  456. if (
  457. currentLoader &&
  458. !state.notCacheableReasons.includes(currentLoader.path)
  459. ) {
  460. state.notCacheableReasons.push(currentLoader.path);
  461. }
  462. }
  463. };
  464. loaderContext.dependency = loaderContext.addDependency = (file) => {
  465. state.fileDependencies.push(file);
  466. };
  467. loaderContext.addContextDependency = (context) => {
  468. state.contextDependencies.push(context);
  469. };
  470. loaderContext.addMissingDependency = (missing) => {
  471. state.missingDependencies.push(missing);
  472. };
  473. loaderContext.getDependencies = () => [...state.fileDependencies];
  474. loaderContext.getContextDependencies = () => [...state.contextDependencies];
  475. loaderContext.getMissingDependencies = () => [...state.missingDependencies];
  476. loaderContext.clearDependencies = () => {
  477. state.fileDependencies.length = 0;
  478. state.contextDependencies.length = 0;
  479. state.missingDependencies.length = 0;
  480. state.cacheable = true;
  481. state.notCacheableReasons.length = 0;
  482. };
  483. Object.defineProperty(loaderContext, LOADER_STATE, { value: state });
  484. return loaderContext;
  485. }
  486. /**
  487. * Marks the request as not cacheable with the given reasons instead of
  488. * attributing the currently running loader (used by the host when the cause
  489. * lives outside the loader, e.g. in a child compilation of `importModule`).
  490. * @param {LoaderRunnerLoaderContext} loaderContext loader context
  491. * @param {string[]} reasons reasons why the request is not cacheable
  492. * @returns {void}
  493. */
  494. module.exports.markNotCacheable = (loaderContext, reasons) => {
  495. const state = getState(/** @type {LoaderContext} */ (loaderContext));
  496. state.cacheable = false;
  497. for (const reason of reasons) {
  498. if (!state.notCacheableReasons.includes(reason)) {
  499. state.notCacheableReasons.push(reason);
  500. }
  501. }
  502. };
  503. /**
  504. * The `request`-family accessors. Enumerable because loaders serialize the
  505. * context; shared (no per-context closures) and `this`-based. Added last, via
  506. * `Object.defineProperties`, to keep the context in fast-properties mode. Shared
  507. * (same descriptors), so re-defining them on a reused context is a harmless no-op.
  508. * @type {PropertyDescriptorMap & ThisType<LoaderContext>}
  509. */
  510. const ACCESSORS = {
  511. resource: {
  512. enumerable: true,
  513. get() {
  514. return (
  515. escapeHash(this.resourcePath) +
  516. escapeHash(this.resourceQuery) +
  517. this.resourceFragment
  518. );
  519. },
  520. set(value) {
  521. const splitted = value && parseResource(value);
  522. this.resourcePath = splitted ? splitted.path : "";
  523. this.resourceQuery = splitted ? splitted.query : "";
  524. this.resourceFragment = splitted ? splitted.fragment : "";
  525. }
  526. },
  527. request: {
  528. enumerable: true,
  529. get() {
  530. return joinRequests(
  531. this.loaders,
  532. 0,
  533. this.loaders.length,
  534. this.resource || ""
  535. );
  536. }
  537. },
  538. remainingRequest: {
  539. enumerable: true,
  540. get() {
  541. return joinRequests(
  542. this.loaders,
  543. this.loaderIndex + 1,
  544. this.loaders.length,
  545. this.resource
  546. );
  547. }
  548. },
  549. currentRequest: {
  550. enumerable: true,
  551. get() {
  552. return joinRequests(
  553. this.loaders,
  554. this.loaderIndex,
  555. this.loaders.length,
  556. this.resource
  557. );
  558. }
  559. },
  560. previousRequest: {
  561. enumerable: true,
  562. get() {
  563. const { loaders } = this;
  564. const end = this.loaderIndex;
  565. if (end === 0) return "";
  566. let result = loaders[0].request;
  567. for (let i = 1; i < end; i++) {
  568. result += `!${loaders[i].request}`;
  569. }
  570. return result;
  571. }
  572. },
  573. query: {
  574. enumerable: true,
  575. get() {
  576. const entry = this.loaders[this.loaderIndex];
  577. return entry.options && typeof entry.options === "object"
  578. ? entry.options
  579. : entry.query;
  580. }
  581. },
  582. data: {
  583. enumerable: true,
  584. get() {
  585. return this.loaders[this.loaderIndex].data;
  586. }
  587. }
  588. };
  589. /**
  590. * @param {RunLoaderOptions} options run options
  591. * @param {(err: Error | null, result: RunLoaderResult) => void} callback callback
  592. * @returns {void}
  593. */
  594. module.exports.runLoaders = function runLoaders(options, callback) {
  595. // reuse a context already prepared by createLoaderContext (e.g. from
  596. // NormalModule), else augment the caller-provided context (or a fresh object)
  597. // in place. State is intentionally preserved across the handoff, so host hooks
  598. // (e.g. beforeLoaders) can pre-add dependencies or mark the request
  599. // non-cacheable before the run; a caller re-running on the same context should
  600. // clearDependencies() first to avoid accumulating stale dependencies.
  601. const provided = /** @type {EXPECTED_ANY} */ (options.context);
  602. const loaderContext =
  603. provided && provided[LOADER_STATE]
  604. ? /** @type {LoaderContext} */ (provided)
  605. : createLoaderContext(provided);
  606. const state = getState(loaderContext);
  607. // (re)set iteration + resource fields and map loaders now, after host hooks
  608. // (e.g. NormalModule's loader/beforeLoaders) have run and may have changed them
  609. loaderContext.loaderIndex = 0;
  610. const resource = options.resource || "";
  611. const splittedResource = resource && parseResource(resource);
  612. loaderContext.resourcePath = splittedResource ? splittedResource.path : "";
  613. loaderContext.resourceQuery = splittedResource ? splittedResource.query : "";
  614. loaderContext.resourceFragment = splittedResource
  615. ? splittedResource.fragment
  616. : "";
  617. loaderContext.context = loaderContext.resourcePath
  618. ? dirname(loaderContext.resourcePath)
  619. : null;
  620. loaderContext.loaders = (options.loaders || []).map(
  621. (loader) => new LoaderObject(loader)
  622. );
  623. const processResourceFn =
  624. options.processResource ||
  625. /** @type {(readResource: EXPECTED_FUNCTION, context: EXPECTED_ANY, res: string, cb: (err: Error | null, ...args: EXPECTED_ANY[]) => void) => void} */
  626. (
  627. (readResource, context, res, cb) => {
  628. context.addDependency(res);
  629. readResource(res, cb);
  630. }
  631. ).bind(null, options.readResource || readFile);
  632. // add accessors last (keeps fast properties) and freeze, now that callers
  633. // (e.g. NormalModule's beforeLoaders) have populated the context
  634. Object.defineProperties(loaderContext, ACCESSORS);
  635. Object.preventExtensions(loaderContext);
  636. /** @type {ProcessOptions} */
  637. const processOptions = {
  638. resourceBuffer: null,
  639. processResource: processResourceFn
  640. };
  641. iteratePitchingLoaders(processOptions, loaderContext, (err, result) => {
  642. if (err) {
  643. return callback(err, {
  644. cacheable: state.cacheable,
  645. notCacheableReasons: state.notCacheableReasons,
  646. fileDependencies: state.fileDependencies,
  647. contextDependencies: state.contextDependencies,
  648. missingDependencies: state.missingDependencies
  649. });
  650. }
  651. callback(null, {
  652. result,
  653. resourceBuffer: processOptions.resourceBuffer,
  654. cacheable: state.cacheable,
  655. notCacheableReasons: state.notCacheableReasons,
  656. fileDependencies: state.fileDependencies,
  657. contextDependencies: state.contextDependencies,
  658. missingDependencies: state.missingDependencies
  659. });
  660. });
  661. };