RelativeUrlRuntimeModule.js 1.2 KB

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