-
-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathvite.config.ts
More file actions
416 lines (393 loc) · 12.1 KB
/
Copy pathvite.config.ts
File metadata and controls
416 lines (393 loc) · 12.1 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import { sentryTanstackStart } from '@sentry/tanstackstart-react/vite'
import { defineConfig } from 'vite'
import type { PluginOption } from 'vite'
import { redact } from '@tanstack/redact/vite'
import contentCollections from '@content-collections/vite'
import { devtools as tanstackDevtools } from '@tanstack/devtools-vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import tailwindcss from '@tailwindcss/vite'
import { cloudflare } from '@cloudflare/vite-plugin'
import { analyzer } from 'vite-bundle-analyzer'
import viteReact from '@vitejs/plugin-react'
import { randomUUID } from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import {
getImportFallbackRepoDirs,
localDocsDevPath,
localDocsDevTokenHeader,
} from './src/utils/local-repo-path.server'
import { localNotebookAi } from './scripts/local-notebook-ai-vite'
const isDev = process.env.NODE_ENV !== 'production'
const shouldUseRedact = process.env.DISABLE_REDACT !== 'true'
const localRedactPackageRoot = process.env.LOCAL_REDACT_PACKAGE_ROOT
const shouldUseSentryPlugin =
process.env.NODE_ENV === 'production' &&
Boolean(process.env.SENTRY_AUTH_TOKEN)
const shouldBuildSourcemaps =
shouldUseSentryPlugin || process.env.BUILD_SOURCEMAPS === 'true'
const SITE_URL = 'https://tanstack.com'
const localDocsDevToken = isDev ? randomUUID() : ''
const localEnvPath = path.resolve(__dirname, '.env.local')
const defaultCheckoutEnvDir = path.join(os.homedir(), 'GitHub/tanstack.com')
const envDir =
!fs.existsSync(localEnvPath) &&
fs.existsSync(path.join(defaultCheckoutEnvDir, '.env.local'))
? defaultCheckoutEnvDir
: __dirname
function localDocsDevFiles(): PluginOption {
return {
name: 'tanstack-local-docs-files',
apply: 'serve',
configureServer(server) {
server.middlewares.use(async (request, response, next) => {
if (!request.url) return next()
const url = new URL(request.url, 'http://localhost')
if (url.pathname !== localDocsDevPath) return next()
if (
request.method !== 'GET' ||
request.headers[localDocsDevTokenHeader] !== localDocsDevToken
) {
response.statusCode = 404
response.end()
return
}
const repo = url.searchParams.get('repo')
const filepath = url.searchParams.get('path')
if (
!repo ||
!/^[a-zA-Z0-9._-]+$/.test(repo) ||
!filepath ||
!isContainedRepoPath(filepath)
) {
response.statusCode = 400
response.end()
return
}
const documentsModuleUrl = pathToFileURL(
path.join(server.config.root, 'src/utils/documents.server.ts'),
).href
const repoDirs = Array.from(
new Set([
...(process.env.TANSTACK_LOCAL_REPOS_DIR
? [path.resolve(process.env.TANSTACK_LOCAL_REPOS_DIR, repo)]
: []),
path.resolve(os.homedir(), 'GitHub', repo),
...getImportFallbackRepoDirs(documentsModuleUrl, repo),
]),
)
const localFilePath = repoDirs
.map((repoDir) => ({
filepath: path.resolve(repoDir, filepath),
repoDir,
}))
.find(
(candidate) =>
isPathInside(candidate.repoDir, candidate.filepath) &&
fs.existsSync(candidate.filepath) &&
fs.statSync(candidate.filepath).isFile(),
)?.filepath
if (!localFilePath) {
response.statusCode = 404
response.end()
return
}
try {
const content = await fs.promises.readFile(localFilePath)
response.statusCode = 200
response.setHeader('Cache-Control', 'no-store')
response.setHeader('Content-Type', 'text/plain; charset=utf-8')
response.end(content)
} catch (error) {
next(error)
}
})
},
}
}
function isContainedRepoPath(filepath: string) {
const normalized = path.normalize(filepath)
return (
!normalized.startsWith('..') &&
!normalized.includes(`${path.sep}..${path.sep}`) &&
!path.isAbsolute(normalized)
)
}
function isPathInside(parent: string, child: string) {
const relativePath = path.relative(parent, child)
return (
relativePath !== '' &&
!relativePath.startsWith('..') &&
!path.isAbsolute(relativePath)
)
}
// Runtime-specific `react-dom/server` variants aren't in @tanstack/redact/vite's
// default alias map. Funnel them all to `@tanstack/redact/server` at the
// top-level resolve so Workers get a single server implementation.
const serverVariantAliases: Record<string, string> = {
'react-dom/server': '@tanstack/redact/server',
'react-dom/server.edge': '@tanstack/redact/server',
'react-dom/server.node': '@tanstack/redact/server',
'react-dom/server.bun': '@tanstack/redact/server',
'react-dom/server.browser': '@tanstack/redact/server',
'react-dom/static.edge': '@tanstack/redact/server',
'react-dom/static.node': '@tanstack/redact/server',
'react-dom/static': '@tanstack/redact/server',
}
const useSyncExternalStoreShimIndexAlias = {
find: /^use-sync-external-store\/shim\/index\.js$/,
replacement: '@tanstack/redact',
}
// These browser-facing packages are imported by SSR assets. Bundle them into
// Worker server output so the runtime never loads their raw package entries.
const serverBundledClientPackages = [
...(shouldUseRedact ? ['@tanstack/redact'] : []),
/^@radix-ui\//,
'@kapaai/react-sdk',
'@tanstack/highlight',
'@tanstack/markdown',
'@tanstack/react-hotkeys',
'@tanstack/react-pacer',
'@tanstack/react-table',
'zustand',
/^@fingerprintjs\//,
]
const routerSsrPackages = [
'@tanstack/history',
'@tanstack/query-core',
'@tanstack/react-query',
'@tanstack/react-router',
'@tanstack/react-router-ssr-query',
'@tanstack/react-router/ssr',
'@tanstack/react-router/ssr/server',
'@tanstack/router-core',
]
export default defineConfig({
envDir,
define: {
__TANSTACK_ENABLE_SERVER_BUILDER_GENERATION__: JSON.stringify(true),
__TANSTACK_ENABLE_IMAGE_TRANSFORMATIONS__: JSON.stringify(true),
__TANSTACK_LOCAL_DOCS_TOKEN__: JSON.stringify(localDocsDevToken),
__TANSTACK_SITE_URL__: JSON.stringify(SITE_URL),
},
resolve: {
alias: [
{
find: '~',
replacement: path.resolve(__dirname, './src'),
},
{
find: 'ejs',
replacement: path.resolve(
__dirname,
'./src/server/runtime/ejs-compat.server.ts',
),
},
{
find: 'unicorn-magic',
replacement: 'unicorn-magic/node',
},
...(shouldUseRedact
? [
useSyncExternalStoreShimIndexAlias,
...Object.entries(serverVariantAliases).map(
([find, replacement]) => ({
find,
replacement,
}),
),
]
: []),
],
},
server: {
port: Number(process.env.PORT) || 3000,
// WebContainer headers for /builder route (SharedArrayBuffer support)
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
},
// Watch linked @tanstack/cli for hot reload during development
watch: isDev
? {
ignored: ['!**/node_modules/@tanstack/cli/**'],
}
: undefined,
},
environments: {
ssr: {
optimizeDeps: {
exclude: ['@tanstack/create'],
},
resolve: {
noExternal: [...serverBundledClientPackages, ...routerSsrPackages],
},
},
},
ssr: {
external: [],
noExternal: [
'@uploadthing/react',
'file-selector',
'normalize-wheel',
'@tanstack/react-hotkeys',
'@webcontainer/api',
...serverBundledClientPackages,
...routerSsrPackages,
],
},
optimizeDeps: {
exclude: [
'postgres',
// CTA packages use execa which has a broken unicorn-magic dependency
'@tanstack/create',
'discord-interactions',
// Don't pre-bundle CLI so we always get fresh changes during dev
...(isDev ? ['@tanstack/cli'] : []),
],
},
build: {
// The lazy iconography route intentionally ships the complete Phosphor
// registry so every icon can be browsed without follow-up requests.
chunkSizeWarningLimit: 4_000,
minify: 'esbuild',
sourcemap: shouldBuildSourcemaps,
reportCompressedSize: false,
rollupOptions: {
output: {
manualChunks: (id) => {
if (
id.includes('/node_modules/@tanstack/react-start') ||
id.includes('/node_modules/@tanstack/start-')
) {
return 'tanstack-start'
}
if (
id.includes('/src/db/types.ts') ||
id.includes('/src/libraries/ids.ts')
) {
return 'shared-constants'
}
if (
id.includes('/node_modules/@tanstack/react-router') ||
id.includes('/node_modules/@tanstack/router-core') ||
id.includes('/node_modules/@tanstack/history')
) {
return 'tanstack-router'
}
if (
id.includes('/node_modules/@tanstack/react-query') ||
id.includes('/node_modules/@tanstack/query-core')
) {
return 'tanstack-query'
}
// Vendor chunk splitting for better caching
if (id.includes('node_modules')) {
if (
id.includes('node_modules/react-dom/') ||
id.includes('node_modules/react/') ||
id.includes('node_modules/scheduler/')
) {
return 'react'
}
}
},
},
},
},
plugins: [
localNotebookAi(),
localDocsDevFiles(),
cloudflare({
viteEnvironment: { name: 'ssr' },
}),
...(shouldUseRedact
? [
redact(
localRedactPackageRoot
? {
packageRoots: {
'@tanstack/redact': localRedactPackageRoot,
},
}
: undefined,
),
]
: []),
...(isDev
? [
tanstackDevtools({
// Console piping mirrors server logs into the browser and browser
// logs back into Vite. A streamed server error can recursively echo
// through that bridge and flood the dev server log.
consolePiping: {
enabled: false,
},
// react-instantsearch's <Configure> forwards all JSX props as
// Algolia search parameters. Injecting `data-tsd-source` as a
// JSX attr leaks it into the request and Algolia 400s with
// "Unknown parameter: data-tsd-source" — breaks site search in dev.
injectSource: {
enabled: true,
ignore: { components: ['Configure'] },
},
}),
]
: []),
tanstackStart({
server: {
build: {
inlineCss: false,
},
},
importProtection: {
behavior: 'error',
client: {
files: ['**/*.server.*', '**/server/**'],
specifiers: [
'@tanstack/react-start/server',
'uploadthing/server',
/^@modelcontextprotocol\/sdk\/server\//,
'discord-interactions',
],
},
},
router: {
codeSplittingOptions: {
defaultBehavior: [
[
'component',
'pendingComponent',
'errorComponent',
'notFoundComponent',
'loader',
],
],
},
},
}),
viteReact(),
...(shouldUseSentryPlugin
? [
sentryTanstackStart({
authToken: process.env.SENTRY_AUTH_TOKEN,
org: 'tanstack',
project: 'tanstack-com',
}),
]
: []),
contentCollections(),
tailwindcss(),
...(process.env.ANALYZE
? [
analyzer({
analyzerMode: 'json',
fileName: 'bundle-analysis',
defaultSizes: 'stat',
}),
]
: []),
],
})