RelativeUrlRuntimeModule.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeGlobals = require("../RuntimeGlobals");
  6. const Template = require("../Template");
  7. const HelperRuntimeModule = require("./HelperRuntimeModule");
  8. /** @import Compilation from "../Compilation" */
  9. class RelativeUrlRuntimeModule extends HelperRuntimeModule {
  10. constructor() {
  11. super("relative url");
  12. }
  13. /**
  14. * Returns true, if the runtime module should get it's own scope.
  15. * When false, `generate()` must emit complete statements ending with `;`
  16. * so a following runtime IIFE is not parsed as a call (ASI).
  17. * @returns {boolean} true, if the runtime module should get it's own scope
  18. */
  19. shouldIsolate() {
  20. return false;
  21. }
  22. /**
  23. * Generates runtime code for this runtime module.
  24. * @returns {string | null} runtime code
  25. */
  26. generate() {
  27. const compilation = /** @type {Compilation} */ (this.compilation);
  28. const { runtimeTemplate } = compilation;
  29. const cst = runtimeTemplate.renderConst();
  30. return Template.asString([
  31. `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`,
  32. Template.indent([
  33. `${cst} realUrl = new URL(url, "x:/");`,
  34. `${cst} values = {};`,
  35. "for (var key in realUrl) values[key] = realUrl[key];",
  36. "values.href = url;",
  37. 'values.pathname = url.replace(/[?#].*/, "");',
  38. 'values.origin = values.protocol = "";',
  39. `values.toString = values.toJSON = ${runtimeTemplate.returningFunction(
  40. "url"
  41. )};`,
  42. "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });"
  43. ]),
  44. "};",
  45. `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;`
  46. ]);
  47. }
  48. }
  49. module.exports = RelativeUrlRuntimeModule;