-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathvite.config.ts
More file actions
338 lines (309 loc) · 10.6 KB
/
Copy pathvite.config.ts
File metadata and controls
338 lines (309 loc) · 10.6 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import type { NormalizedOutputOptions, OutputBundle, PluginContext } from 'rolldown';
import { bundleStats } from 'rollup-plugin-bundle-stats';
import { visualizer } from 'rollup-plugin-visualizer';
import { fileURLToPath } from 'url';
import { defineConfig, loadEnv, normalizePath, type Plugin, type PluginOption, type UserConfig } from 'vite';
import { type Target, viteStaticCopy } from 'vite-plugin-static-copy';
import { watchAndRun } from 'vite-plugin-watch-and-run';
import buildGitInfoPlugin from './plugins/gitInfo.ts';
import packageJson from './package.json' with { type: 'json' };
const DIR_NAME = dirname(fileURLToPath(import.meta.url));
const PRODUCTION_URL = 'https://web.telegram.org/a';
const { version: APP_VERSION } = packageJson;
const BUNDLE_STATS_OUT_DIR = 'bundle-stats';
const DEFAULT_BUNDLE_STATS_BASELINE_FILE = 'baseline.json';
const BUNDLE_STATS_VISUALIZER_FILE = 'visualizer.html';
const WORKER_BUNDLE_COLLECTOR_PLUGIN_NAME = 'telegram:collect-worker-report-bundle';
const BUNDLE_REPORT_PLUGIN_SUFFIX = ':with-workers';
const DEV_SERVER_WATCH_IGNORES = [
'**/.cache/**',
'**/dist/**',
'**/tauri/target/**',
];
const DEV_BUNDLE_WARMUP_CLIENT_FILES = [
'src/bundles/auth.ts',
'src/bundles/main.ts',
'src/bundles/extra.ts',
'src/bundles/calls.ts',
'src/bundles/stars.ts',
];
const IMAGE_ASSET_RE = /\.(?:avif|gif|jpe?g|png|svg|webp)$/i;
const WATCHED_STATIC_COPY_TARGETS: Target[] = [
{
src: normalizePath(resolve(DIR_NAME, 'node_modules/opus-recorder/dist/decoderWorker.min.wasm')),
dest: 'assets',
rename: { stripBase: true },
},
];
const UNWATCHED_STATIC_COPY_TARGETS: Target[] = [
{
src: normalizePath(resolve(DIR_NAME, 'node_modules/emoji-data-ios/img-apple-64/**/*')),
dest: '.',
rename: { stripBase: 2 },
},
{
src: normalizePath(resolve(DIR_NAME, 'node_modules/emoji-data-ios/img-apple-160/**/*')),
dest: '.',
rename: { stripBase: 2 },
},
];
type BundleReportPlugin = {
name: string;
generateBundle?: unknown;
};
type BundleReportHook = (
this: PluginContext,
outputOptions: NormalizedOutputOptions,
bundle: OutputBundle,
isWrite: boolean,
) => void | Promise<void>;
export default defineConfig(({ mode }): UserConfig => {
const env = loadEnv(mode, process.cwd(), '');
setViteEnv(env);
const {
HEAD = '',
BUNDLE_STATS: bundleStatsValue = '',
BUNDLE_STATS_BASELINE_PATH: bundleStatsBaselinePath = '',
BUNDLE_STATS_VISUALIZER: bundleStatsVisualizerValue = '',
HTTPS_CERT_PATH: httpsCertPath = '',
HTTPS_KEY_PATH: httpsKeyPath = '',
} = env;
const appEnv = env.APP_ENV || (mode === 'development' ? 'development' : 'production');
const appMockedClient = env.APP_MOCKED_CLIENT || '';
const defaultAppTitle = `Telegram${appEnv !== 'production' ? ' Beta' : ''}`;
const baseUrl = env.BASE_URL || PRODUCTION_URL;
const appTitle = env.APP_TITLE || defaultAppTitle;
const isProductionApp = appEnv === 'production';
const appleIcon = isProductionApp ? 'apple-touch-icon' : 'apple-touch-icon-dev';
const mainIcon = isProductionApp ? 'icon-192x192' : 'icon-dev-192x192';
const manifest = isProductionApp ? 'site.webmanifest' : 'site_dev.webmanifest';
const csp = buildCsp(appEnv);
const isDevelopmentMode = mode === 'development';
const telegramApiId = env.TELEGRAM_API_ID || '';
const telegramApiHash = env.TELEGRAM_API_HASH || '';
const workerReportBundles: OutputBundle[] = [];
const plugins: PluginOption[] = [
buildGitInfoPlugin({
appEnv,
head: HEAD,
isDevelopmentMode,
rootDir: DIR_NAME,
}),
viteStaticCopy({ targets: WATCHED_STATIC_COPY_TARGETS }),
viteStaticCopy({
targets: UNWATCHED_STATIC_COPY_TARGETS,
watch: {
options: {
ignored: '**/*',
},
},
}),
isDevelopmentMode && watchAndRun([
{
name: 'lang',
watch: buildProjectPath('src/assets/localization/fallback.strings'),
watchFile: (filePath) => Promise.resolve(isProjectFile(filePath, 'src/assets/localization/fallback.strings')),
run: 'npm run lang:ts',
},
{
name: 'gramjs',
watch: buildProjectPath('src/lib/gramjs/tl/static'),
watchFile: (filePath) => Promise.resolve(isPathInsideProjectDirectory(filePath, 'src/lib/gramjs/tl/static')),
run: 'npm run gramjs:tl',
},
{
name: 'icons',
watch: buildProjectPath('src/assets/font-icons'),
watchFile: (filePath) => Promise.resolve(isPathInsideProjectDirectory(filePath, 'src/assets/font-icons')),
run: 'npm run icons:build',
},
]),
];
if (bundleStatsVisualizerValue === '1') {
plugins.push(createBundleReportPlugin(visualizer((outputOptions) => ({
filename: resolve(
DIR_NAME,
outputOptions.dir,
BUNDLE_STATS_OUT_DIR,
BUNDLE_STATS_VISUALIZER_FILE,
),
open: true,
template: 'treemap',
})), workerReportBundles));
}
if (bundleStatsValue === '1') {
plugins.push(createBundleReportPlugin(bundleStats({
html: true,
json: true,
compare: Boolean(bundleStatsBaselinePath),
baseline: !bundleStatsBaselinePath, // For master branch upload
baselineFilepath: bundleStatsBaselinePath || DEFAULT_BUNDLE_STATS_BASELINE_FILE,
outDir: BUNDLE_STATS_OUT_DIR,
}), workerReportBundles));
if (bundleStatsBaselinePath) {
// Write current PR stats for the compact GitHub comment
plugins.push(createBundleReportPlugin(bundleStats({
html: false,
json: false,
compare: false,
baseline: true,
baselineFilepath: DEFAULT_BUNDLE_STATS_BASELINE_FILE,
outDir: BUNDLE_STATS_OUT_DIR,
silent: true,
}), workerReportBundles));
}
}
const shouldCollectWorkerReportBundles = bundleStatsVisualizerValue === '1' || bundleStatsValue === '1';
if (appEnv !== 'test' && (!telegramApiId || !telegramApiHash)) {
throw new Error('Missing required Telegram API credentials');
}
setViteEnv({
TG_APP_ENV: appEnv,
TG_APP_MOCKED_CLIENT: appMockedClient,
TG_APP_NAME: env.APP_NAME || '',
TG_APP_TITLE: appTitle,
TG_PUBLIC_URL: baseUrl,
TG_CSP: csp,
TG_APPLE_ICON: appleIcon,
TG_MAIN_ICON: mainIcon,
TG_MANIFEST: manifest,
TG_TELEGRAM_API_ID: telegramApiId,
TG_TELEGRAM_API_HASH: telegramApiHash,
TG_TEST_SESSION: env.TEST_SESSION || '',
});
return {
base: './',
envPrefix: ['VITE_', 'TG_'],
assetsInclude: ['**/*.tgs'],
optimizeDeps: {
exclude: ['temml'],
},
define: {
APP_VERSION: JSON.stringify(APP_VERSION),
},
resolve: {
tsconfigPaths: true,
alias: [
...(appMockedClient === '1' ? [{
find: /^(?:\.\/client|(?:\.\.\/)*lib\/gramjs\/client)\/TelegramClient$/,
replacement: resolve(DIR_NAME, 'src/lib/gramjs/client/MockClient.ts'),
}] : []),
],
},
css: {
modules: {
localsConvention: 'camelCase',
generateScopedName: isProductionApp ? '[hash:base64:8]' : '[name]__[local]',
},
},
server: {
host: '0.0.0.0',
port: 1234,
strictPort: true,
headers: {
'Content-Security-Policy': csp,
'Service-Worker-Allowed': '/',
},
https: getHttpsConfig(httpsCertPath, httpsKeyPath),
warmup: {
clientFiles: DEV_BUNDLE_WARMUP_CLIENT_FILES,
},
watch: {
ignored: DEV_SERVER_WATCH_IGNORES,
},
},
build: {
sourcemap: true,
assetsInlineLimit: (filePath) => (IMAGE_ASSET_RE.test(filePath) ? false : undefined),
},
worker: {
plugins: shouldCollectWorkerReportBundles ? () => [
createWorkerBundleCollectorPlugin(workerReportBundles),
] : undefined,
rolldownOptions: {
output: {
entryFileNames: '[name]-[hash].js',
},
},
},
plugins,
};
});
function createBundleReportPlugin(plugin: BundleReportPlugin, workerReportBundles: OutputBundle[]): Plugin {
return {
name: `${plugin.name}${BUNDLE_REPORT_PLUGIN_SUFFIX}`,
async generateBundle(outputOptions, bundle, isWrite) {
const generateBundle = parseBundleReportHook(plugin.generateBundle);
await generateBundle?.call(
this,
outputOptions,
mergeOutputBundles(bundle, workerReportBundles),
isWrite,
);
},
};
}
function createWorkerBundleCollectorPlugin(workerReportBundles: OutputBundle[]): Plugin {
return {
name: WORKER_BUNDLE_COLLECTOR_PLUGIN_NAME,
generateBundle(_outputOptions, bundle) {
workerReportBundles.push({ ...bundle });
},
};
}
function mergeOutputBundles(bundle: OutputBundle, workerReportBundles: OutputBundle[]): OutputBundle {
const result: OutputBundle = {};
Object.assign(result, bundle, ...workerReportBundles);
return result;
}
function parseBundleReportHook(hook: unknown): BundleReportHook | undefined {
if (typeof hook === 'function') {
return hook as BundleReportHook;
}
if (!hook || typeof hook !== 'object' || !('handler' in hook) || typeof hook.handler !== 'function') {
return undefined;
}
return hook.handler as BundleReportHook;
}
function setViteEnv(env: Record<string, string>) {
Object.entries(env).forEach(([key, value]) => {
process.env[key] = value;
});
}
function buildCsp(appEnv: string) {
return `
default-src 'self';
connect-src 'self' wss://*.web.telegram.org blob: http: https: ${appEnv === 'development' ? 'wss: ipc:' : ''};
script-src 'self' 'wasm-unsafe-eval'
https://t.me/_websync_ https://telegram.me/_websync_ https://telegram.dog/_websync_;
worker-src 'self'${appEnv === 'development' ? ' blob:' : ''};
style-src 'self' 'unsafe-inline';
font-src 'self' data:;
img-src 'self' data: blob: https://ss3.4sqi.net/img/categories_v2/;
media-src 'self' blob: data:;
object-src 'none';
frame-src http: https:
bitkeep: bnc: bybitapp: echooo: imtokenv2: mytonwallet-tc:
nicegram-tc: safepal-tc: tonkeeper-pro-tc: tonkeeper-tc:;
base-uri 'none';
form-action 'none';`
.replace(/\s+/g, ' ').trim();
}
function buildProjectPath(projectPath: string) {
return normalizePath(resolve(DIR_NAME, projectPath));
}
function isProjectFile(filePath: string, projectPath: string) {
return normalizePath(filePath) === buildProjectPath(projectPath);
}
function isPathInsideProjectDirectory(filePath: string, projectPath: string) {
return normalizePath(filePath).startsWith(`${buildProjectPath(projectPath)}/`);
}
function getHttpsConfig(httpsCertPath: string, httpsKeyPath: string) {
if (!httpsCertPath || !httpsKeyPath) return undefined;
return {
cert: readFileSync(httpsCertPath),
key: readFileSync(httpsKeyPath),
};
}