RelativeUrlRuntimeModule.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. /** @typedef {import("../Compilation")} Compilation */
  9. class RelativeUrlRuntimeModule extends HelperRuntimeModule {
  10. constructor() {
  11. super("relative url");
  12. }
  13. /**
  14. * @returns {string | null} runtime code
  15. */
  16. generate() {
  17. const compilation = /** @type {Compilation} */ (this.compilation);
  18. const { runtimeTemplate } = compilation;
  19. return Template.asString([
  20. `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`,
  21. Template.indent([
  22. 'var realUrl = new URL(url, "x:/");',
  23. "var values = {};",
  24. "for (var key in realUrl) values[key] = realUrl[key];",
  25. "values.href = url;",
  26. 'values.pathname = url.replace(/[?#].*/, "");',
  27. 'values.origin = values.protocol = "";',
  28. `values.toString = values.toJSON = ${runtimeTemplate.returningFunction(
  29. "url"
  30. )};`,
  31. "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });"
  32. ]),
  33. "};",
  34. `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;`
  35. ]);
  36. }
  37. }
  38. module.exports = RelativeUrlRuntimeModule;