unplugin-https-reverse-proxy 4.0.0 → 4.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-K7HSLE6X.js → chunk-JA3D5AWS.js} +40 -4
- package/dist/chunk-RSBXFJ3Z.js +232 -0
- package/dist/esbuild.cjs +264 -4
- package/dist/esbuild.js +2 -1
- package/dist/hmr-sse-bridge.cjs +258 -0
- package/dist/hmr-sse-bridge.d.cts +10 -0
- package/dist/hmr-sse-bridge.d.ts +10 -0
- package/dist/hmr-sse-bridge.js +8 -0
- package/dist/index.cjs +264 -4
- package/dist/index.js +2 -1
- package/dist/nuxt.cjs +152 -4
- package/dist/nuxt.js +2 -1
- package/dist/rollup.cjs +264 -4
- package/dist/rollup.js +2 -1
- package/dist/rspack.cjs +264 -4
- package/dist/rspack.js +2 -1
- package/dist/vite.cjs +264 -4
- package/dist/vite.js +2 -1
- package/dist/webpack.cjs +264 -4
- package/dist/webpack.js +2 -1
- package/package.json +1 -1
- package/src/caddy/index.ts +24 -5
- package/src/hmr-sse-bridge.ts +266 -0
- package/src/index.ts +20 -0
package/dist/webpack.cjs
CHANGED
|
@@ -13859,6 +13859,17 @@ function getCaddyConfig() {
|
|
|
13859
13859
|
}
|
|
13860
13860
|
return caddyConfig;
|
|
13861
13861
|
}
|
|
13862
|
+
function splitHostPort(addr) {
|
|
13863
|
+
const lastColon = addr.lastIndexOf(":");
|
|
13864
|
+
if (lastColon === -1)
|
|
13865
|
+
return { host: addr, port: "" };
|
|
13866
|
+
if (addr.startsWith("[")) {
|
|
13867
|
+
const end = addr.indexOf("]");
|
|
13868
|
+
if (end !== -1 && addr[end + 1] === ":")
|
|
13869
|
+
return { host: addr.slice(1, end), port: addr.slice(end + 2) };
|
|
13870
|
+
}
|
|
13871
|
+
return { host: addr.slice(0, lastColon), port: addr.slice(lastColon + 1) };
|
|
13872
|
+
}
|
|
13862
13873
|
var CaddyInstant = class {
|
|
13863
13874
|
constructor() {
|
|
13864
13875
|
this.inited = false;
|
|
@@ -13906,6 +13917,7 @@ var CaddyInstant = class {
|
|
|
13906
13917
|
*/
|
|
13907
13918
|
async run(source, target, options) {
|
|
13908
13919
|
source = source.replace("0.0.0.0", "127.0.0.1");
|
|
13920
|
+
source = source.replace(/^localhost(?=:)/i, "127.0.0.1");
|
|
13909
13921
|
const {
|
|
13910
13922
|
restore = true,
|
|
13911
13923
|
base = "/",
|
|
@@ -13917,10 +13929,11 @@ var CaddyInstant = class {
|
|
|
13917
13929
|
this._target = target;
|
|
13918
13930
|
if (!this.inited)
|
|
13919
13931
|
await this.init();
|
|
13920
|
-
|
|
13932
|
+
const sourceHost = splitHostPort(source).host;
|
|
13933
|
+
const targetHost = splitHostPort(target).host;
|
|
13934
|
+
if (!await addHost(sourceHost, targetHost))
|
|
13921
13935
|
throw new Error("update host failed");
|
|
13922
13936
|
consola.success("update host success\n");
|
|
13923
|
-
const targetHost = target.split(":")[0];
|
|
13924
13937
|
const normalizeBase = (b) => {
|
|
13925
13938
|
let out = b || "/";
|
|
13926
13939
|
if (!out.startsWith("/"))
|
|
@@ -13980,7 +13993,7 @@ var CaddyInstant = class {
|
|
|
13980
13993
|
});
|
|
13981
13994
|
const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
|
|
13982
13995
|
import_node_process4.default.exit = async (code) => {
|
|
13983
|
-
const port = Number(source.
|
|
13996
|
+
const port = Number(splitHostPort(source).port);
|
|
13984
13997
|
if (!Number.isNaN(port) && await tryPort(port))
|
|
13985
13998
|
await kill(port);
|
|
13986
13999
|
const pwd = import_node_process4.default.cwd();
|
|
@@ -13988,6 +14001,10 @@ var CaddyInstant = class {
|
|
|
13988
14001
|
if ((0, import_node_fs3.existsSync)(viteCacheDir))
|
|
13989
14002
|
await chmodRecursive(viteCacheDir, 511).catch(() => {
|
|
13990
14003
|
});
|
|
14004
|
+
const viteTempCacheDir = `${pwd}/node_modules/.vite-temp`;
|
|
14005
|
+
if ((0, import_node_fs3.existsSync)(viteTempCacheDir))
|
|
14006
|
+
await chmodRecursive(viteTempCacheDir, 511).catch(() => {
|
|
14007
|
+
});
|
|
13991
14008
|
const nuxtCacheDir = `${pwd}/.nuxt`;
|
|
13992
14009
|
if ((0, import_node_fs3.existsSync)(nuxtCacheDir))
|
|
13993
14010
|
await chmodRecursive(nuxtCacheDir, 511).catch(() => {
|
|
@@ -14059,7 +14076,7 @@ ${line}
|
|
|
14059
14076
|
this._stopEffects.forEach((fn) => fn());
|
|
14060
14077
|
try {
|
|
14061
14078
|
if (restore && this._source && this._target) {
|
|
14062
|
-
if (await removeHost(this._source.
|
|
14079
|
+
if (await removeHost(splitHostPort(this._source).host, splitHostPort(this._target).host))
|
|
14063
14080
|
consola.success("Restore host success.\n");
|
|
14064
14081
|
else
|
|
14065
14082
|
consola.fail("Restore host failed.\n");
|
|
@@ -14087,9 +14104,238 @@ ${line}
|
|
|
14087
14104
|
}
|
|
14088
14105
|
};
|
|
14089
14106
|
|
|
14107
|
+
// src/hmr-sse-bridge.ts
|
|
14108
|
+
var SSE_PATH = "/__hmr_sse";
|
|
14109
|
+
var SEND_PATH = "/__hmr_send";
|
|
14110
|
+
var MAX_POST_BODY = 64 * 1024;
|
|
14111
|
+
function setupHmrSseBridge(server) {
|
|
14112
|
+
const sseClients = /* @__PURE__ */ new Set();
|
|
14113
|
+
const originalSend = server.ws.send.bind(server.ws);
|
|
14114
|
+
server.ws.send = (...args2) => {
|
|
14115
|
+
;
|
|
14116
|
+
originalSend(...args2);
|
|
14117
|
+
let payload;
|
|
14118
|
+
if (typeof args2[0] === "string") {
|
|
14119
|
+
payload = JSON.stringify({ type: "custom", event: args2[0], data: args2[1] });
|
|
14120
|
+
} else {
|
|
14121
|
+
payload = JSON.stringify(args2[0]);
|
|
14122
|
+
}
|
|
14123
|
+
for (const res of sseClients) {
|
|
14124
|
+
try {
|
|
14125
|
+
res.write(`data: ${payload}
|
|
14126
|
+
|
|
14127
|
+
`);
|
|
14128
|
+
} catch {
|
|
14129
|
+
sseClients.delete(res);
|
|
14130
|
+
}
|
|
14131
|
+
}
|
|
14132
|
+
};
|
|
14133
|
+
server.middlewares.use((req, res, next2) => {
|
|
14134
|
+
var _a4;
|
|
14135
|
+
const url2 = (_a4 = req.url) == null ? void 0 : _a4.split("?")[0];
|
|
14136
|
+
if (url2 === SSE_PATH && req.method === "GET") {
|
|
14137
|
+
handleSseConnection(req, res, sseClients);
|
|
14138
|
+
return;
|
|
14139
|
+
}
|
|
14140
|
+
if (url2 === SEND_PATH && req.method === "POST") {
|
|
14141
|
+
handleClientMessage(req, res, server);
|
|
14142
|
+
return;
|
|
14143
|
+
}
|
|
14144
|
+
next2();
|
|
14145
|
+
});
|
|
14146
|
+
}
|
|
14147
|
+
function handleSseConnection(_req, res, sseClients) {
|
|
14148
|
+
res.writeHead(200, {
|
|
14149
|
+
"Content-Type": "text/event-stream",
|
|
14150
|
+
"Cache-Control": "no-cache",
|
|
14151
|
+
"Connection": "keep-alive"
|
|
14152
|
+
});
|
|
14153
|
+
res.write(`data: ${JSON.stringify({ type: "connected" })}
|
|
14154
|
+
|
|
14155
|
+
`);
|
|
14156
|
+
sseClients.add(res);
|
|
14157
|
+
const keepAlive = setInterval(() => {
|
|
14158
|
+
try {
|
|
14159
|
+
res.write(": ping\n\n");
|
|
14160
|
+
} catch {
|
|
14161
|
+
cleanup();
|
|
14162
|
+
}
|
|
14163
|
+
}, 3e4);
|
|
14164
|
+
function cleanup() {
|
|
14165
|
+
clearInterval(keepAlive);
|
|
14166
|
+
sseClients.delete(res);
|
|
14167
|
+
}
|
|
14168
|
+
res.on("close", cleanup);
|
|
14169
|
+
res.on("error", cleanup);
|
|
14170
|
+
}
|
|
14171
|
+
function handleClientMessage(req, res, server) {
|
|
14172
|
+
let body = "";
|
|
14173
|
+
let overflow = false;
|
|
14174
|
+
req.on("data", (chunk) => {
|
|
14175
|
+
body += chunk.toString();
|
|
14176
|
+
if (body.length > MAX_POST_BODY) {
|
|
14177
|
+
overflow = true;
|
|
14178
|
+
req.destroy();
|
|
14179
|
+
}
|
|
14180
|
+
});
|
|
14181
|
+
req.on("end", () => {
|
|
14182
|
+
var _a4, _b3, _c2, _d2, _e;
|
|
14183
|
+
if (overflow) {
|
|
14184
|
+
res.writeHead(413);
|
|
14185
|
+
res.end('{"ok":false}');
|
|
14186
|
+
return;
|
|
14187
|
+
}
|
|
14188
|
+
try {
|
|
14189
|
+
const data = JSON.parse(body);
|
|
14190
|
+
if (data.type === "custom" && data.event) {
|
|
14191
|
+
const dummyClient = {
|
|
14192
|
+
send: (...args2) => {
|
|
14193
|
+
server.ws.send(...args2);
|
|
14194
|
+
}
|
|
14195
|
+
};
|
|
14196
|
+
(_e = (_d2 = (_c2 = (_b3 = (_a4 = server.environments) == null ? void 0 : _a4.client) == null ? void 0 : _b3.hot) == null ? void 0 : _c2.api) == null ? void 0 : _d2.emit) == null ? void 0 : _e.call(_d2, data.event, data.data, dummyClient);
|
|
14197
|
+
}
|
|
14198
|
+
res.writeHead(200, {
|
|
14199
|
+
"Content-Type": "application/json"
|
|
14200
|
+
});
|
|
14201
|
+
res.end('{"ok":true}');
|
|
14202
|
+
} catch {
|
|
14203
|
+
res.writeHead(400);
|
|
14204
|
+
res.end('{"ok":false}');
|
|
14205
|
+
}
|
|
14206
|
+
});
|
|
14207
|
+
}
|
|
14208
|
+
var hmrSseBridgeClientScript = `
|
|
14209
|
+
(function() {
|
|
14210
|
+
// Activate when served over HTTPS to bypass WSS self-signed cert issues
|
|
14211
|
+
if (location.protocol !== 'https:') return;
|
|
14212
|
+
|
|
14213
|
+
var OriginalWebSocket = window.WebSocket;
|
|
14214
|
+
|
|
14215
|
+
function SseWebSocket(originalUrl) {
|
|
14216
|
+
var self = this;
|
|
14217
|
+
// WebSocket readyState constants on instance
|
|
14218
|
+
self.CONNECTING = 0;
|
|
14219
|
+
self.OPEN = 1;
|
|
14220
|
+
self.CLOSING = 2;
|
|
14221
|
+
self.CLOSED = 3;
|
|
14222
|
+
self.readyState = 0;
|
|
14223
|
+
self.onopen = null;
|
|
14224
|
+
self.onmessage = null;
|
|
14225
|
+
self.onclose = null;
|
|
14226
|
+
self.onerror = null;
|
|
14227
|
+
self.bufferedAmount = 0;
|
|
14228
|
+
self.extensions = '';
|
|
14229
|
+
self.binaryType = 'blob';
|
|
14230
|
+
self.protocol = 'vite-hmr';
|
|
14231
|
+
self.url = originalUrl;
|
|
14232
|
+
self._listeners = {};
|
|
14233
|
+
self._opened = false;
|
|
14234
|
+
|
|
14235
|
+
var sseUrl = location.origin + '${SSE_PATH}';
|
|
14236
|
+
var sendUrl = location.origin + '${SEND_PATH}';
|
|
14237
|
+
self._sendUrl = sendUrl;
|
|
14238
|
+
|
|
14239
|
+
var es = new EventSource(sseUrl);
|
|
14240
|
+
self._es = es;
|
|
14241
|
+
|
|
14242
|
+
es.onopen = function() {
|
|
14243
|
+
if (self._opened) return;
|
|
14244
|
+
self._opened = true;
|
|
14245
|
+
self.readyState = 1;
|
|
14246
|
+
var evt = new Event('open');
|
|
14247
|
+
if (self.onopen) self.onopen(evt);
|
|
14248
|
+
self._emit('open', evt);
|
|
14249
|
+
};
|
|
14250
|
+
|
|
14251
|
+
es.onmessage = function(e) {
|
|
14252
|
+
var evt = new MessageEvent('message', { data: e.data });
|
|
14253
|
+
if (self.onmessage) self.onmessage(evt);
|
|
14254
|
+
self._emit('message', evt);
|
|
14255
|
+
};
|
|
14256
|
+
|
|
14257
|
+
es.onerror = function() {
|
|
14258
|
+
// EventSource auto-reconnects on error; don't treat as fatal close
|
|
14259
|
+
// Only emit error event, never close event (SSE handles reconnect internally)
|
|
14260
|
+
if (self.readyState >= 2) return;
|
|
14261
|
+
// EventSource auto-reconnects; no action needed
|
|
14262
|
+
};
|
|
14263
|
+
}
|
|
14264
|
+
|
|
14265
|
+
SseWebSocket.prototype.send = function(data) {
|
|
14266
|
+
if (this.readyState !== 1) return;
|
|
14267
|
+
fetch(this._sendUrl, {
|
|
14268
|
+
method: 'POST',
|
|
14269
|
+
headers: { 'Content-Type': 'application/json' },
|
|
14270
|
+
body: data
|
|
14271
|
+
}).catch(function() {});
|
|
14272
|
+
};
|
|
14273
|
+
|
|
14274
|
+
SseWebSocket.prototype.close = function() {
|
|
14275
|
+
if (this.readyState >= 2) return;
|
|
14276
|
+
this.readyState = 3;
|
|
14277
|
+
if (this._es) this._es.close();
|
|
14278
|
+
var evt = new CloseEvent('close', { code: 1000, reason: '', wasClean: true });
|
|
14279
|
+
if (this.onclose) this.onclose(evt);
|
|
14280
|
+
this._emit('close', evt);
|
|
14281
|
+
};
|
|
14282
|
+
|
|
14283
|
+
SseWebSocket.prototype.addEventListener = function(type, fn, options) {
|
|
14284
|
+
if (!this._listeners[type]) this._listeners[type] = [];
|
|
14285
|
+
var entry = { fn: fn, once: !!(options && options.once) };
|
|
14286
|
+
this._listeners[type].push(entry);
|
|
14287
|
+
};
|
|
14288
|
+
|
|
14289
|
+
SseWebSocket.prototype.removeEventListener = function(type, fn) {
|
|
14290
|
+
var list = this._listeners[type];
|
|
14291
|
+
if (!list) return;
|
|
14292
|
+
this._listeners[type] = list.filter(function(e) { return e.fn !== fn; });
|
|
14293
|
+
};
|
|
14294
|
+
|
|
14295
|
+
SseWebSocket.prototype.dispatchEvent = function(evt) {
|
|
14296
|
+
this._emit(evt.type, evt);
|
|
14297
|
+
return true;
|
|
14298
|
+
};
|
|
14299
|
+
|
|
14300
|
+
SseWebSocket.prototype._emit = function(type, evt) {
|
|
14301
|
+
var list = this._listeners[type];
|
|
14302
|
+
if (!list) return;
|
|
14303
|
+
var remaining = [];
|
|
14304
|
+
list.forEach(function(entry) {
|
|
14305
|
+
entry.fn(evt);
|
|
14306
|
+
if (!entry.once) remaining.push(entry);
|
|
14307
|
+
});
|
|
14308
|
+
this._listeners[type] = remaining;
|
|
14309
|
+
};
|
|
14310
|
+
|
|
14311
|
+
function PatchedWebSocket(url, protocols) {
|
|
14312
|
+
// Only intercept Vite HMR connections (protocol 'vite-hmr')
|
|
14313
|
+
var isViteHmr = protocols === 'vite-hmr'
|
|
14314
|
+
|| (Array.isArray(protocols) && protocols.indexOf('vite-hmr') !== -1);
|
|
14315
|
+
if (!isViteHmr) {
|
|
14316
|
+
if (protocols !== undefined) {
|
|
14317
|
+
return new OriginalWebSocket(url, protocols);
|
|
14318
|
+
}
|
|
14319
|
+
return new OriginalWebSocket(url);
|
|
14320
|
+
}
|
|
14321
|
+
return new SseWebSocket(url);
|
|
14322
|
+
}
|
|
14323
|
+
|
|
14324
|
+
PatchedWebSocket.CONNECTING = 0;
|
|
14325
|
+
PatchedWebSocket.OPEN = 1;
|
|
14326
|
+
PatchedWebSocket.CLOSING = 2;
|
|
14327
|
+
PatchedWebSocket.CLOSED = 3;
|
|
14328
|
+
PatchedWebSocket.prototype = Object.create(OriginalWebSocket.prototype);
|
|
14329
|
+
PatchedWebSocket.prototype.constructor = PatchedWebSocket;
|
|
14330
|
+
|
|
14331
|
+
window.WebSocket = PatchedWebSocket;
|
|
14332
|
+
})();
|
|
14333
|
+
`;
|
|
14334
|
+
|
|
14090
14335
|
// src/index.ts
|
|
14091
14336
|
var config;
|
|
14092
14337
|
var caddy;
|
|
14338
|
+
var hmrSseBridgeActive = false;
|
|
14093
14339
|
var cwd = import_node_process5.default.cwd();
|
|
14094
14340
|
function colorUrl(url2) {
|
|
14095
14341
|
return import_picocolors2.default.green(url2.replace(/:(\d+)\//, (_, port) => `:${import_picocolors2.default.bold(port)}/`));
|
|
@@ -14176,6 +14422,20 @@ var unpluginFactory = (options) => ({
|
|
|
14176
14422
|
}
|
|
14177
14423
|
const base = server.config.base || "/";
|
|
14178
14424
|
server.printUrls = () => vitePrintUrls(options, source, target, base, _printUrls);
|
|
14425
|
+
if (options.https) {
|
|
14426
|
+
setupHmrSseBridge(server);
|
|
14427
|
+
hmrSseBridgeActive = true;
|
|
14428
|
+
consola.info("HMR SSE bridge enabled for iOS Safari WSS workaround");
|
|
14429
|
+
}
|
|
14430
|
+
},
|
|
14431
|
+
transformIndexHtml() {
|
|
14432
|
+
if (!hmrSseBridgeActive)
|
|
14433
|
+
return [];
|
|
14434
|
+
return [{
|
|
14435
|
+
tag: "script",
|
|
14436
|
+
children: hmrSseBridgeClientScript,
|
|
14437
|
+
injectTo: "head-prepend"
|
|
14438
|
+
}];
|
|
14179
14439
|
}
|
|
14180
14440
|
},
|
|
14181
14441
|
webpack(compiler) {
|
package/dist/webpack.js
CHANGED
package/package.json
CHANGED
package/src/caddy/index.ts
CHANGED
|
@@ -114,6 +114,19 @@ function getCaddyConfig(): ReturnType<typeof useCaddyConfig> {
|
|
|
114
114
|
return caddyConfig
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
/** Split `host:port` (IPv4 or hostname); supports `[::1]:port`. */
|
|
118
|
+
function splitHostPort(addr: string): { host: string, port: string } {
|
|
119
|
+
const lastColon = addr.lastIndexOf(':')
|
|
120
|
+
if (lastColon === -1)
|
|
121
|
+
return { host: addr, port: '' }
|
|
122
|
+
if (addr.startsWith('[')) {
|
|
123
|
+
const end = addr.indexOf(']')
|
|
124
|
+
if (end !== -1 && addr[end + 1] === ':')
|
|
125
|
+
return { host: addr.slice(1, end), port: addr.slice(end + 2) }
|
|
126
|
+
}
|
|
127
|
+
return { host: addr.slice(0, lastColon), port: addr.slice(lastColon + 1) }
|
|
128
|
+
}
|
|
129
|
+
|
|
117
130
|
export class CaddyInstant {
|
|
118
131
|
private inited = false
|
|
119
132
|
private stoped = false
|
|
@@ -180,6 +193,9 @@ export class CaddyInstant {
|
|
|
180
193
|
*/
|
|
181
194
|
async run(source: string, target: string, options?: Partial<RunOptions>): Promise<void> {
|
|
182
195
|
source = source.replace('0.0.0.0', '127.0.0.1')
|
|
196
|
+
// Caddy dials the upstream host via DNS; `localhost` can hit lookup timeouts (VPN/DNS).
|
|
197
|
+
// Use loopback IP so the proxy never depends on resolving "localhost".
|
|
198
|
+
source = source.replace(/^localhost(?=:)/i, '127.0.0.1')
|
|
183
199
|
const {
|
|
184
200
|
restore = true,
|
|
185
201
|
base = '/',
|
|
@@ -194,11 +210,11 @@ export class CaddyInstant {
|
|
|
194
210
|
if (!this.inited)
|
|
195
211
|
await this.init()
|
|
196
212
|
|
|
197
|
-
|
|
213
|
+
const sourceHost = splitHostPort(source).host
|
|
214
|
+
const targetHost = splitHostPort(target).host
|
|
215
|
+
if (!await addHost(sourceHost, targetHost))
|
|
198
216
|
throw new Error('update host failed')
|
|
199
217
|
consola.success('update host success\n')
|
|
200
|
-
|
|
201
|
-
const targetHost = target.split(':')[0]
|
|
202
218
|
const normalizeBase = (b: string): string => {
|
|
203
219
|
let out = b || '/'
|
|
204
220
|
if (!out.startsWith('/'))
|
|
@@ -270,7 +286,7 @@ export class CaddyInstant {
|
|
|
270
286
|
|
|
271
287
|
// @ts-expect-error override
|
|
272
288
|
process.exit = async (code?: number) => {
|
|
273
|
-
const port = Number(source.
|
|
289
|
+
const port = Number(splitHostPort(source).port)
|
|
274
290
|
if (!Number.isNaN(port) && await tryPort(port))
|
|
275
291
|
await kill(port)
|
|
276
292
|
|
|
@@ -279,6 +295,9 @@ export class CaddyInstant {
|
|
|
279
295
|
const viteCacheDir = `${pwd}/node_modules/.vite`
|
|
280
296
|
if (existsSync(viteCacheDir))
|
|
281
297
|
await chmodRecursive(viteCacheDir, 0o777).catch(() => { })
|
|
298
|
+
const viteTempCacheDir = `${pwd}/node_modules/.vite-temp`
|
|
299
|
+
if (existsSync(viteTempCacheDir))
|
|
300
|
+
await chmodRecursive(viteTempCacheDir, 0o777).catch(() => { })
|
|
282
301
|
const nuxtCacheDir = `${pwd}/.nuxt`
|
|
283
302
|
if (existsSync(nuxtCacheDir))
|
|
284
303
|
await chmodRecursive(nuxtCacheDir, 0o777).catch(() => { })
|
|
@@ -367,7 +386,7 @@ export class CaddyInstant {
|
|
|
367
386
|
|
|
368
387
|
try {
|
|
369
388
|
if (restore && this._source && this._target) {
|
|
370
|
-
if (await removeHost(this._source.
|
|
389
|
+
if (await removeHost(splitHostPort(this._source).host, splitHostPort(this._target).host))
|
|
371
390
|
consola.success('Restore host success.\n')
|
|
372
391
|
|
|
373
392
|
else
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import type { Buffer } from 'node:buffer'
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
3
|
+
import type { ViteDevServer } from 'vite'
|
|
4
|
+
|
|
5
|
+
const SSE_PATH = '/__hmr_sse'
|
|
6
|
+
const SEND_PATH = '/__hmr_send'
|
|
7
|
+
const MAX_POST_BODY = 64 * 1024 // 64KB limit for client messages
|
|
8
|
+
|
|
9
|
+
export function setupHmrSseBridge(server: ViteDevServer): void {
|
|
10
|
+
const sseClients = new Set<ServerResponse>()
|
|
11
|
+
|
|
12
|
+
// Monkey-patch server.ws.send to also push to SSE clients
|
|
13
|
+
const originalSend = server.ws.send.bind(server.ws)
|
|
14
|
+
server.ws.send = (...args: any[]) => {
|
|
15
|
+
// Call original WebSocket send
|
|
16
|
+
;(originalSend as any)(...args)
|
|
17
|
+
|
|
18
|
+
// Build the payload string same as Vite does internally
|
|
19
|
+
let payload: string
|
|
20
|
+
if (typeof args[0] === 'string') {
|
|
21
|
+
// server.ws.send(event, data) — custom event, wrap it
|
|
22
|
+
payload = JSON.stringify({ type: 'custom', event: args[0], data: args[1] })
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
// server.ws.send(payloadObject)
|
|
26
|
+
payload = JSON.stringify(args[0])
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Push to all SSE clients (skip errored ones)
|
|
30
|
+
for (const res of sseClients) {
|
|
31
|
+
try {
|
|
32
|
+
res.write(`data: ${payload}\n\n`)
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
sseClients.delete(res)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Add middleware for SSE and POST endpoints
|
|
41
|
+
server.middlewares.use((req: IncomingMessage, res: ServerResponse, next: () => void) => {
|
|
42
|
+
const url = req.url?.split('?')[0]
|
|
43
|
+
|
|
44
|
+
if (url === SSE_PATH && req.method === 'GET') {
|
|
45
|
+
handleSseConnection(req, res, sseClients)
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (url === SEND_PATH && req.method === 'POST') {
|
|
50
|
+
handleClientMessage(req, res, server)
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
next()
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function handleSseConnection(
|
|
59
|
+
_req: IncomingMessage,
|
|
60
|
+
res: ServerResponse,
|
|
61
|
+
sseClients: Set<ServerResponse>,
|
|
62
|
+
): void {
|
|
63
|
+
res.writeHead(200, {
|
|
64
|
+
'Content-Type': 'text/event-stream',
|
|
65
|
+
'Cache-Control': 'no-cache',
|
|
66
|
+
'Connection': 'keep-alive',
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
// Send initial connected message (same as Vite's WebSocket)
|
|
70
|
+
res.write(`data: ${JSON.stringify({ type: 'connected' })}\n\n`)
|
|
71
|
+
|
|
72
|
+
sseClients.add(res)
|
|
73
|
+
|
|
74
|
+
// Keep-alive ping every 30s
|
|
75
|
+
const keepAlive = setInterval(() => {
|
|
76
|
+
try {
|
|
77
|
+
res.write(': ping\n\n')
|
|
78
|
+
}
|
|
79
|
+
catch { cleanup() }
|
|
80
|
+
}, 30000)
|
|
81
|
+
|
|
82
|
+
function cleanup(): void {
|
|
83
|
+
clearInterval(keepAlive)
|
|
84
|
+
sseClients.delete(res)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
res.on('close', cleanup)
|
|
88
|
+
res.on('error', cleanup)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function handleClientMessage(
|
|
92
|
+
req: IncomingMessage,
|
|
93
|
+
res: ServerResponse,
|
|
94
|
+
server: ViteDevServer,
|
|
95
|
+
): void {
|
|
96
|
+
let body = ''
|
|
97
|
+
let overflow = false
|
|
98
|
+
req.on('data', (chunk: Buffer) => {
|
|
99
|
+
body += chunk.toString()
|
|
100
|
+
if (body.length > MAX_POST_BODY) {
|
|
101
|
+
overflow = true
|
|
102
|
+
req.destroy()
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
req.on('end', () => {
|
|
106
|
+
if (overflow) {
|
|
107
|
+
res.writeHead(413)
|
|
108
|
+
res.end('{"ok":false}')
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
const data = JSON.parse(body)
|
|
113
|
+
// Forward custom events to Vite's HMR server
|
|
114
|
+
// Vite client sends: { type: 'custom', event: string, data: any }
|
|
115
|
+
if (data.type === 'custom' && data.event) {
|
|
116
|
+
// Trigger listeners registered via server.ws.on(event, handler)
|
|
117
|
+
// by simulating the internal dispatch with a dummy client
|
|
118
|
+
const dummyClient = {
|
|
119
|
+
send: (...args: any[]) => { server.ws.send(...(args as [any])) },
|
|
120
|
+
}
|
|
121
|
+
// Access internal customListeners via the 'on' registered handlers
|
|
122
|
+
// We re-emit by calling the server's hot channel listener mechanism
|
|
123
|
+
;(server as any).environments?.client?.hot?.api?.emit?.(data.event, data.data, dummyClient)
|
|
124
|
+
}
|
|
125
|
+
res.writeHead(200, {
|
|
126
|
+
'Content-Type': 'application/json',
|
|
127
|
+
})
|
|
128
|
+
res.end('{"ok":true}')
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
res.writeHead(400)
|
|
132
|
+
res.end('{"ok":false}')
|
|
133
|
+
}
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Client-side script that patches WebSocket to use SSE+fetch on iOS Safari.
|
|
139
|
+
* This script is injected via Vite's transformIndexHtml hook.
|
|
140
|
+
*/
|
|
141
|
+
export const hmrSseBridgeClientScript = `
|
|
142
|
+
(function() {
|
|
143
|
+
// Activate when served over HTTPS to bypass WSS self-signed cert issues
|
|
144
|
+
if (location.protocol !== 'https:') return;
|
|
145
|
+
|
|
146
|
+
var OriginalWebSocket = window.WebSocket;
|
|
147
|
+
|
|
148
|
+
function SseWebSocket(originalUrl) {
|
|
149
|
+
var self = this;
|
|
150
|
+
// WebSocket readyState constants on instance
|
|
151
|
+
self.CONNECTING = 0;
|
|
152
|
+
self.OPEN = 1;
|
|
153
|
+
self.CLOSING = 2;
|
|
154
|
+
self.CLOSED = 3;
|
|
155
|
+
self.readyState = 0;
|
|
156
|
+
self.onopen = null;
|
|
157
|
+
self.onmessage = null;
|
|
158
|
+
self.onclose = null;
|
|
159
|
+
self.onerror = null;
|
|
160
|
+
self.bufferedAmount = 0;
|
|
161
|
+
self.extensions = '';
|
|
162
|
+
self.binaryType = 'blob';
|
|
163
|
+
self.protocol = 'vite-hmr';
|
|
164
|
+
self.url = originalUrl;
|
|
165
|
+
self._listeners = {};
|
|
166
|
+
self._opened = false;
|
|
167
|
+
|
|
168
|
+
var sseUrl = location.origin + '${SSE_PATH}';
|
|
169
|
+
var sendUrl = location.origin + '${SEND_PATH}';
|
|
170
|
+
self._sendUrl = sendUrl;
|
|
171
|
+
|
|
172
|
+
var es = new EventSource(sseUrl);
|
|
173
|
+
self._es = es;
|
|
174
|
+
|
|
175
|
+
es.onopen = function() {
|
|
176
|
+
if (self._opened) return;
|
|
177
|
+
self._opened = true;
|
|
178
|
+
self.readyState = 1;
|
|
179
|
+
var evt = new Event('open');
|
|
180
|
+
if (self.onopen) self.onopen(evt);
|
|
181
|
+
self._emit('open', evt);
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
es.onmessage = function(e) {
|
|
185
|
+
var evt = new MessageEvent('message', { data: e.data });
|
|
186
|
+
if (self.onmessage) self.onmessage(evt);
|
|
187
|
+
self._emit('message', evt);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
es.onerror = function() {
|
|
191
|
+
// EventSource auto-reconnects on error; don't treat as fatal close
|
|
192
|
+
// Only emit error event, never close event (SSE handles reconnect internally)
|
|
193
|
+
if (self.readyState >= 2) return;
|
|
194
|
+
// EventSource auto-reconnects; no action needed
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
SseWebSocket.prototype.send = function(data) {
|
|
199
|
+
if (this.readyState !== 1) return;
|
|
200
|
+
fetch(this._sendUrl, {
|
|
201
|
+
method: 'POST',
|
|
202
|
+
headers: { 'Content-Type': 'application/json' },
|
|
203
|
+
body: data
|
|
204
|
+
}).catch(function() {});
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
SseWebSocket.prototype.close = function() {
|
|
208
|
+
if (this.readyState >= 2) return;
|
|
209
|
+
this.readyState = 3;
|
|
210
|
+
if (this._es) this._es.close();
|
|
211
|
+
var evt = new CloseEvent('close', { code: 1000, reason: '', wasClean: true });
|
|
212
|
+
if (this.onclose) this.onclose(evt);
|
|
213
|
+
this._emit('close', evt);
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
SseWebSocket.prototype.addEventListener = function(type, fn, options) {
|
|
217
|
+
if (!this._listeners[type]) this._listeners[type] = [];
|
|
218
|
+
var entry = { fn: fn, once: !!(options && options.once) };
|
|
219
|
+
this._listeners[type].push(entry);
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
SseWebSocket.prototype.removeEventListener = function(type, fn) {
|
|
223
|
+
var list = this._listeners[type];
|
|
224
|
+
if (!list) return;
|
|
225
|
+
this._listeners[type] = list.filter(function(e) { return e.fn !== fn; });
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
SseWebSocket.prototype.dispatchEvent = function(evt) {
|
|
229
|
+
this._emit(evt.type, evt);
|
|
230
|
+
return true;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
SseWebSocket.prototype._emit = function(type, evt) {
|
|
234
|
+
var list = this._listeners[type];
|
|
235
|
+
if (!list) return;
|
|
236
|
+
var remaining = [];
|
|
237
|
+
list.forEach(function(entry) {
|
|
238
|
+
entry.fn(evt);
|
|
239
|
+
if (!entry.once) remaining.push(entry);
|
|
240
|
+
});
|
|
241
|
+
this._listeners[type] = remaining;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
function PatchedWebSocket(url, protocols) {
|
|
245
|
+
// Only intercept Vite HMR connections (protocol 'vite-hmr')
|
|
246
|
+
var isViteHmr = protocols === 'vite-hmr'
|
|
247
|
+
|| (Array.isArray(protocols) && protocols.indexOf('vite-hmr') !== -1);
|
|
248
|
+
if (!isViteHmr) {
|
|
249
|
+
if (protocols !== undefined) {
|
|
250
|
+
return new OriginalWebSocket(url, protocols);
|
|
251
|
+
}
|
|
252
|
+
return new OriginalWebSocket(url);
|
|
253
|
+
}
|
|
254
|
+
return new SseWebSocket(url);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
PatchedWebSocket.CONNECTING = 0;
|
|
258
|
+
PatchedWebSocket.OPEN = 1;
|
|
259
|
+
PatchedWebSocket.CLOSING = 2;
|
|
260
|
+
PatchedWebSocket.CLOSED = 3;
|
|
261
|
+
PatchedWebSocket.prototype = Object.create(OriginalWebSocket.prototype);
|
|
262
|
+
PatchedWebSocket.prototype.constructor = PatchedWebSocket;
|
|
263
|
+
|
|
264
|
+
window.WebSocket = PatchedWebSocket;
|
|
265
|
+
})();
|
|
266
|
+
`
|