Repository navigation
Expand file tree
/
Copy pathvite.config.mts
More file actions
312 lines (286 loc) · 11.5 KB
/
Copy pathvite.config.mts
File metadata and controls
312 lines (286 loc) · 11.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
import react from '@vitejs/plugin-react'
import * as fs from 'fs'
// @ts-expect-error multiformats package.json exports omit types
import { CID } from 'multiformats/cid'
// @ts-expect-error multiformats package.json exports omit types
import * as raw from 'multiformats/codecs/raw'
// @ts-expect-error multiformats package.json exports omit types
import { sha256 } from 'multiformats/hashes/sha2'
import * as path from 'path'
import { dirname, resolve } from 'path'
import * as ssri from 'ssri'
import { fileURLToPath } from 'url'
import type { PluginOption } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import { analyzer } from 'vite-bundle-analyzer'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import tsconfigPaths from 'vite-tsconfig-paths'
import { cspMeta, headers, serializeCsp } from './headers'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const VITE_CSP_META = serializeCsp(cspMeta)
const publicFilesEnvVars: Record<string, string> = {
VITE_CSP_META: JSON.stringify(VITE_CSP_META),
}
const publicPath = path.join(__dirname, 'public')
for (const dirent of fs.readdirSync(publicPath, { withFileTypes: true })) {
if (!dirent.isFile()) continue
const mungedName = dirent.name
.toUpperCase()
.split('')
.map(x => (/^[0-9A-Z]$/.test(x) ? x : '_'))
.join('')
const data = fs.readFileSync(path.join(publicPath, dirent.name))
const integrity = ssri.fromData(data, {
strict: true,
algorithms: ['sha256'],
})
publicFilesEnvVars[`VITE_SRI_${mungedName}`] = JSON.stringify(integrity)
const digest = sha256.digest(data)
const cid = CID.create(1, raw.code, digest).toString()
publicFilesEnvVars[`VITE_CID_${mungedName}`] = JSON.stringify(cid)
}
// For whatever reason, globalThis is not defined for the local esbuild environment while
// using the vite-plugin-node-polyfills plugin. This plugin will appropriately define globalThis
// to fix this scenario (may be resolved in a future release of vite-plugin-node-polyfills hopefully).
// hdwallet workspace packages depend on ethers v5 (BigNumber, providers, etc.)
// but Vite pre-bundles the root's ethers v6 for bare 'ethers' imports.
// This plugin conditionally resolves 'ethers' to 'ethers5' (npm:ethers@5.7.2)
// only when the importer is an hdwallet source file, preserving ethers v6 for the root app.
const resolveEthersV5ForHdwallet: PluginOption = {
name: 'resolve-ethers-v5-hdwallet',
enforce: 'pre',
resolveId(source, importer) {
if (source === 'ethers' && importer && /\/packages\/hdwallet-/.test(importer)) {
return this.resolve('ethers5', importer, { skipSelf: true })
}
},
}
// hdwallet workspace packages depend on bech32 v1 (flat API: bech32.toWords, bech32.encode)
// but Vite pre-bundles the root's bech32 v2 for bare 'bech32' imports.
// v2 exports { bech32, bech32m } instead of flat functions, breaking hdwallet at runtime.
// This plugin resolves 'bech32' to the 'bech32-v1' aliased package (npm:bech32@1.1.4) for hdwallet source files,
// following the same pattern as resolveEthersV5ForHdwallet with ethers5.
const resolveBech32V1ForHdwallet: PluginOption = {
name: 'resolve-bech32-v1-hdwallet',
enforce: 'pre',
resolveId(source, importer) {
if (source === 'bech32' && importer && /\/packages\/hdwallet-/.test(importer)) {
return this.resolve('bech32-v1', importer, { skipSelf: true })
}
},
}
const defineGlobalThis: PluginOption = {
name: 'define-global-this',
enforce: 'pre',
transform(code) {
if (code.includes('vite-plugin-node-polyfills')) {
return `if (typeof globalThis === 'undefined') {
globalThis = typeof window !== 'undefined' ? window :
typeof global !== 'undefined' ? global :
typeof self !== 'undefined' ? self : this;
};${code}`
}
},
}
const serveCompressedAssets: PluginOption = {
name: 'serve-compressed-assets',
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (!req.url?.startsWith('/generated/') || !req.url?.includes('.json')) {
return next()
}
const acceptEncoding = req.headers['accept-encoding'] || ''
const urlWithoutQuery = req.url.split('?')[0]
const filePath = path.join(publicPath, urlWithoutQuery)
if (!filePath.startsWith(publicPath + path.sep)) {
return next()
}
const tryServeCompressed = (
encoding: string,
extension: string,
contentType: string,
): boolean => {
const compressedPath = `${filePath}.${extension}`
if (fs.existsSync(compressedPath)) {
res.setHeader('Content-Type', contentType)
res.setHeader('Content-Encoding', encoding)
res.setHeader('Vary', 'Accept-Encoding')
fs.createReadStream(compressedPath).pipe(res)
return true
}
return false
}
if (acceptEncoding.includes('br') && tryServeCompressed('br', 'br', 'application/json')) {
return
}
if (acceptEncoding.includes('gzip') && tryServeCompressed('gzip', 'gz', 'application/json')) {
return
}
next()
})
},
}
// eslint-disable-next-line import/no-default-export
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
const port = Number(process.env.PORT) || 3000
return {
plugins: [
resolveEthersV5ForHdwallet,
resolveBech32V1ForHdwallet,
mode === 'development' && !process.env.DEPLOY && defineGlobalThis,
nodePolyfills({
globals: {
Buffer: true,
global: true,
process: true,
},
protocolImports: true,
}),
react({
babel: {
plugins: [
[
'babel-plugin-react-compiler',
{
compilationMode: 'infer', // Auto-compile components following Rules of React
},
],
],
},
}),
tsconfigPaths(),
process.env.ANALYZE === 'true' &&
analyzer({
analyzerMode: 'server',
analyzerPort: 8888,
openAnalyzer: true,
}),
serveCompressedAssets,
],
define: {
...Object.fromEntries(
Object.entries(publicFilesEnvVars).map(([key, value]) => [`import.meta.env.${key}`, value]),
),
...Object.fromEntries(
Object.entries(publicFilesEnvVars).map(([key, value]) => [`process.env.${key}`, value]),
),
...Object.fromEntries(
Object.entries(env)
.filter(([key]) => key.startsWith('VITE_'))
.map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)]),
),
},
server: {
port,
headers,
host: '0.0.0.0',
allowedHosts: true,
proxy: {
'/user-api': {
target: env.USER_API_URL || 'http://localhost:3002',
changeOrigin: true,
rewrite: path => path.replace(/^\/user-api/, ''),
},
'/swaps-api': {
target: env.SWAPS_API_URL || 'http://localhost:3001',
changeOrigin: true,
rewrite: path => path.replace(/^\/swaps-api/, ''),
},
'/notifications-api': {
target: env.NOTIFICATIONS_API_URL || 'http://localhost:3003',
changeOrigin: true,
rewrite: path => path.replace(/^\/notifications-api/, ''),
},
},
},
preview: {
port,
headers,
},
worker: {
format: 'es',
},
resolve: {
// Ensure a single copy of React packages (prevents duplicate bundling in pnpm)
dedupe: ['react', 'react-dom', 'react-is', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
alias: {
'@': resolve(__dirname, './src'),
'ethers/lib/utils': 'ethers5/lib/utils.js',
'ethers/lib/utils.js': 'ethers5/lib/utils.js',
'dayjs/locale': resolve(__dirname, 'node_modules/dayjs/locale'),
'@shapeshiftoss/hdwallet-native/nativeEvents': resolve(
__dirname,
'./packages/hdwallet-native/src/nativeEvents.ts',
),
'@shapeshiftoss/hdwallet-native/crypto/revocable': resolve(
__dirname,
'./packages/hdwallet-native/src/crypto/isolation/engines/default/revocable.ts',
),
'@shapeshiftoss/hdwallet-core': resolve(__dirname, './packages/hdwallet-core/src'),
'@shapeshiftoss/caip': resolve(__dirname, './packages/caip/src'),
'@shapeshiftoss/types': resolve(__dirname, './packages/types/src'),
},
},
build: {
target: 'esnext',
commonjsOptions: {
transformMixedEsModules: true,
exclude: ['@shapeshiftoss/caip', '@shapeshiftoss/types'],
},
chunkSizeWarningLimit: 2000,
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
},
output: {
manualChunks: id => {
if (id.includes('node_modules')) {
// buffer polyfill must be in its own chunk to avoid circular deps between ui↔sdk in pnpm
// Matches: node_modules/buffer/, node_modules/base64-js/, node_modules/ieee754/,
// and also vite-plugin-node-polyfills/shims/buffer/ and safe-buffer
if (/\/node_modules\/(buffer|base64-js|ieee754|safe-buffer)\//.test(id))
return 'polyfills'
if (/vite-plugin-node-polyfills\/shims\/buffer\//.test(id)) return 'polyfills'
if (id.match(/(framer-motion|@visx|@coral-xyz)/)) return 'ui'
if (id.match(/(react-icons|@react-spring|react-datepicker|react-dom)/)) return 'react'
// Ensure core 'react' package is in the 'react' chunk to prevent duplication in pnpm
if (/\/node_modules\/react\//.test(id) && !/\/@[^/]+\/react/.test(id)) return 'react'
if (id.match(/(dayjs|lodash|@formatjs)/)) return 'utils'
if (id.match(/(@redux|@tanstack)/)) return 'state'
if (id.match(/(@sentry|mixpanel|@moralisweb3|moralis)/)) return 'sdk'
if (id.match(/(embla-carousel)/)) return 'carousel'
if (id.includes('lightweight-charts')) return 'charts'
if (id.includes('html5-qrcode')) return 'qr-scanner'
if (id.includes('react-scan')) return 'react-scan'
if (id.includes('styled-components')) return 'styled-components'
if (id.includes('date-fns')) return 'date-fns'
if (id.includes('valibot')) return 'valibot'
if (id.includes('@0noco/graphqllsp')) return 'graphqllsp'
return null
}
if (id.includes('assets/translations')) return 'translations'
if (id.includes('localAssetData')) return 'local-asset-data'
return null
},
hashCharacters: 'hex',
},
onwarn(warning, warn) {
// Ignore annotation warnings with /*#__PURE__*/ pattern
if (warning.message.includes('/*#__PURE__*/') || warning.message.includes('A comment'))
return
// Ignore eval warnings in dependencies
if (warning.code === 'EVAL' && warning.id?.includes('node_modules')) return
// Ignore dynamic import chunking warnings
const dynamicImport = 'dynamic import will not move module into another chunk'
if (warning.plugin === 'vite:reporter' && warning.message.includes(dynamicImport)) return
warn(warning)
},
},
minify: mode === 'development' && !process.env.DEPLOY ? false : 'esbuild',
sourcemap: mode === 'development' && !process.env.DEPLOY ? 'inline' : false,
outDir: 'build',
},
}
})