transform.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // src/rspack/context.ts
  2. import { Buffer } from "buffer";
  3. import sources from "webpack-sources";
  4. import { Parser } from "acorn";
  5. function createBuildContext(compilation) {
  6. return {
  7. parse(code, opts = {}) {
  8. return Parser.parse(code, {
  9. sourceType: "module",
  10. ecmaVersion: "latest",
  11. locations: true,
  12. ...opts
  13. });
  14. },
  15. addWatchFile() {
  16. },
  17. emitFile(emittedFile) {
  18. const outFileName = emittedFile.fileName || emittedFile.name;
  19. if (emittedFile.source && outFileName) {
  20. compilation.emitAsset(
  21. outFileName,
  22. new sources.RawSource(
  23. // @ts-expect-error types mismatch
  24. typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
  25. )
  26. );
  27. }
  28. },
  29. getWatchFiles() {
  30. return [];
  31. }
  32. };
  33. }
  34. function createContext(loader) {
  35. return {
  36. error: (error) => loader.emitError(normalizeMessage(error)),
  37. warn: (message) => loader.emitWarning(normalizeMessage(message))
  38. };
  39. }
  40. function normalizeMessage(error) {
  41. const err = new Error(typeof error === "string" ? error : error.message);
  42. if (typeof error === "object") {
  43. err.stack = error.stack;
  44. err.cause = error.meta;
  45. }
  46. return err;
  47. }
  48. // src/rspack/loaders/transform.ts
  49. async function transform(source, map) {
  50. const callback = this.async();
  51. let unpluginName;
  52. if (typeof this.query === "string") {
  53. const query = new URLSearchParams(this.query);
  54. unpluginName = query.get("unpluginName");
  55. } else {
  56. unpluginName = this.query.unpluginName;
  57. }
  58. const id = this.resource;
  59. const plugin = this._compiler?.$unpluginContext[unpluginName];
  60. if (!plugin?.transform)
  61. return callback(null, source, map);
  62. const context = createContext(this);
  63. const res = await plugin.transform.call(
  64. Object.assign(
  65. this._compilation && createBuildContext(this._compilation),
  66. context
  67. ),
  68. source,
  69. id
  70. );
  71. if (res == null)
  72. callback(null, source, map);
  73. else if (typeof res !== "string")
  74. callback(null, res.code, map == null ? map : res.map || map);
  75. else
  76. callback(null, res, map);
  77. }
  78. export {
  79. transform as default
  80. };