client.mjs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. import "@vite/env";
  2. //#region ../../node_modules/.pnpm/nanoid@5.1.16/node_modules/nanoid/non-secure/index.js
  3. let urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
  4. let nanoid = (size = 21) => {
  5. let id = "";
  6. let i = size | 0;
  7. while (i-- > 0) id += urlAlphabet[Math.random() * 64 | 0];
  8. return id;
  9. };
  10. //#endregion
  11. //#region src/shared/constants.ts
  12. /**
  13. * Prefix for resolved Ids that are not valid browser import specifiers
  14. */
  15. const VALID_ID_PREFIX = `/@id/`;
  16. /**
  17. * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
  18. * module ID with `\0`, a convention from the rollup ecosystem.
  19. * This prevents other plugins from trying to process the id (like node resolution),
  20. * and core features like sourcemaps can use this info to differentiate between
  21. * virtual modules and regular files.
  22. * `\0` is not a permitted char in import URLs so we have to replace them during
  23. * import analysis. The id will be decoded back before entering the plugins pipeline.
  24. * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
  25. * modules in the browser end up encoded as `/@id/__x00__{id}`
  26. */
  27. const NULL_BYTE_PLACEHOLDER = `__x00__`;
  28. let SOURCEMAPPING_URL = "sourceMa";
  29. SOURCEMAPPING_URL += "ppingURL";
  30. typeof process !== "undefined" && process.platform;
  31. /**
  32. * Prepend `/@id/` and replace null byte so the id is URL-safe.
  33. * This is prepended to resolved ids that are not valid browser
  34. * import specifiers by the importAnalysis plugin.
  35. */
  36. function wrapId(id) {
  37. return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
  38. }
  39. (async function() {}).constructor;
  40. function promiseWithResolvers() {
  41. let resolve;
  42. let reject;
  43. return {
  44. promise: new Promise((_resolve, _reject) => {
  45. resolve = _resolve;
  46. reject = _reject;
  47. }),
  48. resolve,
  49. reject
  50. };
  51. }
  52. //#endregion
  53. //#region src/shared/moduleRunnerTransport.ts
  54. function reviveInvokeError(e) {
  55. const error = new Error(e.message || "Unknown invoke error");
  56. Object.assign(error, e, { runnerError: /* @__PURE__ */ new Error("RunnerError") });
  57. return error;
  58. }
  59. const createInvokeableTransport = (transport) => {
  60. if (transport.invoke) return {
  61. ...transport,
  62. async invoke(name, data) {
  63. const result = await transport.invoke({
  64. type: "custom",
  65. event: "vite:invoke",
  66. data: {
  67. id: "send",
  68. name,
  69. data
  70. }
  71. });
  72. if ("error" in result) throw reviveInvokeError(result.error);
  73. return result.result;
  74. }
  75. };
  76. if (!transport.send || !transport.connect) throw new Error("transport must implement send and connect when invoke is not implemented");
  77. const rpcPromises = /* @__PURE__ */ new Map();
  78. return {
  79. ...transport,
  80. connect({ onMessage, onDisconnection }) {
  81. return transport.connect({
  82. onMessage(payload) {
  83. if (payload.type === "custom" && payload.event === "vite:invoke") {
  84. const data = payload.data;
  85. if (data.id.startsWith("response:")) {
  86. const invokeId = data.id.slice(9);
  87. const promise = rpcPromises.get(invokeId);
  88. if (!promise) return;
  89. if (promise.timeoutId) clearTimeout(promise.timeoutId);
  90. rpcPromises.delete(invokeId);
  91. const { error, result } = data.data;
  92. if (error) promise.reject(error);
  93. else promise.resolve(result);
  94. return;
  95. }
  96. }
  97. onMessage(payload);
  98. },
  99. onDisconnection
  100. });
  101. },
  102. disconnect() {
  103. rpcPromises.forEach((promise) => {
  104. promise.reject(/* @__PURE__ */ new Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
  105. });
  106. rpcPromises.clear();
  107. return transport.disconnect?.();
  108. },
  109. send(data) {
  110. return transport.send(data);
  111. },
  112. async invoke(name, data) {
  113. const promiseId = nanoid();
  114. const wrappedData = {
  115. type: "custom",
  116. event: "vite:invoke",
  117. data: {
  118. name,
  119. id: `send:${promiseId}`,
  120. data
  121. }
  122. };
  123. const sendPromise = transport.send(wrappedData);
  124. const { promise, resolve, reject } = promiseWithResolvers();
  125. const timeout = transport.timeout ?? 6e4;
  126. let timeoutId;
  127. if (timeout > 0) {
  128. timeoutId = setTimeout(() => {
  129. rpcPromises.delete(promiseId);
  130. reject(/* @__PURE__ */ new Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
  131. }, timeout);
  132. timeoutId?.unref?.();
  133. }
  134. rpcPromises.set(promiseId, {
  135. resolve,
  136. reject,
  137. name,
  138. timeoutId
  139. });
  140. if (sendPromise) sendPromise.catch((err) => {
  141. clearTimeout(timeoutId);
  142. rpcPromises.delete(promiseId);
  143. reject(err);
  144. });
  145. try {
  146. return await promise;
  147. } catch (err) {
  148. throw reviveInvokeError(err);
  149. }
  150. }
  151. };
  152. };
  153. const normalizeModuleRunnerTransport = (transport) => {
  154. const invokeableTransport = createInvokeableTransport(transport);
  155. let isConnected = !invokeableTransport.connect;
  156. let connectingPromise;
  157. return {
  158. ...transport,
  159. ...invokeableTransport.connect ? { async connect(onMessage) {
  160. if (isConnected) return;
  161. if (connectingPromise) {
  162. await connectingPromise;
  163. return;
  164. }
  165. const maybePromise = invokeableTransport.connect({
  166. onMessage: onMessage ?? (() => {}),
  167. onDisconnection() {
  168. isConnected = false;
  169. }
  170. });
  171. if (maybePromise) {
  172. connectingPromise = maybePromise;
  173. await connectingPromise;
  174. connectingPromise = void 0;
  175. }
  176. isConnected = true;
  177. } } : {},
  178. ...invokeableTransport.disconnect ? { async disconnect() {
  179. if (!isConnected) return;
  180. if (connectingPromise) await connectingPromise;
  181. isConnected = false;
  182. await invokeableTransport.disconnect();
  183. } } : {},
  184. async send(data) {
  185. if (!invokeableTransport.send) return;
  186. if (!isConnected) {
  187. if (connectingPromise) await connectingPromise;
  188. else throw new SendBeforeConnectError("send was called before connect");
  189. }
  190. await invokeableTransport.send(data);
  191. },
  192. async invoke(name, data) {
  193. if (!isConnected) {
  194. if (connectingPromise) await connectingPromise;
  195. else throw new SendBeforeConnectError("invoke was called before connect");
  196. }
  197. return invokeableTransport.invoke(name, data);
  198. }
  199. };
  200. };
  201. var SendBeforeConnectError = class extends Error {
  202. constructor(message) {
  203. super(message);
  204. this.name = "SendBeforeConnectError";
  205. }
  206. };
  207. const createWebSocketModuleRunnerTransport = (options) => {
  208. const pingInterval = options.pingInterval ?? 3e4;
  209. let ws;
  210. let pingIntervalId;
  211. return {
  212. async connect({ onMessage, onDisconnection }) {
  213. const socket = options.createConnection();
  214. socket.addEventListener("message", ({ data }) => {
  215. onMessage(JSON.parse(data));
  216. });
  217. let isOpened = socket.readyState === socket.OPEN;
  218. if (!isOpened) await new Promise((resolve, reject) => {
  219. socket.addEventListener("open", () => {
  220. isOpened = true;
  221. resolve();
  222. }, { once: true });
  223. socket.addEventListener("close", () => {
  224. if (!isOpened) {
  225. reject(/* @__PURE__ */ new Error("WebSocket closed without opened."));
  226. return;
  227. }
  228. onMessage({
  229. type: "custom",
  230. event: "vite:ws:disconnect",
  231. data: { webSocket: socket }
  232. });
  233. onDisconnection();
  234. });
  235. });
  236. onMessage({
  237. type: "custom",
  238. event: "vite:ws:connect",
  239. data: { webSocket: socket }
  240. });
  241. ws = socket;
  242. pingIntervalId = setInterval(() => {
  243. if (socket.readyState === socket.OPEN) socket.send(JSON.stringify({ type: "ping" }));
  244. }, pingInterval);
  245. },
  246. disconnect() {
  247. clearInterval(pingIntervalId);
  248. ws?.close();
  249. },
  250. send(data) {
  251. ws.send(JSON.stringify(data));
  252. }
  253. };
  254. };
  255. //#endregion
  256. //#region src/shared/pretty-format.ts
  257. const DEFAULT_OPTIONS = {
  258. maxDepth: 3,
  259. maxWidth: 100
  260. };
  261. const objectToString = Object.prototype.toString;
  262. const errorToString = Error.prototype.toString;
  263. const identifierRE = /^[a-z_$][\w$]*$/i;
  264. function prettyFormat(value, options = {}) {
  265. return printer(value, {
  266. ...DEFAULT_OPTIONS,
  267. ...options
  268. }, 0, []);
  269. }
  270. function printer(value, config, depth, refs) {
  271. return printBasicValue(value) ?? printComplexValue(value, config, depth, refs);
  272. }
  273. function printBasicValue(value) {
  274. if (value == null) return String(value);
  275. if (typeof value === "string") return JSON.stringify(value);
  276. if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
  277. if (typeof value === "bigint") return `${value}n`;
  278. if (typeof value === "boolean" || typeof value === "symbol") return String(value);
  279. if (typeof value === "function") return value.name ? `[Function: ${value.name}]` : "[Function]";
  280. const type = objectToString.call(value);
  281. if (type === "[object Date]") return Number.isNaN(+value) ? "Date { NaN }" : value.toISOString();
  282. if (type === "[object Error]" || value instanceof Error) return `[${errorToString.call(value)}]`;
  283. }
  284. function printComplexValue(value, config, depth, refs) {
  285. if (refs.includes(value)) return "[Circular]";
  286. refs = [...refs, value];
  287. const hitMaxDepth = ++depth > config.maxDepth;
  288. if (Array.isArray(value)) return hitMaxDepth ? "[Array]" : `[${printListItems(value, config, depth, refs)}]`;
  289. return hitMaxDepth ? "[Object]" : `{${printObjectProperties(value, config, depth, refs)}}`;
  290. }
  291. function printListItems(value, config, depth, refs) {
  292. const width = Math.min(value.length, config.maxWidth);
  293. const result = [];
  294. for (let i = 0; i < width; i++) result.push(i in value ? printer(value[i], config, depth, refs) : "");
  295. if (width < value.length) result.push(`…(${value.length - width})`);
  296. return withSpacing(result);
  297. }
  298. function printObjectProperties(value, config, depth, refs) {
  299. const keys = Object.keys(value);
  300. const width = Math.min(keys.length, config.maxWidth);
  301. const result = [];
  302. for (let i = 0; i < width; i++) {
  303. const key = keys[i];
  304. const name = key !== "__proto__" && identifierRE.test(key) ? key : JSON.stringify(key);
  305. result.push(`${name}: ${printer(value[key], config, depth, refs)}`);
  306. }
  307. if (width < keys.length) result.push(`…(${keys.length - width})`);
  308. return withSpacing(result);
  309. }
  310. function withSpacing(values) {
  311. return values.length === 0 ? "" : ` ${values.join(", ")} `;
  312. }
  313. //#endregion
  314. //#region src/shared/forwardConsole.ts
  315. function setupForwardConsoleHandler(transport, options, console = globalThis.console) {
  316. if (!options.enabled) return;
  317. async function sendError(type, error) {
  318. await transport.send({
  319. type: "custom",
  320. event: "vite:forward-console",
  321. data: {
  322. type,
  323. data: {
  324. name: error?.name || "Unknown Error",
  325. message: error?.message || String(error),
  326. stack: error?.stack
  327. }
  328. }
  329. });
  330. }
  331. async function sendLog(level, args) {
  332. try {
  333. await transport.send({
  334. type: "custom",
  335. event: "vite:forward-console",
  336. data: {
  337. type: "log",
  338. data: {
  339. level,
  340. message: truncateConsoleMessage(formatConsoleArgs(args))
  341. }
  342. }
  343. });
  344. } catch (err) {
  345. try {
  346. await sendError("unhandled-rejection", err);
  347. } catch (err) {
  348. if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
  349. }
  350. }
  351. }
  352. const originalConsoleError = console.error;
  353. for (const level of options.logLevels) {
  354. const original = console[level];
  355. if (typeof original !== "function") continue;
  356. console[level] = (...args) => {
  357. original(...args);
  358. sendLog(level, args);
  359. };
  360. }
  361. if (options.unhandledErrors && typeof window !== "undefined") {
  362. window.addEventListener("error", async (event) => {
  363. const error = event.error ?? (event.message ? new Error(event.message) : event);
  364. try {
  365. await sendError("error", error);
  366. } catch (err) {
  367. if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
  368. }
  369. });
  370. window.addEventListener("unhandledrejection", async (event) => {
  371. try {
  372. await sendError("unhandled-rejection", event.reason);
  373. } catch (err) {
  374. if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
  375. }
  376. });
  377. }
  378. }
  379. function formatConsoleArgs(args) {
  380. if (args.length === 0) return "";
  381. if (typeof args[0] !== "string") return args.map((arg) => stringifyConsoleArg(arg)).join(" ");
  382. const len = args.length;
  383. let i = 1;
  384. let message = args[0].replace(/%[sdjifoOc%]/g, (specifier) => {
  385. if (specifier === "%%") return "%";
  386. if (i >= len) return specifier;
  387. const arg = args[i++];
  388. switch (specifier) {
  389. case "%s":
  390. if (typeof arg === "bigint") return `${arg.toString()}n`;
  391. return typeof arg === "object" && arg != null ? stringifyConsoleArg(arg) : String(arg);
  392. case "%d":
  393. if (typeof arg === "bigint") return `${arg.toString()}n`;
  394. if (typeof arg === "symbol") return "NaN";
  395. return Number(arg).toString();
  396. case "%i":
  397. if (typeof arg === "bigint") return `${arg.toString()}n`;
  398. return Number.parseInt(String(arg), 10).toString();
  399. case "%f": return Number.parseFloat(String(arg)).toString();
  400. case "%o":
  401. case "%O": return stringifyConsoleArg(arg);
  402. case "%j": try {
  403. return JSON.stringify(arg) ?? "undefined";
  404. } catch {
  405. return "[Circular]";
  406. }
  407. case "%c": return "";
  408. default: return specifier;
  409. }
  410. });
  411. for (let arg = args[i]; i < len; arg = args[++i]) if (arg == null || typeof arg !== "object") message += ` ${typeof arg === "symbol" ? arg.toString() : String(arg)}`;
  412. else message += ` ${stringifyConsoleArg(arg)}`;
  413. return message;
  414. }
  415. function stringifyConsoleArg(value) {
  416. if (typeof value === "string") return value;
  417. if (value instanceof Error) return value.stack || `${value.name}: ${value.message}`;
  418. try {
  419. return prettyFormat(value);
  420. } catch {
  421. return String(value);
  422. }
  423. }
  424. const MAX_CONSOLE_MESSAGE_LENGTH = 1e4;
  425. function truncateConsoleMessage(message) {
  426. if (message.length <= MAX_CONSOLE_MESSAGE_LENGTH) return message;
  427. let end = 9999;
  428. if (isHighSurrogate(message[end - 1])) end--;
  429. return `${message.slice(0, end)}…`;
  430. }
  431. function isHighSurrogate(value) {
  432. return value >= "\ud800" && value <= "\udbff";
  433. }
  434. //#endregion
  435. //#region \0@oxc-project+runtime@0.151.0/helpers/esm/typeof.js
  436. function _typeof(o) {
  437. "@babel/helpers - typeof";
  438. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
  439. return typeof o;
  440. } : function(o) {
  441. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  442. }, _typeof(o);
  443. }
  444. //#endregion
  445. //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPrimitive.js
  446. function toPrimitive(t, r) {
  447. if ("object" != _typeof(t) || !t) return t;
  448. var e = t[Symbol.toPrimitive];
  449. if (void 0 !== e) {
  450. var i = e.call(t, r || "default");
  451. if ("object" != _typeof(i)) return i;
  452. throw new TypeError("@@toPrimitive must return a primitive value.");
  453. }
  454. return ("string" === r ? String : Number)(t);
  455. }
  456. //#endregion
  457. //#region \0@oxc-project+runtime@0.151.0/helpers/esm/toPropertyKey.js
  458. function toPropertyKey(t) {
  459. var i = toPrimitive(t, "string");
  460. return "symbol" == _typeof(i) ? i : i + "";
  461. }
  462. //#endregion
  463. //#region \0@oxc-project+runtime@0.151.0/helpers/esm/defineProperty.js
  464. function _defineProperty(e, r, t) {
  465. return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  466. value: t,
  467. enumerable: !0,
  468. configurable: !0,
  469. writable: !0
  470. }) : e[r] = t, e;
  471. }
  472. //#endregion
  473. //#region src/shared/hmr.ts
  474. var HMRContext = class {
  475. constructor(hmrClient, ownerPath) {
  476. this.hmrClient = hmrClient;
  477. this.ownerPath = ownerPath;
  478. _defineProperty(this, "newListeners", void 0);
  479. if (!hmrClient.dataMap.has(ownerPath)) hmrClient.dataMap.set(ownerPath, {});
  480. const mod = hmrClient.hotModulesMap.get(ownerPath);
  481. if (mod) mod.callbacks = [];
  482. const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
  483. if (staleListeners) for (const [event, staleFns] of staleListeners) {
  484. const listeners = hmrClient.customListenersMap.get(event);
  485. if (listeners) hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
  486. }
  487. this.newListeners = /* @__PURE__ */ new Map();
  488. hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
  489. }
  490. get data() {
  491. return this.hmrClient.dataMap.get(this.ownerPath);
  492. }
  493. accept(deps, callback) {
  494. if (typeof deps === "function" || !deps) this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
  495. else if (typeof deps === "string") this.acceptDeps([deps], ([mod]) => callback?.(mod));
  496. else if (Array.isArray(deps)) this.acceptDeps(deps, callback);
  497. else throw new Error(`invalid hot.accept() usage.`);
  498. }
  499. acceptExports(_, callback) {
  500. this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
  501. }
  502. dispose(cb) {
  503. this.hmrClient.disposeMap.set(this.ownerPath, cb);
  504. }
  505. prune(cb) {
  506. this.hmrClient.pruneMap.set(this.ownerPath, cb);
  507. }
  508. decline() {}
  509. invalidate(message) {
  510. const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
  511. this.hmrClient.notifyListeners("vite:invalidate", {
  512. path: this.ownerPath,
  513. message,
  514. firstInvalidatedBy
  515. });
  516. this.send("vite:invalidate", {
  517. path: this.ownerPath,
  518. message,
  519. firstInvalidatedBy
  520. });
  521. this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
  522. }
  523. on(event, cb) {
  524. const addToMap = (map) => {
  525. const existing = map.get(event) || [];
  526. existing.push(cb);
  527. map.set(event, existing);
  528. };
  529. addToMap(this.hmrClient.customListenersMap);
  530. addToMap(this.newListeners);
  531. }
  532. off(event, cb) {
  533. const removeFromMap = (map) => {
  534. const existing = map.get(event);
  535. if (existing === void 0) return;
  536. const pruned = existing.filter((l) => l !== cb);
  537. if (pruned.length === 0) {
  538. map.delete(event);
  539. return;
  540. }
  541. map.set(event, pruned);
  542. };
  543. removeFromMap(this.hmrClient.customListenersMap);
  544. removeFromMap(this.newListeners);
  545. }
  546. send(event, data) {
  547. this.hmrClient.send({
  548. type: "custom",
  549. event,
  550. data
  551. });
  552. }
  553. acceptDeps(deps, callback = () => {}) {
  554. const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
  555. id: this.ownerPath,
  556. callbacks: []
  557. };
  558. mod.callbacks.push({
  559. deps,
  560. fn: callback
  561. });
  562. this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
  563. }
  564. };
  565. var HMRClient = class {
  566. constructor(logger, transport, importUpdatedModule) {
  567. this.logger = logger;
  568. this.transport = transport;
  569. this.importUpdatedModule = importUpdatedModule;
  570. _defineProperty(this, "hotModulesMap", /* @__PURE__ */ new Map());
  571. _defineProperty(this, "disposeMap", /* @__PURE__ */ new Map());
  572. _defineProperty(this, "pruneMap", /* @__PURE__ */ new Map());
  573. _defineProperty(this, "dataMap", /* @__PURE__ */ new Map());
  574. _defineProperty(this, "customListenersMap", /* @__PURE__ */ new Map());
  575. _defineProperty(this, "ctxToListenersMap", /* @__PURE__ */ new Map());
  576. _defineProperty(this, "currentFirstInvalidatedBy", void 0);
  577. _defineProperty(this, "updateQueue", []);
  578. _defineProperty(this, "pendingUpdateQueue", false);
  579. }
  580. async notifyListeners(event, data) {
  581. const cbs = this.customListenersMap.get(event);
  582. if (cbs) await Promise.allSettled(cbs.map((cb) => cb(data)));
  583. }
  584. send(payload) {
  585. this.transport.send(payload).catch((err) => {
  586. this.logger.error(err);
  587. });
  588. }
  589. clear() {
  590. this.hotModulesMap.clear();
  591. this.disposeMap.clear();
  592. this.pruneMap.clear();
  593. this.dataMap.clear();
  594. this.customListenersMap.clear();
  595. this.ctxToListenersMap.clear();
  596. }
  597. async prunePaths(paths) {
  598. try {
  599. await Promise.all(paths.map((path) => {
  600. const disposer = this.disposeMap.get(path);
  601. if (disposer) return disposer(this.dataMap.get(path));
  602. }));
  603. await Promise.all(paths.map((path) => {
  604. const fn = this.pruneMap.get(path);
  605. if (fn) return fn(this.dataMap.get(path));
  606. }));
  607. } finally {
  608. paths.forEach((path) => this.dataMap.delete(path));
  609. }
  610. }
  611. warnFailedUpdate(err, path) {
  612. if (!(err instanceof Error) || !err.message.includes("fetch")) this.logger.error(err);
  613. this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
  614. }
  615. /**
  616. * buffer multiple hot updates triggered by the same src change
  617. * so that they are invoked in the same order they were sent.
  618. * (otherwise the order may be inconsistent because of the http request round trip)
  619. */
  620. async queueUpdate(payload) {
  621. this.updateQueue.push(this.fetchUpdate(payload));
  622. if (!this.pendingUpdateQueue) {
  623. this.pendingUpdateQueue = true;
  624. await Promise.resolve();
  625. this.pendingUpdateQueue = false;
  626. const loading = [...this.updateQueue];
  627. this.updateQueue = [];
  628. (await Promise.all(loading)).forEach((fn) => fn && fn());
  629. }
  630. }
  631. async fetchUpdate(update) {
  632. const { path, acceptedPath, firstInvalidatedBy } = update;
  633. const mod = this.hotModulesMap.get(path);
  634. if (!mod) return;
  635. let fetchedModule;
  636. const isSelfUpdate = path === acceptedPath;
  637. const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
  638. if (isSelfUpdate || qualifiedCallbacks.length > 0) {
  639. const disposer = this.disposeMap.get(acceptedPath);
  640. if (disposer) await disposer(this.dataMap.get(acceptedPath));
  641. try {
  642. fetchedModule = await this.importUpdatedModule(update);
  643. } catch (e) {
  644. this.warnFailedUpdate(e, acceptedPath);
  645. }
  646. }
  647. return () => {
  648. try {
  649. this.currentFirstInvalidatedBy = firstInvalidatedBy;
  650. for (const { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
  651. const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
  652. this.logger.debug(`hot updated: ${loggedPath}`);
  653. } finally {
  654. this.currentFirstInvalidatedBy = void 0;
  655. }
  656. };
  657. }
  658. };
  659. //#endregion
  660. //#region src/shared/hmrHandler.ts
  661. function createHMRHandler(handler) {
  662. const queue = new Queue();
  663. return (payload) => queue.enqueue(() => handler(payload));
  664. }
  665. var Queue = class {
  666. constructor() {
  667. _defineProperty(this, "queue", []);
  668. _defineProperty(this, "pending", false);
  669. }
  670. enqueue(promise) {
  671. return new Promise((resolve, reject) => {
  672. this.queue.push({
  673. promise,
  674. resolve,
  675. reject
  676. });
  677. this.dequeue();
  678. });
  679. }
  680. dequeue() {
  681. if (this.pending) return false;
  682. const item = this.queue.shift();
  683. if (!item) return false;
  684. this.pending = true;
  685. item.promise().then(item.resolve).catch(item.reject).finally(() => {
  686. this.pending = false;
  687. this.dequeue();
  688. });
  689. return true;
  690. }
  691. };
  692. //#endregion
  693. //#region src/client/overlay.ts
  694. const hmrConfigName = __HMR_CONFIG_NAME__;
  695. const base$1 = __BASE__ || "/";
  696. const cspNonce = "document" in globalThis ? document.querySelector("meta[property=csp-nonce]")?.nonce : void 0;
  697. function h(e, attrs = {}, ...children) {
  698. const elem = document.createElement(e);
  699. for (const [k, v] of Object.entries(attrs)) if (v !== void 0) elem.setAttribute(k, v);
  700. elem.append(...children);
  701. return elem;
  702. }
  703. const templateStyle = `
  704. :host {
  705. position: fixed;
  706. top: 0;
  707. left: 0;
  708. width: 100%;
  709. height: 100%;
  710. z-index: 99999;
  711. --monospace: 'SFMono-Regular', Consolas,
  712. 'Liberation Mono', Menlo, Courier, monospace;
  713. --red: #ff5555;
  714. --yellow: #e2aa53;
  715. --purple: #cfa4ff;
  716. --cyan: #2dd9da;
  717. --dim: #c9c9c9;
  718. --window-background: #181818;
  719. --window-color: #d8d8d8;
  720. }
  721. .backdrop {
  722. position: fixed;
  723. z-index: 99999;
  724. top: 0;
  725. left: 0;
  726. width: 100%;
  727. height: 100%;
  728. overflow-y: scroll;
  729. margin: 0;
  730. background: rgba(0, 0, 0, 0.66);
  731. }
  732. .window {
  733. font-family: var(--monospace);
  734. line-height: 1.5;
  735. max-width: 80vw;
  736. color: var(--window-color);
  737. box-sizing: border-box;
  738. margin: 30px auto;
  739. padding: 2.5vh 4vw;
  740. position: relative;
  741. background: var(--window-background);
  742. border-radius: 6px 6px 8px 8px;
  743. box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
  744. overflow: hidden;
  745. border-top: 8px solid var(--red);
  746. direction: ltr;
  747. text-align: left;
  748. }
  749. pre {
  750. font-family: var(--monospace);
  751. font-size: 16px;
  752. margin-top: 0;
  753. margin-bottom: 1em;
  754. overflow-x: scroll;
  755. scrollbar-width: none;
  756. }
  757. pre::-webkit-scrollbar {
  758. display: none;
  759. }
  760. pre.frame::-webkit-scrollbar {
  761. display: block;
  762. height: 5px;
  763. }
  764. pre.frame::-webkit-scrollbar-thumb {
  765. background: #999;
  766. border-radius: 5px;
  767. }
  768. pre.frame {
  769. scrollbar-width: thin;
  770. }
  771. .message {
  772. line-height: 1.3;
  773. font-weight: 400;
  774. white-space: pre-wrap;
  775. }
  776. .message-body {
  777. color: var(--red);
  778. }
  779. .plugin {
  780. color: var(--purple);
  781. }
  782. .file {
  783. color: var(--cyan);
  784. margin-bottom: 0;
  785. white-space: pre-wrap;
  786. word-break: break-all;
  787. }
  788. .frame {
  789. color: var(--yellow);
  790. }
  791. .stack {
  792. font-size: 13px;
  793. color: var(--dim);
  794. }
  795. .tip {
  796. font-size: 13px;
  797. color: #999;
  798. border-top: 1px dotted #999;
  799. padding-top: 13px;
  800. line-height: 1.8;
  801. }
  802. code {
  803. font-size: 13px;
  804. font-family: var(--monospace);
  805. color: var(--yellow);
  806. }
  807. .file-link {
  808. text-decoration: underline;
  809. cursor: pointer;
  810. }
  811. kbd {
  812. line-height: 1.5;
  813. font-family: ui-monospace, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  814. font-size: 0.75rem;
  815. font-weight: 700;
  816. background-color: rgb(38, 40, 44);
  817. color: rgb(166, 167, 171);
  818. padding: 0.15rem 0.3rem;
  819. border-radius: 0.25rem;
  820. border-width: 0.0625rem 0.0625rem 0.1875rem;
  821. border-style: solid;
  822. border-color: rgb(54, 57, 64);
  823. border-image: initial;
  824. }
  825. `;
  826. const createTemplate = () => h("div", {
  827. class: "backdrop",
  828. part: "backdrop"
  829. }, h("div", {
  830. class: "window",
  831. part: "window"
  832. }, h("pre", {
  833. class: "message",
  834. part: "message"
  835. }, h("span", {
  836. class: "plugin",
  837. part: "plugin"
  838. }), h("span", {
  839. class: "message-body",
  840. part: "message-body"
  841. })), h("pre", {
  842. class: "file",
  843. part: "file"
  844. }), h("pre", {
  845. class: "frame",
  846. part: "frame"
  847. }), h("pre", {
  848. class: "stack",
  849. part: "stack"
  850. }), h("div", {
  851. class: "tip",
  852. part: "tip"
  853. }, "Click outside, press ", h("kbd", {}, "Esc"), " key, or fix the code to dismiss.", h("br"), "You can also disable this overlay by setting ", h("code", { part: "config-option-name" }, "server.hmr.overlay"), " to ", h("code", { part: "config-option-value" }, "false"), " in ", h("code", { part: "config-file-name" }, hmrConfigName), ".")), h("style", { nonce: cspNonce }, templateStyle));
  854. const fileRE = /(?:file:\/\/)?(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
  855. const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
  856. const { HTMLElement = class {} } = globalThis;
  857. var ErrorOverlay = class extends HTMLElement {
  858. constructor(err, links = true) {
  859. super();
  860. this.root = this.attachShadow({ mode: "open" });
  861. this.root.appendChild(createTemplate());
  862. codeframeRE.lastIndex = 0;
  863. const hasFrame = err.frame && codeframeRE.test(err.frame);
  864. const message = hasFrame ? err.message.replace(codeframeRE, "") : err.message;
  865. if (err.plugin) this.text(".plugin", `[plugin:${err.plugin}] `);
  866. this.text(".message-body", message.trim());
  867. const [file] = (err.loc?.file || err.id || "unknown file").split(`?`);
  868. if (err.loc) this.text(".file", `${file}:${err.loc.line}:${err.loc.column}`, links);
  869. else if (err.id) this.text(".file", file);
  870. if (hasFrame) this.text(".frame", err.frame.trim());
  871. this.text(".stack", err.stack, links);
  872. this.root.querySelector(".window").addEventListener("click", (e) => {
  873. e.stopPropagation();
  874. });
  875. this.addEventListener("click", () => {
  876. this.close();
  877. });
  878. this.closeOnEsc = (e) => {
  879. if (e.key === "Escape" || e.code === "Escape") this.close();
  880. };
  881. document.addEventListener("keydown", this.closeOnEsc);
  882. }
  883. text(selector, text, linkFiles = false) {
  884. const el = this.root.querySelector(selector);
  885. if (!linkFiles) el.textContent = text;
  886. else {
  887. let curIndex = 0;
  888. let match;
  889. fileRE.lastIndex = 0;
  890. while (match = fileRE.exec(text)) {
  891. const { 0: file, index } = match;
  892. const frag = text.slice(curIndex, index);
  893. el.appendChild(document.createTextNode(frag));
  894. const link = document.createElement("a");
  895. link.textContent = file;
  896. link.className = "file-link";
  897. link.onclick = () => {
  898. fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url));
  899. };
  900. el.appendChild(link);
  901. curIndex += frag.length + file.length;
  902. }
  903. if (curIndex < text.length) el.appendChild(document.createTextNode(text.slice(curIndex)));
  904. }
  905. }
  906. close() {
  907. this.parentNode?.removeChild(this);
  908. document.removeEventListener("keydown", this.closeOnEsc);
  909. }
  910. };
  911. const overlayId = "vite-error-overlay";
  912. const { customElements } = globalThis;
  913. if (customElements && !customElements.get("vite-error-overlay")) customElements.define(overlayId, ErrorOverlay);
  914. //#endregion
  915. //#region src/client/client.ts
  916. console.debug("[vite] connecting...");
  917. const importMetaUrl = new URL(import.meta.url);
  918. const serverHost = __SERVER_HOST__;
  919. const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === "https:" ? "wss" : "ws");
  920. const hmrPort = __HMR_PORT__;
  921. const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
  922. const directSocketHost = __HMR_DIRECT_TARGET__;
  923. const base = __BASE__ || "/";
  924. const hmrTimeout = __HMR_TIMEOUT__;
  925. const wsToken = __WS_TOKEN__;
  926. const forwardConsole = __SERVER_FORWARD_CONSOLE__;
  927. const transport = normalizeModuleRunnerTransport((() => {
  928. let wsTransport = createWebSocketModuleRunnerTransport({
  929. createConnection: () => new WebSocket(`${socketProtocol}://${socketHost}?token=${wsToken}`, "vite-hmr"),
  930. pingInterval: hmrTimeout
  931. });
  932. return {
  933. async connect(handlers) {
  934. try {
  935. await wsTransport.connect(handlers);
  936. } catch (e) {
  937. if (!hmrPort) {
  938. wsTransport = createWebSocketModuleRunnerTransport({
  939. createConnection: () => new WebSocket(`${socketProtocol}://${directSocketHost}?token=${wsToken}`, "vite-hmr"),
  940. pingInterval: hmrTimeout
  941. });
  942. try {
  943. await wsTransport.connect(handlers);
  944. console.info("[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error.");
  945. } catch (e) {
  946. if (e instanceof Error && e.message.includes("WebSocket closed without opened.")) {
  947. const currentScriptHostURL = new URL(import.meta.url);
  948. const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
  949. console.error(`[vite] failed to connect to websocket.
  950. your current setup:
  951. (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\nCheck out your Vite / network configuration and https://vite.dev/config/server-options.html#server-hmr .`);
  952. }
  953. }
  954. return;
  955. }
  956. console.error(`[vite] failed to connect to websocket (${e}). `);
  957. throw e;
  958. }
  959. },
  960. async disconnect() {
  961. await wsTransport.disconnect();
  962. },
  963. send(data) {
  964. wsTransport.send(data);
  965. }
  966. };
  967. })());
  968. let willUnload = false;
  969. if (typeof window !== "undefined") window.addEventListener?.("beforeunload", () => {
  970. willUnload = true;
  971. });
  972. function cleanUrl(pathname) {
  973. const url = new URL(pathname, "http://vite.dev");
  974. url.searchParams.delete("direct");
  975. return url.pathname + url.search;
  976. }
  977. let isFirstUpdate = true;
  978. const outdatedLinkTags = /* @__PURE__ */ new WeakSet();
  979. const debounceReload = (time) => {
  980. let timer;
  981. return () => {
  982. if (timer) {
  983. clearTimeout(timer);
  984. timer = null;
  985. }
  986. timer = setTimeout(() => {
  987. location.reload();
  988. }, time);
  989. };
  990. };
  991. const pageReload = debounceReload(20);
  992. function wrapIdIfNeeded(id) {
  993. return id[0] === "." || id[0] === "/" ? id : wrapId(id);
  994. }
  995. const hmrClient = new HMRClient({
  996. error: (err) => console.error("[vite]", err),
  997. debug: (...msg) => console.debug("[vite]", ...msg)
  998. }, transport, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport }) {
  999. const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`);
  1000. const browserPath = wrapIdIfNeeded(acceptedPathWithoutQuery);
  1001. const importPromise = import(
  1002. /* @vite-ignore */
  1003. base + browserPath.slice(1) + `?${explicitImportRequired ? "import&" : ""}t=${timestamp}${query ? `&${query}` : ""}`
  1004. );
  1005. if (isWithinCircularImport) importPromise.catch(() => {
  1006. console.info(`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`);
  1007. pageReload();
  1008. });
  1009. return await importPromise;
  1010. });
  1011. let bundledDevClient;
  1012. transport.connect(createHMRHandler(handleMessage));
  1013. setupForwardConsoleHandler(transport, forwardConsole);
  1014. function clearOverlayOrReloadOnFirstUpdate() {
  1015. if (hasDocument) {
  1016. if (isFirstUpdate && hasErrorOverlay()) {
  1017. location.reload();
  1018. return "reload";
  1019. }
  1020. if (enableOverlay) clearErrorOverlay();
  1021. isFirstUpdate = false;
  1022. }
  1023. return "continue";
  1024. }
  1025. async function handleMessage(payload) {
  1026. const activeHmrClient = hmrClient;
  1027. switch (payload.type) {
  1028. case "connected":
  1029. console.debug(`[vite] connected.`);
  1030. break;
  1031. case "bundled-dev-update":
  1032. bundledDevClient.handlePush(payload);
  1033. break;
  1034. case "update":
  1035. await activeHmrClient.notifyListeners("vite:beforeUpdate", payload);
  1036. if (clearOverlayOrReloadOnFirstUpdate() === "reload") return;
  1037. await Promise.all(payload.updates.map(async (update) => {
  1038. if (update.type === "js-update") return hmrClient.queueUpdate(update);
  1039. const { path, timestamp } = update;
  1040. const searchUrl = cleanUrl(path);
  1041. const el = Array.from(document.querySelectorAll("link")).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl));
  1042. if (!el) return;
  1043. const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes("?") ? "&" : "?"}t=${timestamp}`;
  1044. return new Promise((resolve) => {
  1045. const newLinkTag = el.cloneNode();
  1046. newLinkTag.href = new URL(newPath, el.href).href;
  1047. const removeOldEl = () => {
  1048. el.remove();
  1049. console.debug(`[vite] css hot updated: ${searchUrl}`);
  1050. resolve();
  1051. };
  1052. newLinkTag.addEventListener("load", removeOldEl);
  1053. newLinkTag.addEventListener("error", removeOldEl);
  1054. outdatedLinkTags.add(el);
  1055. el.after(newLinkTag);
  1056. });
  1057. }));
  1058. await activeHmrClient.notifyListeners("vite:afterUpdate", payload);
  1059. break;
  1060. case "custom":
  1061. await activeHmrClient.notifyListeners(payload.event, payload.data);
  1062. if (payload.event === "vite:ws:disconnect") {
  1063. if (hasDocument && !willUnload) {
  1064. console.log(`[vite] server connection lost. Polling for restart...`);
  1065. const socket = payload.data.webSocket;
  1066. const url = new URL(socket.url);
  1067. url.search = "";
  1068. await waitForSuccessfulPing(url.href);
  1069. location.reload();
  1070. }
  1071. }
  1072. break;
  1073. case "full-reload":
  1074. if (payload.ifFallback && !globalThis.__vite_is_fallback_page__) break;
  1075. await activeHmrClient.notifyListeners("vite:beforeFullReload", payload);
  1076. if (hasDocument) {
  1077. if (payload.path && payload.path.endsWith(".html")) {
  1078. const pagePath = decodeURI(location.pathname);
  1079. const payloadPath = base + payload.path.slice(1);
  1080. if (pagePath === payloadPath || payload.path === "/index.html" || pagePath.endsWith("/") && pagePath + "index.html" === payloadPath) pageReload();
  1081. return;
  1082. } else pageReload();
  1083. }
  1084. break;
  1085. case "prune":
  1086. await activeHmrClient.notifyListeners("vite:beforePrune", payload);
  1087. await activeHmrClient.prunePaths(payload.paths);
  1088. break;
  1089. case "error":
  1090. await activeHmrClient.notifyListeners("vite:error", payload);
  1091. if (hasDocument) {
  1092. const err = payload.err;
  1093. if (enableOverlay) createErrorOverlay(err);
  1094. else console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`);
  1095. }
  1096. break;
  1097. case "ping": break;
  1098. default: return payload;
  1099. }
  1100. }
  1101. const enableOverlay = __HMR_ENABLE_OVERLAY__;
  1102. const hasDocument = "document" in globalThis;
  1103. function createErrorOverlay(err) {
  1104. clearErrorOverlay();
  1105. const { customElements } = globalThis;
  1106. if (customElements) {
  1107. const ErrorOverlayConstructor = customElements.get(overlayId);
  1108. document.body.appendChild(new ErrorOverlayConstructor(err));
  1109. }
  1110. }
  1111. function clearErrorOverlay() {
  1112. document.querySelectorAll(overlayId).forEach((n) => n.close());
  1113. }
  1114. function hasErrorOverlay() {
  1115. return document.querySelectorAll(overlayId).length;
  1116. }
  1117. function waitForSuccessfulPing(socketUrl) {
  1118. if (typeof SharedWorker === "undefined") {
  1119. const visibilityManager = {
  1120. currentState: document.visibilityState,
  1121. listeners: /* @__PURE__ */ new Set()
  1122. };
  1123. const onVisibilityChange = () => {
  1124. visibilityManager.currentState = document.visibilityState;
  1125. for (const listener of visibilityManager.listeners) listener(visibilityManager.currentState);
  1126. };
  1127. document.addEventListener("visibilitychange", onVisibilityChange);
  1128. return waitForSuccessfulPingInternal(socketUrl, visibilityManager);
  1129. }
  1130. const blob = new Blob([
  1131. "\"use strict\";",
  1132. `const waitForSuccessfulPingInternal = ${waitForSuccessfulPingInternal.toString()};`,
  1133. `const fn = ${pingWorkerContentMain.toString()};`,
  1134. `fn(${JSON.stringify(socketUrl)})`
  1135. ], { type: "application/javascript" });
  1136. const objURL = URL.createObjectURL(blob);
  1137. const sharedWorker = new SharedWorker(objURL);
  1138. return new Promise((resolve, reject) => {
  1139. const onVisibilityChange = () => {
  1140. sharedWorker.port.postMessage({ visibility: document.visibilityState });
  1141. };
  1142. document.addEventListener("visibilitychange", onVisibilityChange);
  1143. sharedWorker.port.addEventListener("message", (event) => {
  1144. document.removeEventListener("visibilitychange", onVisibilityChange);
  1145. sharedWorker.port.close();
  1146. const data = event.data;
  1147. if (data.type === "error") {
  1148. reject(data.error);
  1149. return;
  1150. }
  1151. resolve();
  1152. });
  1153. onVisibilityChange();
  1154. sharedWorker.port.start();
  1155. });
  1156. }
  1157. function pingWorkerContentMain(socketUrl) {
  1158. self.addEventListener("connect", (_event) => {
  1159. const port = _event.ports[0];
  1160. if (!socketUrl) {
  1161. port.postMessage({
  1162. type: "error",
  1163. error: /* @__PURE__ */ new Error("socketUrl not found")
  1164. });
  1165. return;
  1166. }
  1167. const visibilityManager = {
  1168. currentState: "visible",
  1169. listeners: /* @__PURE__ */ new Set()
  1170. };
  1171. port.addEventListener("message", (event) => {
  1172. const { visibility } = event.data;
  1173. visibilityManager.currentState = visibility;
  1174. console.debug("[vite] new window visibility", visibility);
  1175. for (const listener of visibilityManager.listeners) listener(visibility);
  1176. });
  1177. port.start();
  1178. console.debug("[vite] connected from window");
  1179. waitForSuccessfulPingInternal(socketUrl, visibilityManager).then(() => {
  1180. console.debug("[vite] ping successful");
  1181. try {
  1182. port.postMessage({ type: "success" });
  1183. } catch (error) {
  1184. port.postMessage({
  1185. type: "error",
  1186. error
  1187. });
  1188. }
  1189. }, (error) => {
  1190. console.debug("[vite] error happened", error);
  1191. try {
  1192. port.postMessage({
  1193. type: "error",
  1194. error
  1195. });
  1196. } catch (error) {
  1197. port.postMessage({
  1198. type: "error",
  1199. error
  1200. });
  1201. }
  1202. });
  1203. });
  1204. }
  1205. async function waitForSuccessfulPingInternal(socketUrl, visibilityManager, ms = 1e3) {
  1206. function wait(ms) {
  1207. return new Promise((resolve) => setTimeout(resolve, ms));
  1208. }
  1209. async function ping() {
  1210. try {
  1211. const socket = new WebSocket(socketUrl, "vite-ping");
  1212. return new Promise((resolve) => {
  1213. function onOpen() {
  1214. resolve(true);
  1215. close();
  1216. }
  1217. function onError() {
  1218. resolve(false);
  1219. close();
  1220. }
  1221. function close() {
  1222. socket.removeEventListener("open", onOpen);
  1223. socket.removeEventListener("error", onError);
  1224. socket.close();
  1225. }
  1226. socket.addEventListener("open", onOpen);
  1227. socket.addEventListener("error", onError);
  1228. });
  1229. } catch {
  1230. return false;
  1231. }
  1232. }
  1233. function waitForWindowShow(visibilityManager) {
  1234. return new Promise((resolve) => {
  1235. const onChange = (newVisibility) => {
  1236. if (newVisibility === "visible") {
  1237. resolve();
  1238. visibilityManager.listeners.delete(onChange);
  1239. }
  1240. };
  1241. visibilityManager.listeners.add(onChange);
  1242. });
  1243. }
  1244. if (await ping()) return;
  1245. await wait(ms);
  1246. while (true) if (visibilityManager.currentState === "visible") {
  1247. if (await ping()) break;
  1248. await wait(ms);
  1249. } else await waitForWindowShow(visibilityManager);
  1250. }
  1251. const sheetsMap = /* @__PURE__ */ new Map();
  1252. const linkSheetsMap = /* @__PURE__ */ new Map();
  1253. if ("document" in globalThis) {
  1254. document.querySelectorAll("style[data-vite-dev-id]").forEach((el) => {
  1255. sheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
  1256. });
  1257. document.querySelectorAll("link[rel=\"stylesheet\"][data-vite-dev-id]").forEach((el) => {
  1258. linkSheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
  1259. });
  1260. }
  1261. let lastInsertedStyle;
  1262. function updateStyle(id, content) {
  1263. if (linkSheetsMap.has(id)) return;
  1264. let style = sheetsMap.get(id);
  1265. if (!style) {
  1266. style = document.createElement("style");
  1267. style.setAttribute("type", "text/css");
  1268. style.setAttribute("data-vite-dev-id", id);
  1269. style.textContent = content;
  1270. if (cspNonce) style.setAttribute("nonce", cspNonce);
  1271. if (!lastInsertedStyle) {
  1272. document.head.appendChild(style);
  1273. setTimeout(() => {
  1274. lastInsertedStyle = void 0;
  1275. }, 0);
  1276. } else lastInsertedStyle.insertAdjacentElement("afterend", style);
  1277. lastInsertedStyle = style;
  1278. } else style.textContent = content;
  1279. sheetsMap.set(id, style);
  1280. }
  1281. function removeStyle(id) {
  1282. if (linkSheetsMap.has(id)) {
  1283. document.querySelectorAll(`link[rel="stylesheet"][data-vite-dev-id="${CSS.escape(id)}"]`).forEach((el) => el.remove());
  1284. linkSheetsMap.delete(id);
  1285. }
  1286. const style = sheetsMap.get(id);
  1287. if (style) {
  1288. document.head.removeChild(style);
  1289. sheetsMap.delete(id);
  1290. }
  1291. }
  1292. function createHotContext(ownerPath) {
  1293. return new HMRContext(hmrClient, ownerPath);
  1294. }
  1295. /**
  1296. * urls here are dynamic import() urls that couldn't be statically analyzed
  1297. */
  1298. function injectQuery(url, queryToInject) {
  1299. if (url[0] !== "." && url[0] !== "/") return url;
  1300. const pathname = url.replace(/[?#].*$/, "");
  1301. const { search, hash } = new URL(url, "http://vite.dev");
  1302. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
  1303. }
  1304. //#endregion
  1305. export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle };