-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
320 lines (302 loc) · 10.5 KB
/
Copy pathvite.config.ts
File metadata and controls
320 lines (302 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';
import fs from 'node:fs';
import path from 'node:path';
// Dev-only: host the Yjs websocket backend on the SAME port as Vite under /yjs/*.
// This avoids the “desktop tabs sync locally but phone sees no notes” trap when
// a reverse proxy forwards only :27015 (HTTP) but not a separate :1234 (WS).
//
// NOTE: Vite also uses a websocket (/) for HMR. We only handle upgrades for /yjs.
import { WebSocketServer, type WebSocket } from 'ws';
import { setupWSConnection } from 'y-websocket/bin/utils';
import type { Plugin } from 'vite';
const packageJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf-8')) as { version?: string };
const appVersion = String(packageJson.version || 'dev');
function parsePublicOrigin(rawValue: string): URL | null {
const normalized = String(rawValue || '').trim();
if (!normalized) return null;
try {
const url = new URL(normalized);
url.pathname = '/';
url.search = '';
url.hash = '';
return url;
} catch {
return null;
}
}
function attachProxyErrorHandlers(proxy: any, label: string): void {
const swallowSocketError = (socket: any): void => {
if (!socket || typeof socket.on !== 'function') return;
socket.on('error', () => {
// Ignore raw socket resets so Vite stays alive while the backend restarts.
// HTTP callers still get a 502 via the `error` handler below when applicable.
});
};
proxy.on('error', (err: Error, _req: unknown, resOrSocket: any) => {
const message = err instanceof Error ? err.message : String(err);
console.warn(`[vite-proxy:${label}] ${message}`);
if (!resOrSocket) return;
if (typeof resOrSocket.writeHead === 'function' && !resOrSocket.headersSent) {
resOrSocket.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
resOrSocket.end('Proxy target unavailable');
return;
}
if (typeof resOrSocket.end === 'function') {
try {
resOrSocket.end();
} catch {
// ignore
}
}
});
proxy.on('proxyReqWs', (_proxyReq: unknown, _req: unknown, socket: any) => {
swallowSocketError(socket);
});
proxy.on('open', (proxySocket: any) => {
swallowSocketError(proxySocket);
});
}
function excalidrawFontsPlugin(): Plugin {
const fontsSourceDir = path.resolve(__dirname, 'node_modules/@excalidraw/excalidraw/dist/prod/fonts');
let resolvedOutDir = '';
return {
name: 'freemannotes:excalidraw-fonts',
configResolved(config) {
resolvedOutDir = config.build.outDir;
},
// Dev server: serve Excalidraw font files from node_modules at /fonts/*.
configureServer(server) {
server.middlewares.use('/fonts', (req, res, next) => {
const safeSuffix = (req.url || '/').replace(/\\/g, '/').replace(/\.\.+/g, '');
const resolved = path.resolve(fontsSourceDir, '.' + safeSuffix);
if (!resolved.startsWith(fontsSourceDir + path.sep) && resolved !== fontsSourceDir) {
next();
return;
}
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
next();
return;
}
res.setHeader('Content-Type', resolved.endsWith('.woff2') ? 'font/woff2' : 'application/octet-stream');
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
fs.createReadStream(resolved).pipe(res);
});
},
// Build: copy fonts directory into the output so they're served at /fonts/*.
closeBundle() {
if (!resolvedOutDir || !fs.existsSync(fontsSourceDir)) return;
const fontsDestDir = path.resolve(__dirname, resolvedOutDir, 'fonts');
fs.cpSync(fontsSourceDir, fontsDestDir, { recursive: true, force: true });
},
};
}
function yjsWebsocketPlugin(): Plugin {
return {
name: 'freemannotes:yjs-websocket',
apply: 'serve',
configureServer(server) {
const httpServer = server.httpServer;
if (!httpServer) return;
const wss = new WebSocketServer({ noServer: true });
httpServer.on('upgrade', (req, socket, head) => {
// Clients (especially mobile + proxies) can disconnect mid-upgrade.
// If nobody listens to the socket error, Node will crash the process.
socket.on('error', () => {
// Intentionally ignored (common ECONNRESET).
});
const url = req.url || '/';
if (!url.startsWith('/yjs')) {
return;
}
console.info(`[yjs-ws-dev] upgrade ${url}`);
try {
wss.handleUpgrade(req, socket, head, (conn: WebSocket) => {
wss.emit('connection', conn, req);
});
} catch {
try {
socket.destroy();
} catch {
// ignore
}
}
});
wss.on('connection', (conn, req) => {
console.info(`[yjs-ws-dev] connected ${(req.url || '/').toString()}`);
// y-websocket expects the room name in the path, typically '/<room>'.
// Our client connects to '/yjs/<room>', so strip the prefix.
(req as any).url = String(req.url || '/').replace(/^\/yjs/, '') || '/';
setupWSConnection(conn, req, { gc: true });
});
httpServer.once('close', () => {
wss.close();
});
},
};
}
export default defineConfig(({ mode }) => {
const envDir = './env.vite';
const env = loadEnv(mode, envDir, 'VITE_');
const devPort = Number(env.VITE_DEV_PORT || 5173);
const apiProxyTarget = String(env.VITE_API_PROXY_TARGET || 'http://localhost:27015').trim();
const publicDevOrigin = parsePublicOrigin(String(env.VITE_DEV_PUBLIC_ORIGIN || ''));
const yjsEmbedEnv = String(env.VITE_YJS_EMBED || '').trim();
const yjsProxyEnv = String(env.VITE_YJS_PROXY || '').trim();
const strictDevPort = publicDevOrigin
? true
: String(env.VITE_DEV_STRICT_PORT || '').trim() === '1';
const hmrConfig = publicDevOrigin
? {
protocol: publicDevOrigin.protocol === 'https:' ? 'wss' : 'ws',
host: publicDevOrigin.hostname,
clientPort: publicDevOrigin.port
? Number(publicDevOrigin.port)
: (publicDevOrigin.protocol === 'https:' ? 443 : 80),
}
: undefined;
// Branch policy for Yjs transport in Vite:
// - Development branch: always embed Yjs websocket in Vite to eliminate noisy
// /yjs ws proxy disconnect logs during iterative mobile testing.
// - Non-development branch: respect explicit env toggles for proxy/embed.
const useYjsProxy = mode === 'development' ? false : yjsProxyEnv === '1';
const embedYjs = mode === 'development' ? true : yjsEmbedEnv === '1';
return {
envDir,
plugins: [
excalidrawFontsPlugin(),
react(),
VitePWA({
strategies: 'injectManifest',
srcDir: 'src',
filename: 'sw.js',
injectRegister: false,
registerType: 'autoUpdate',
includeAssets: [
'pwa-192x192.png',
'pwa-512x512.png',
'pwa-192x192-maskable.png',
'pwa-512x512-maskable.png',
'apple-touch-icon.png',
],
manifest: {
name: 'Freeman Notes',
short_name: 'Freeman Notes',
description: 'Offline-first collaborative note taking for personal and shared workspaces.',
start_url: '/',
scope: '/',
display: 'standalone',
orientation: 'portrait',
// Match the default app background so Android standalone chrome does
// not flash a white navigation bar before the runtime theme sync runs.
theme_color: '#0b0f16',
background_color: '#0b0f16',
icons: [
// 'any' icons are displayed as-is (transparent background preserved).
// Used for browser tabs, notification trays, and launchers that
// render the icon without cropping or background-filling.
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
// 'maskable' icons have an opaque background (app dark theme colour)
// and the logo scaled to fit within the inner 80% safe zone.
// Android adaptive-icon launchers prefer these — without them the
// launcher fills the transparent area with its own colour (often
// white), making a light logo invisible.
{ src: 'pwa-192x192-maskable.png', sizes: '192x192', type: 'image/png', purpose: 'maskable' },
{ src: 'pwa-512x512-maskable.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
},
injectManifest: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,json,woff2}'],
maximumFileSizeToCacheInBytes: 6 * 1024 * 1024,
},
devOptions: {
enabled: true,
type: 'classic',
navigateFallback: '/index.html',
},
}),
...(embedYjs ? [yjsWebsocketPlugin()] : []),
],
define: {
__APP_VERSION__: JSON.stringify(appVersion),
},
server: {
host: true,
port: devPort,
// Reverse-proxied dev domains need a stable port; ad-hoc local sessions can
// still opt into fallback ports by leaving VITE_DEV_PUBLIC_ORIGIN unset.
strictPort: strictDevPort,
origin: publicDevOrigin?.origin,
hmr: hmrConfig,
allowedHosts: true,
proxy: {
// Proxy API + uploads to the Node server so cookie-based auth remains same-origin.
'/api': {
target: apiProxyTarget,
changeOrigin: true,
xfwd: true,
configure(proxy) {
attachProxyErrorHandlers(proxy, 'api');
},
},
'/uploads': {
target: apiProxyTarget,
changeOrigin: true,
xfwd: true,
configure(proxy) {
attachProxyErrorHandlers(proxy, 'uploads');
},
},
'/ws': {
target: apiProxyTarget,
ws: true,
changeOrigin: true,
xfwd: true,
configure(proxy) {
attachProxyErrorHandlers(proxy, 'ws');
},
},
// Proxy Yjs websocket rooms to the Node server so dev can see persisted notes.
// Branch notes:
// - When `embedYjs` is true, Vite itself handles /yjs upgrades via plugin.
// - Only when `embedYjs` is false *and* `useYjsProxy` is true do we
// register the ws proxy entry.
...((embedYjs || !useYjsProxy)
? {}
: {
'/yjs': {
target: apiProxyTarget,
ws: true,
changeOrigin: true,
xfwd: true,
configure(proxy) {
attachProxyErrorHandlers(proxy, 'yjs');
},
},
}),
},
},
preview: {
host: true,
port: Number(env.VITE_PREVIEW_PORT || 4173),
strictPort: true,
},
optimizeDeps: {
esbuildOptions: {
// Excalidraw's ESM locale bundle requires the ES2022 parser target.
target: 'es2022',
treeShaking: true,
},
},
build: {
// The verified publish flow already deletes dist-build-temp before invoking
// Vite. Keep nested builds (notably vite-plugin-pwa injectManifest's custom
// service worker build) from emptying the shared outDir and deleting the
// client build artifacts before Workbox scans them.
target: 'es2022',
emptyOutDir: false,
},
};
});