transform.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // src/webpack/context.ts
  2. import { resolve } from "path";
  3. import sources from "webpack-sources";
  4. import { Parser } from "acorn";
  5. function createContext(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(id) {
  16. (compilation.fileDependencies ?? compilation.compilationDependencies).add(
  17. resolve(process.cwd(), id)
  18. );
  19. },
  20. emitFile(emittedFile) {
  21. const outFileName = emittedFile.fileName || emittedFile.name;
  22. if (emittedFile.source && outFileName) {
  23. compilation.emitAsset(
  24. outFileName,
  25. sources ? new sources.RawSource(
  26. typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
  27. ) : {
  28. source: () => emittedFile.source,
  29. size: () => emittedFile.source.length
  30. }
  31. );
  32. }
  33. },
  34. getWatchFiles() {
  35. return Array.from(
  36. compilation.fileDependencies ?? compilation.compilationDependencies
  37. );
  38. }
  39. };
  40. }
  41. // src/webpack/loaders/transform.ts
  42. async function transform(source, map) {
  43. const callback = this.async();
  44. let unpluginName;
  45. if (typeof this.query === "string") {
  46. const query = new URLSearchParams(this.query);
  47. unpluginName = query.get("unpluginName");
  48. } else {
  49. unpluginName = this.query.unpluginName;
  50. }
  51. const plugin = this._compiler?.$unpluginContext[unpluginName];
  52. if (!plugin?.transform)
  53. return callback(null, source, map);
  54. const context = {
  55. error: (error) => this.emitError(typeof error === "string" ? new Error(error) : error),
  56. warn: (error) => this.emitWarning(typeof error === "string" ? new Error(error) : error)
  57. };
  58. const res = await plugin.transform.call(Object.assign(this._compilation && createContext(this._compilation), context), source, this.resource);
  59. if (res == null)
  60. callback(null, source, map);
  61. else if (typeof res !== "string")
  62. callback(null, res.code, map == null ? map : res.map || map);
  63. else
  64. callback(null, res, map);
  65. }
  66. export {
  67. transform as default
  68. };