index.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
  2. function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
  3. function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
  4. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
  5. function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
  6. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  7. /* global __resourceQuery, __webpack_hash__ */
  8. // @ts-expect-error
  9. import hotEmitter from "webpack/hot/emitter.js";
  10. // @ts-expect-error
  11. import webpackHotLog from "webpack/hot/log.js";
  12. import { createOverlay, formatProblem } from "./overlay.js";
  13. import { defineProgressElement, isProgressSupported } from "./progress.js";
  14. import socket from "./socket.js";
  15. import { log, setLogLevel } from "./utils/log.js";
  16. import sendMessage from "./utils/sendMessage.js";
  17. // eslint-disable-next-line jsdoc/no-restricted-syntax
  18. /** @typedef {any} EXPECTED_ANY */
  19. /**
  20. * @typedef {object} RawOverlayOptions
  21. * @property {string=} warnings warnings
  22. * @property {string=} errors errors
  23. * @property {string=} runtimeErrors runtime errors
  24. * @property {string=} trustedTypesPolicyName trusted types policy name
  25. */
  26. /**
  27. * @typedef {object} OverlayOptions
  28. * @property {(boolean | ((error: Error) => boolean))=} warnings warnings
  29. * @property {(boolean | ((error: Error) => boolean))=} errors errors
  30. * @property {(boolean | ((error: Error) => boolean))=} runtimeErrors runtime errors
  31. * @property {string=} trustedTypesPolicyName trusted types policy name
  32. */
  33. /** @typedef {false | true | "none" | "error" | "warn" | "info" | "log" | "verbose"} LogLevel */
  34. /**
  35. * @typedef {object} Options
  36. * @property {boolean} hot true when hot enabled, otherwise false
  37. * @property {boolean} liveReload true when live reload enabled, otherwise false
  38. * @property {boolean} progress true when need to show progress, otherwise false
  39. * @property {boolean | OverlayOptions} overlay overlay options
  40. * @property {LogLevel=} logging logging level
  41. * @property {number=} reconnect count of allowed reconnection
  42. */
  43. /**
  44. * @typedef {object} Status
  45. * @property {boolean} isUnloading true when unloaded, otherwise false
  46. * @property {string} currentHash current hash
  47. * @property {string=} previousHash previous hash
  48. */
  49. /**
  50. * @param {boolean | RawOverlayOptions | OverlayOptions} overlayOptions overlay options
  51. */
  52. var decodeOverlayOptions = function decodeOverlayOptions(overlayOptions) {
  53. if (_typeof(overlayOptions) === "object") {
  54. var requiredOptions = ["warnings", "errors", "runtimeErrors"];
  55. for (var i = 0; i < requiredOptions.length; i++) {
  56. var property = /** @type {keyof Omit<RawOverlayOptions, "trustedTypesPolicyName">} */
  57. requiredOptions[i];
  58. if (typeof overlayOptions[property] === "string") {
  59. var overlayFilterFunctionString = decodeURIComponent(overlayOptions[property]);
  60. /** @type {OverlayOptions} */
  61. overlayOptions[property] = /** @type {(error: Error) => boolean} */
  62. // eslint-disable-next-line no-new-func
  63. new Function("message", "var callback = ".concat(overlayFilterFunctionString, "\n return callback(message)"));
  64. }
  65. }
  66. }
  67. };
  68. /**
  69. * @type {Status}
  70. */
  71. var status = {
  72. isUnloading: false,
  73. currentHash: __webpack_hash__
  74. };
  75. /**
  76. * @returns {string} current script source
  77. */
  78. var getCurrentScriptSource = function getCurrentScriptSource() {
  79. // `document.currentScript` is the most accurate way to find the current script,
  80. // but is not supported in all browsers.
  81. if (document.currentScript) {
  82. return /** @type {string} */document.currentScript.getAttribute("src");
  83. }
  84. // Fallback to getting all scripts running in the document.
  85. var scriptElements = document.scripts || [];
  86. var scriptElementsWithSrc = Array.prototype.filter.call(scriptElements, function (element) {
  87. return element.getAttribute("src");
  88. });
  89. if (scriptElementsWithSrc.length > 0) {
  90. var currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1];
  91. return currentScript.getAttribute("src");
  92. }
  93. // Fail as there was no script to use.
  94. throw new Error("[webpack-dev-server] Failed to get current script source.");
  95. };
  96. /** @typedef {{ hot?: string, ["live-reload"]?: string, progress?: string, reconnect?: string, logging?: LogLevel, overlay?: string, fromCurrentScript?: boolean }} AdditionalParsedURL */
  97. /** @typedef {Partial<URL> & AdditionalParsedURL} ParsedURL */
  98. /**
  99. * @param {string} resourceQuery resource query
  100. * @returns {ParsedURL} parsed URL
  101. */
  102. var parseURL = function parseURL(resourceQuery) {
  103. /** @type {ParsedURL} */
  104. var result = {};
  105. if (typeof resourceQuery === "string" && resourceQuery !== "") {
  106. var searchParams = resourceQuery.slice(1).split("&");
  107. for (var i = 0; i < searchParams.length; i++) {
  108. var pair = searchParams[i].split("=");
  109. /** @type {EXPECTED_ANY} */
  110. result[pair[0]] = decodeURIComponent(pair[1]);
  111. }
  112. } else {
  113. // Else, get the url from the <script> this file was called with.
  114. var scriptSource = getCurrentScriptSource();
  115. var scriptSourceURL;
  116. try {
  117. // The placeholder `baseURL` with `window.location.href`,
  118. // is to allow parsing of path-relative or protocol-relative URLs,
  119. // and will have no effect if `scriptSource` is a fully valid URL.
  120. scriptSourceURL = new URL(scriptSource, self.location.href);
  121. } catch (_err) {
  122. // URL parsing failed, do nothing.
  123. // We will still proceed to see if we can recover using `resourceQuery`
  124. }
  125. if (scriptSourceURL) {
  126. result = scriptSourceURL;
  127. result.fromCurrentScript = true;
  128. }
  129. }
  130. return result;
  131. };
  132. var parsedResourceQuery = parseURL(__resourceQuery);
  133. /** @typedef {{ ["Hot Module Replacement"]: boolean, ["Live Reloading"]: boolean, Progress: boolean, Overlay: boolean }} Features */
  134. /** @type {Features} */
  135. var enabledFeatures = {
  136. "Hot Module Replacement": false,
  137. "Live Reloading": false,
  138. Progress: false,
  139. Overlay: false
  140. };
  141. /** @type {Options} */
  142. var options = {
  143. hot: false,
  144. liveReload: false,
  145. progress: false,
  146. overlay: false
  147. };
  148. if (parsedResourceQuery.hot === "true") {
  149. options.hot = true;
  150. enabledFeatures["Hot Module Replacement"] = true;
  151. }
  152. if (parsedResourceQuery["live-reload"] === "true") {
  153. options.liveReload = true;
  154. enabledFeatures["Live Reloading"] = true;
  155. }
  156. if (parsedResourceQuery.progress === "true") {
  157. options.progress = true;
  158. enabledFeatures.Progress = true;
  159. }
  160. if (parsedResourceQuery.overlay) {
  161. try {
  162. options.overlay = JSON.parse(parsedResourceQuery.overlay);
  163. } catch (err) {
  164. log.error("Error parsing overlay options from resource query:", err);
  165. }
  166. // Fill in default "true" params for partially-specified objects.
  167. if (_typeof(options.overlay) === "object") {
  168. options.overlay = _objectSpread({
  169. errors: true,
  170. warnings: true,
  171. runtimeErrors: true
  172. }, options.overlay);
  173. decodeOverlayOptions(options.overlay);
  174. }
  175. enabledFeatures.Overlay = options.overlay !== false;
  176. }
  177. if (parsedResourceQuery.logging) {
  178. options.logging = parsedResourceQuery.logging;
  179. }
  180. if (typeof parsedResourceQuery.reconnect !== "undefined") {
  181. options.reconnect = Number(parsedResourceQuery.reconnect);
  182. }
  183. /**
  184. * @param {false | true | "none" | "error" | "warn" | "info" | "log" | "verbose"} level level
  185. */
  186. var setAllLogLevel = function setAllLogLevel(level) {
  187. // This is needed because the HMR logger operate separately from dev server logger
  188. webpackHotLog.setLogLevel(level === "verbose" || level === "log" ? "info" : level);
  189. setLogLevel(level);
  190. };
  191. if (options.logging) {
  192. setAllLogLevel(options.logging);
  193. }
  194. /**
  195. * @param {Features} features features
  196. */
  197. var logEnabledFeatures = function logEnabledFeatures(features) {
  198. var listEnabledFeatures = Object.keys(features);
  199. if (!features || listEnabledFeatures.length === 0) {
  200. return;
  201. }
  202. var logString = "Server started:";
  203. // Server started: Hot Module Replacement enabled, Live Reloading enabled, Overlay disabled.
  204. for (var i = 0; i < listEnabledFeatures.length; i++) {
  205. var key = /** @type {keyof Features} */listEnabledFeatures[i];
  206. logString += " ".concat(key, " ").concat(features[key] ? "enabled" : "disabled", ",");
  207. }
  208. // replace last comma with a period
  209. logString = logString.slice(0, -1).concat(".");
  210. log.info(logString);
  211. };
  212. logEnabledFeatures(enabledFeatures);
  213. self.addEventListener("beforeunload", function () {
  214. status.isUnloading = true;
  215. });
  216. var overlay = typeof window !== "undefined" ? createOverlay(_typeof(options.overlay) === "object" ? {
  217. trustedTypesPolicyName: options.overlay.trustedTypesPolicyName,
  218. catchRuntimeError: options.overlay.runtimeErrors
  219. } : {
  220. trustedTypesPolicyName: false,
  221. catchRuntimeError: options.overlay
  222. }) : {
  223. send: function send() {}
  224. };
  225. /**
  226. * @param {Options} options options
  227. * @param {Status} currentStatus current status
  228. */
  229. var reloadApp = function reloadApp(_ref, currentStatus) {
  230. var hot = _ref.hot,
  231. liveReload = _ref.liveReload;
  232. if (currentStatus.isUnloading) {
  233. return;
  234. }
  235. var currentHash = currentStatus.currentHash,
  236. previousHash = currentStatus.previousHash;
  237. var isInitial = currentHash.indexOf(/** @type {string} */previousHash) >= 0;
  238. if (isInitial) {
  239. return;
  240. }
  241. /**
  242. * @param {Window} rootWindow root window
  243. * @param {number} intervalId interval id
  244. */
  245. function applyReload(rootWindow, intervalId) {
  246. clearInterval(intervalId);
  247. log.info("App updated. Reloading...");
  248. rootWindow.location.reload();
  249. }
  250. var search = self.location.search.toLowerCase();
  251. var allowToHot = search.indexOf("webpack-dev-server-hot=false") === -1;
  252. var allowToLiveReload = search.indexOf("webpack-dev-server-live-reload=false") === -1;
  253. if (hot && allowToHot) {
  254. log.info("App hot update...");
  255. if (typeof EventTarget !== "undefined" && hotEmitter instanceof EventTarget) {
  256. var event = new CustomEvent("webpackHotUpdate", {
  257. detail: {
  258. currentHash: currentStatus.currentHash
  259. },
  260. bubbles: true,
  261. cancelable: false
  262. });
  263. hotEmitter.dispatchEvent(event);
  264. } else {
  265. hotEmitter.emit("webpackHotUpdate", currentStatus.currentHash);
  266. }
  267. if (typeof self !== "undefined" && self.window) {
  268. // broadcast update to window
  269. self.postMessage("webpackHotUpdate".concat(currentStatus.currentHash), "*");
  270. }
  271. }
  272. // allow refreshing the page only if liveReload isn't disabled
  273. else if (liveReload && allowToLiveReload) {
  274. /** @type {Window} */
  275. var rootWindow = self;
  276. // use parent window for reload (in case we're in an iframe with no valid src)
  277. var intervalId = self.setInterval(function () {
  278. if (rootWindow.location.protocol !== "about:") {
  279. // reload immediately if protocol is valid
  280. applyReload(rootWindow, intervalId);
  281. } else {
  282. rootWindow = rootWindow.parent;
  283. if (rootWindow.parent === rootWindow) {
  284. // if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
  285. applyReload(rootWindow, intervalId);
  286. }
  287. }
  288. });
  289. }
  290. };
  291. var ansiRegex = new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|"), "g");
  292. /**
  293. * Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string.
  294. * Adapted from code originally released by Sindre Sorhus
  295. * Licensed the MIT License
  296. * @param {string} string string
  297. * @returns {string} string without ansi
  298. */
  299. var stripAnsi = function stripAnsi(string) {
  300. if (typeof string !== "string") {
  301. throw new TypeError("Expected a `string`, got `".concat(_typeof(string), "`"));
  302. }
  303. return string.replace(ansiRegex, "");
  304. };
  305. var onSocketMessage = {
  306. hot: function hot() {
  307. if (parsedResourceQuery.hot === "false") {
  308. return;
  309. }
  310. options.hot = true;
  311. },
  312. liveReload: function liveReload() {
  313. if (parsedResourceQuery["live-reload"] === "false") {
  314. return;
  315. }
  316. options.liveReload = true;
  317. },
  318. invalid: function invalid() {
  319. log.info("App updated. Recompiling...");
  320. // Fixes #1042. overlay doesn't clear if errors are fixed but warnings remain.
  321. if (options.overlay) {
  322. overlay.send({
  323. type: "DISMISS"
  324. });
  325. }
  326. sendMessage("Invalid");
  327. },
  328. /**
  329. * @param {string} hash hash
  330. */
  331. hash: function hash(_hash) {
  332. status.previousHash = status.currentHash;
  333. status.currentHash = _hash;
  334. },
  335. logging: setAllLogLevel,
  336. /**
  337. * @param {boolean} value overlay value
  338. */
  339. overlay: function overlay(value) {
  340. if (typeof document === "undefined") {
  341. return;
  342. }
  343. options.overlay = value;
  344. decodeOverlayOptions(options.overlay);
  345. },
  346. /**
  347. * @param {number} value reconnect value
  348. */
  349. reconnect: function reconnect(value) {
  350. if (parsedResourceQuery.reconnect === "false") {
  351. return;
  352. }
  353. options.reconnect = value;
  354. },
  355. /**
  356. * @param {boolean} value progress value
  357. */
  358. progress: function progress(value) {
  359. options.progress = value;
  360. },
  361. /**
  362. * @param {{ pluginName?: string, percent: string, msg: string }} data date with progress
  363. */
  364. "progress-update": function progressUpdate(data) {
  365. if (options.progress) {
  366. log.info("".concat(data.pluginName ? "[".concat(data.pluginName, "] ") : "").concat(data.percent, "% - ").concat(data.msg, "."));
  367. }
  368. if (isProgressSupported() && typeof options.progress === "string") {
  369. var progress = document.querySelector("wds-progress");
  370. if (!progress) {
  371. defineProgressElement();
  372. progress = document.createElement("wds-progress");
  373. document.body.appendChild(progress);
  374. }
  375. progress.setAttribute("progress", data.percent);
  376. progress.setAttribute("type", options.progress);
  377. }
  378. sendMessage("Progress", data);
  379. },
  380. "still-ok": function stillOk() {
  381. log.info("Nothing changed.");
  382. if (options.overlay) {
  383. overlay.send({
  384. type: "DISMISS"
  385. });
  386. }
  387. sendMessage("StillOk");
  388. },
  389. ok: function ok() {
  390. sendMessage("Ok");
  391. if (options.overlay) {
  392. overlay.send({
  393. type: "DISMISS"
  394. });
  395. }
  396. reloadApp(options, status);
  397. },
  398. /**
  399. * @param {string} file changed file
  400. */
  401. "static-changed": function staticChanged(file) {
  402. log.info("".concat(file ? "\"".concat(file, "\"") : "Content", " from static directory was changed. Reloading..."));
  403. self.location.reload();
  404. },
  405. /**
  406. * @param {Error[]} warnings warnings
  407. * @param {{ preventReloading: boolean }=} params extra params
  408. */
  409. warnings: function warnings(_warnings, params) {
  410. log.warn("Warnings while compiling.");
  411. var printableWarnings = _warnings.map(function (error) {
  412. var _formatProblem = formatProblem("warning", error),
  413. header = _formatProblem.header,
  414. body = _formatProblem.body;
  415. return "".concat(header, "\n").concat(stripAnsi(body));
  416. });
  417. sendMessage("Warnings", printableWarnings);
  418. for (var i = 0; i < printableWarnings.length; i++) {
  419. log.warn(printableWarnings[i]);
  420. }
  421. var overlayWarningsSetting = typeof options.overlay === "boolean" ? options.overlay : options.overlay && options.overlay.warnings;
  422. if (overlayWarningsSetting) {
  423. var warningsToDisplay = typeof overlayWarningsSetting === "function" ? _warnings.filter(overlayWarningsSetting) : _warnings;
  424. if (warningsToDisplay.length) {
  425. overlay.send({
  426. type: "BUILD_ERROR",
  427. level: "warning",
  428. messages: _warnings
  429. });
  430. }
  431. }
  432. if (params && params.preventReloading) {
  433. return;
  434. }
  435. reloadApp(options, status);
  436. },
  437. /**
  438. * @param {Error[]} errors errors
  439. */
  440. errors: function errors(_errors) {
  441. log.error("Errors while compiling. Reload prevented.");
  442. var printableErrors = _errors.map(function (error) {
  443. var _formatProblem2 = formatProblem("error", error),
  444. header = _formatProblem2.header,
  445. body = _formatProblem2.body;
  446. return "".concat(header, "\n").concat(stripAnsi(body));
  447. });
  448. sendMessage("Errors", printableErrors);
  449. for (var i = 0; i < printableErrors.length; i++) {
  450. log.error(printableErrors[i]);
  451. }
  452. var overlayErrorsSettings = typeof options.overlay === "boolean" ? options.overlay : options.overlay && options.overlay.errors;
  453. if (overlayErrorsSettings) {
  454. var errorsToDisplay = typeof overlayErrorsSettings === "function" ? _errors.filter(overlayErrorsSettings) : _errors;
  455. if (errorsToDisplay.length) {
  456. overlay.send({
  457. type: "BUILD_ERROR",
  458. level: "error",
  459. messages: _errors
  460. });
  461. }
  462. }
  463. },
  464. /**
  465. * @param {Error} error error
  466. */
  467. error: function error(_error) {
  468. log.error(_error);
  469. },
  470. close: function close() {
  471. log.info("Disconnected!");
  472. if (options.overlay) {
  473. overlay.send({
  474. type: "DISMISS"
  475. });
  476. }
  477. sendMessage("Close");
  478. }
  479. };
  480. /**
  481. * @param {{ protocol?: string, auth?: string, hostname?: string, port?: string, pathname?: string, search?: string, hash?: string, slashes?: boolean }} objURL object URL
  482. * @returns {string} formatted url
  483. */
  484. var formatURL = function formatURL(objURL) {
  485. var protocol = objURL.protocol || "";
  486. if (protocol && protocol.slice(-1) !== ":") {
  487. protocol += ":";
  488. }
  489. var auth = objURL.auth || "";
  490. if (auth) {
  491. auth = encodeURIComponent(auth);
  492. auth = auth.replace(/%3A/i, ":");
  493. auth += "@";
  494. }
  495. var host = "";
  496. if (objURL.hostname) {
  497. host = auth + (objURL.hostname.indexOf(":") === -1 ? objURL.hostname : "[".concat(objURL.hostname, "]"));
  498. if (objURL.port) {
  499. host += ":".concat(objURL.port);
  500. }
  501. }
  502. var pathname = objURL.pathname || "";
  503. if (objURL.slashes) {
  504. host = "//".concat(host || "");
  505. if (pathname && pathname.charAt(0) !== "/") {
  506. pathname = "/".concat(pathname);
  507. }
  508. } else if (!host) {
  509. host = "";
  510. }
  511. var search = objURL.search || "";
  512. if (search && search.charAt(0) !== "?") {
  513. search = "?".concat(search);
  514. }
  515. var hash = objURL.hash || "";
  516. if (hash && hash.charAt(0) !== "#") {
  517. hash = "#".concat(hash);
  518. }
  519. pathname = pathname.replace(/[?#]/g,
  520. /**
  521. * @param {string} match matched string
  522. * @returns {string} encoded URI component
  523. */
  524. function (match) {
  525. return encodeURIComponent(match);
  526. });
  527. search = search.replace("#", "%23");
  528. return "".concat(protocol).concat(host).concat(pathname).concat(search).concat(hash);
  529. };
  530. /**
  531. * @param {ParsedURL} parsedURL parsed URL
  532. * @returns {string} socket URL
  533. */
  534. var createSocketURL = function createSocketURL(parsedURL) {
  535. var hostname = parsedURL.hostname;
  536. // Node.js module parses it as `::`
  537. // `new URL(urlString, [baseURLString])` parses it as '[::]'
  538. var isInAddrAny = hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]";
  539. // why do we need this check?
  540. // hostname n/a for file protocol (example, when using electron, ionic)
  541. // see: https://github.com/webpack/webpack-dev-server/pull/384
  542. if (isInAddrAny && self.location.hostname && self.location.protocol.indexOf("http") === 0) {
  543. hostname = self.location.hostname;
  544. }
  545. var socketURLProtocol = parsedURL.protocol || self.location.protocol;
  546. // When https is used in the app, secure web sockets are always necessary because the browser doesn't accept non-secure web sockets.
  547. if (socketURLProtocol === "auto:" || hostname && isInAddrAny && self.location.protocol === "https:") {
  548. socketURLProtocol = self.location.protocol;
  549. }
  550. socketURLProtocol = socketURLProtocol.replace(/^(?:http|.+-extension|file)/i, "ws");
  551. var socketURLAuth = "";
  552. // `new URL(urlString, [baseURLstring])` doesn't have `auth` property
  553. // Parse authentication credentials in case we need them
  554. if (parsedURL.username) {
  555. socketURLAuth = parsedURL.username;
  556. // Since HTTP basic authentication does not allow empty username,
  557. // we only include password if the username is not empty.
  558. if (parsedURL.password) {
  559. // Result: <username>:<password>
  560. socketURLAuth = socketURLAuth.concat(":", parsedURL.password);
  561. }
  562. }
  563. // In case the host is a raw IPv6 address, it can be enclosed in
  564. // the brackets as the brackets are needed in the final URL string.
  565. // Need to remove those as url.format blindly adds its own set of brackets
  566. // if the host string contains colons. That would lead to non-working
  567. // double brackets (e.g. [[::]]) host
  568. //
  569. // All of these web socket url params are optionally passed in through resourceQuery,
  570. // so we need to fall back to the default if they are not provided
  571. var socketURLHostname = (hostname || self.location.hostname || "localhost").replace(/^\[(.*)\]$/, "$1");
  572. var socketURLPort = parsedURL.port;
  573. if (!socketURLPort || socketURLPort === "0") {
  574. socketURLPort = self.location.port;
  575. }
  576. // If path is provided it'll be passed in via the resourceQuery as a
  577. // query param so it has to be parsed out of the querystring in order for the
  578. // client to open the socket to the correct location.
  579. var socketURLPathname = "/ws";
  580. if (parsedURL.pathname && !parsedURL.fromCurrentScript) {
  581. socketURLPathname = parsedURL.pathname;
  582. }
  583. return formatURL({
  584. protocol: socketURLProtocol,
  585. auth: socketURLAuth,
  586. hostname: socketURLHostname,
  587. port: socketURLPort,
  588. pathname: socketURLPathname,
  589. slashes: true
  590. });
  591. };
  592. var socketURL = createSocketURL(parsedResourceQuery);
  593. socket(socketURL, onSocketMessage, options.reconnect);
  594. export { createSocketURL, getCurrentScriptSource, parseURL };