-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvite.config.ts
More file actions
209 lines (184 loc) · 5.92 KB
/
Copy pathvite.config.ts
File metadata and controls
209 lines (184 loc) · 5.92 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
import react from "@vitejs/plugin-react";
import { defineConfig } from "vitest/config";
import { Buffer } from "node:buffer";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import packageJson from "./package.json" with { type: "json" };
import { storybookTest } from "@storybook/addon-vitest/vitest-plugin";
import { playwright } from "@vitest/browser-playwright";
const dirname =
typeof __dirname !== "undefined"
? __dirname
: path.dirname(fileURLToPath(import.meta.url));
const apiRuntimeFilePath = path.resolve(dirname, ".time-pilot/high-score-api.json");
const defaultHighScoreApiUrl = "http://localhost:8787";
const apiPortScanStart = 8787;
const apiPortScanAttempts = 20;
const getHighScoreApiUrl = (): string => {
if (process.env.HIGH_SCORE_API_URL) {
return process.env.HIGH_SCORE_API_URL;
}
try {
const runtime = JSON.parse(
readFileSync(apiRuntimeFilePath, "utf8")
) as Partial<{ url: string }>;
if (typeof runtime.url === "string" && runtime.url.startsWith("http")) {
return runtime.url;
}
} catch {
// The API server writes this file once it starts; use the default before then.
}
return defaultHighScoreApiUrl;
};
const getHighScoreApiCandidates = (): string[] => {
const urls = new Set<string>([getHighScoreApiUrl(), defaultHighScoreApiUrl]);
for (let offset = 0; offset < apiPortScanAttempts; offset += 1) {
urls.add(`http://localhost:${apiPortScanStart + offset}`);
}
return [...urls];
};
const readRequestBody = async (
request: import("node:http").IncomingMessage
): Promise<Buffer | undefined> => {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
return chunks.length > 0 ? Buffer.concat(chunks) : undefined;
};
const createProxyHeaders = (
request: import("node:http").IncomingMessage
): Headers => {
const headers = new Headers();
Object.entries(request.headers).forEach(([key, value]) => {
if (key.toLowerCase() === "host" || value === undefined) {
return;
}
if (Array.isArray(value)) {
value.forEach((entry) => headers.append(key, entry));
return;
}
headers.set(key, value);
});
return headers;
};
const isLikelyApiResponse = (response: Response): boolean => {
const contentType = response.headers.get("content-type") ?? "";
return response.status !== 404 && contentType.includes("application/json");
};
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
export default defineConfig({
base: process.env.VITE_BASE_PATH ?? "/",
define: {
__TIME_PILOT_VERSION__: JSON.stringify(packageJson.version),
},
plugins: [
{
name: "time-pilot-html-version",
transformIndexHtml: (html) =>
html.replaceAll("%TIME_PILOT_VERSION%", packageJson.version),
},
{
name: "time-pilot-api-proxy",
configureServer: (server) => {
server.middlewares.use(async (request, response, next) => {
if (!request.url?.startsWith("/api/")) {
next();
return;
}
const body = await readRequestBody(request);
const headers = createProxyHeaders(request);
try {
let proxiedResponse: Response | null = null;
for (const candidate of getHighScoreApiCandidates()) {
try {
const candidateResponse = await fetch(new URL(request.url, candidate), {
body,
headers,
method: request.method,
redirect: "manual",
});
if (isLikelyApiResponse(candidateResponse)) {
proxiedResponse = candidateResponse;
break;
}
} catch {
proxiedResponse = null;
}
}
if (!proxiedResponse) {
throw new Error("High score API unavailable");
}
response.statusCode = proxiedResponse.status;
proxiedResponse.headers.forEach((value, key) => {
response.setHeader(key, value);
});
response.end(Buffer.from(await proxiedResponse.arrayBuffer()));
} catch {
response.statusCode = 502;
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.end(JSON.stringify({ error: "api_unavailable" }));
}
});
},
},
react(),
],
build: {
rollupOptions: {
input: {
about: path.resolve(dirname, "about/index.html"),
main: path.resolve(dirname, "index.html"),
pwa: path.resolve(dirname, "pwa/index.html"),
},
output: {
assetFileNames: (assetInfo) =>
assetInfo.names.some((name) => name.endsWith(".css"))
? "assets/app.css"
: "assets/[name][extname]",
chunkFileNames: "assets/[name].js",
entryFileNames: "assets/app.js",
},
},
},
server: {
host: "0.0.0.0",
open: true,
},
test: {
projects: [
{
extends: true,
test: {
environment: "jsdom",
globals: true,
setupFiles: ["src/test/setup.ts"],
},
},
{
extends: true,
plugins: [
// The plugin will run tests for the stories defined in your Storybook config
// See options at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon#storybooktest
storybookTest({
configDir: path.join(dirname, ".storybook"),
}),
],
test: {
name: "storybook",
browser: {
enabled: true,
headless: true,
provider: playwright({}),
instances: [
{
browser: "chromium",
},
],
},
},
},
],
},
});