-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathplugin.ts
More file actions
655 lines (584 loc) · 20.6 KB
/
Copy pathplugin.ts
File metadata and controls
655 lines (584 loc) · 20.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
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import { VIRTUAL_MODULES } from '@tanstack/start-server-core'
import { resolve as resolvePath } from 'pathe'
import {
SERVER_FN_LOOKUP,
TRANSFORM_ID_REGEX,
VITE_ENVIRONMENT_NAMES,
} from '../../constants'
import { detectKindsInCode } from '../../start-compiler/compiler'
import { getTransformCodeFilterForEnv } from '../../start-compiler/config'
import {
createCompilerVirtualModuleIdPattern,
createStartCompiler,
loadCompilerVirtualModule,
mergeServerFnsById,
} from '../../start-compiler/host'
import { generateServerFnResolverModule } from '../../start-compiler/server-fn-resolver-module'
import { cleanId } from '../../start-compiler/utils'
import { createVirtualModule } from '../createVirtualModule'
import {
MissingHydrateSourceError,
createHydrateCompilerPlugin,
} from '../../hydrate-when-transform'
import { resolveViteId } from '../../utils'
import {
createViteDevServerFnModuleSpecifierEncoder,
decodeViteDevServerModuleSpecifier,
} from './module-specifier'
import { mergeHotUpdateModules } from './hot-update'
import type {
CompileStartFrameworkOptions,
StartCompilerImportTransform,
StartCompilerPlugin,
} from '../../types'
import type {
GenerateFunctionIdFnOptional,
ServerFn,
} from '../../start-compiler/types'
import type { Environment, EnvironmentModuleNode, PluginOption } from 'vite'
// Re-export from shared constants for backwards compatibility
export { SERVER_FN_LOOKUP }
const validateServerFnIdVirtualModule = `virtual:tanstack-start-validate-server-fn-id`
const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split'
type ModuleInvalidationEnvironment = {
moduleGraph: {
getModulesByFile: (file: string) => Set<EnvironmentModuleNode> | undefined
invalidateModule: (
mod: EnvironmentModuleNode,
seen?: Set<EnvironmentModuleNode>,
) => void
}
}
type ViteModuleLoadOptions = {
devId?: string
load: (options: { id: string }) => Promise<{ code?: string | null } | null>
error: (message: string) => never
}
async function loadViteModuleFromEnvironment(
environment: Environment,
id: string,
opts: ViteModuleLoadOptions,
): Promise<string | undefined> {
if (environment.mode === 'build') {
const loaded = await opts.load({ id })
return loaded?.code ?? ''
}
if (environment.mode === 'dev') {
await environment.transformRequest(opts.devId ?? id)
return undefined
}
opts.error(
`could not load module ${id}: unknown environment mode ${environment.mode}`,
)
}
function invalidateMatchingFileModules(
environment: ModuleInvalidationEnvironment,
ids: Iterable<string>,
shouldInvalidate: (mod: EnvironmentModuleNode) => boolean,
) {
const seen = new Set<EnvironmentModuleNode>()
const invalidatedModules: Array<EnvironmentModuleNode> = []
for (const id of ids) {
const fileModules = environment.moduleGraph.getModulesByFile(cleanId(id))
if (!fileModules) {
continue
}
for (const fileModule of fileModules) {
if (!shouldInvalidate(fileModule)) {
continue
}
environment.moduleGraph.invalidateModule(fileModule, seen)
invalidatedModules.push(fileModule)
}
}
return invalidatedModules
}
function invalidateServerFnProviderModules(
environment: {
moduleGraph: {
getModulesByFile: (file: string) => Set<EnvironmentModuleNode> | undefined
invalidateModule: (
mod: EnvironmentModuleNode,
seen?: Set<EnvironmentModuleNode>,
) => void
}
},
ids: Iterable<string>,
) {
return invalidateMatchingFileModules(
environment,
ids,
(fileModule) => fileModule.id?.includes(TSS_SERVERFN_SPLIT_PARAM) ?? false,
)
}
function invalidateServerFnLookupModules(
environment: ModuleInvalidationEnvironment,
ids: Iterable<string>,
) {
invalidateMatchingFileModules(
environment,
ids,
(fileModule) => fileModule.id?.includes(SERVER_FN_LOOKUP) ?? false,
)
}
function invalidateCompilerVirtualModules(
environment: ModuleInvalidationEnvironment,
ids: Iterable<string>,
pattern: RegExp | undefined,
) {
if (!pattern) {
return []
}
return invalidateMatchingFileModules(environment, ids, (fileModule) => {
if (!fileModule.id) {
return false
}
pattern.lastIndex = 0
return pattern.test(fileModule.id)
})
}
function getServerFnProviderIds(ids: Iterable<string>) {
const providerIds = new Set<string>()
for (const id of ids) {
const cleanedId = cleanId(id)
providerIds.add(`${cleanedId}?${TSS_SERVERFN_SPLIT_PARAM}`)
}
return providerIds
}
function invalidateModuleNodes(
environment: {
moduleGraph: {
invalidateModule: (
mod: EnvironmentModuleNode,
seen?: Set<EnvironmentModuleNode>,
) => void
}
},
modules: Iterable<EnvironmentModuleNode>,
) {
const seen = new Set<EnvironmentModuleNode>()
for (const mod of modules) {
environment.moduleGraph.invalidateModule(mod, seen)
}
}
function getDevServerFnValidatorModule(): string {
return `
export async function getServerFnById(id, _access) {
const validateIdImport = ${JSON.stringify(validateServerFnIdVirtualModule)} + '?id=' + id
await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport)
const decoded = Buffer.from(id, 'base64url').toString('utf8')
const devServerFn = JSON.parse(decoded)
const mod = await import(/* @vite-ignore */ devServerFn.file)
return mod[devServerFn.export]
}
`
}
function parseIdQuery(id: string): {
filename: string
query: {
[k: string]: string
}
} {
if (!id.includes('?')) return { filename: id, query: {} }
const [filename, rawQuery] = id.split(`?`, 2) as [string, string]
const query = Object.fromEntries(new URLSearchParams(rawQuery))
return { filename, query }
}
export interface StartCompilerPluginOptions {
framework: CompileStartFrameworkOptions
environments: Array<{
name: string
type: 'client' | 'server'
getServerFnById?: string
}>
/**
* Custom function ID generator (optional).
*/
generateFunctionId?: GenerateFunctionIdFnOptional
compilerTransforms?: Array<StartCompilerImportTransform> | undefined
compilerPlugins?: Array<StartCompilerPlugin> | undefined
serverFnProviderModuleDirectives?: ReadonlyArray<string> | undefined
/**
* The Vite environment name for the server function provider.
*/
providerEnvName: string
}
export function startCompilerPlugin(
opts: StartCompilerPluginOptions,
): PluginOption {
const compilers = new Map<string, ReturnType<typeof createStartCompiler>>()
const compilerPlugins = [
createHydrateCompilerPlugin(),
...(opts.compilerPlugins ?? []),
]
const compilerVirtualModuleIdPattern =
createCompilerVirtualModuleIdPattern(compilerPlugins)
const environmentByName = new Map(
opts.environments.map((environment) => [environment.name, environment]),
)
// Shared registry of server functions across all environments
const serverFnsById: Record<string, ServerFn> = {}
const onServerFnsById = (d: Record<string, ServerFn>) => {
mergeServerFnsById(serverFnsById, d)
}
let root = process.cwd()
let bundledDev = false
// Determine which environments need the resolver (getServerFnById)
// SSR environment always needs the resolver for server-side calls
// Provider environment needs it for the actual implementation
const ssrEnvName = VITE_ENVIRONMENT_NAMES.server
// SSR is the provider when the provider environment is the default server environment
const ssrIsProvider = opts.providerEnvName === ssrEnvName
// Environments that need the resolver: SSR (for server calls) and provider (for implementation)
const appliedResolverEnvironments = new Set(
ssrIsProvider ? [opts.providerEnvName] : [ssrEnvName, opts.providerEnvName],
)
function perEnvServerFnPlugin(environment: {
name: string
type: 'client' | 'server'
}): PluginOption {
const compilerTransforms =
environment.name === opts.providerEnvName
? opts.compilerTransforms
: undefined
const serverFnProviderModuleDirectives =
environment.name === opts.providerEnvName
? opts.serverFnProviderModuleDirectives
: undefined
// Derive transform code filter from KindDetectionPatterns (single source of truth)
const transformCodeFilter = getTransformCodeFilterForEnv(environment.type, {
compilerTransforms,
compilerPlugins,
})
return {
name: `tanstack-start-core::server-fn:${environment.name}`,
enforce: 'pre',
applyToEnvironment(env) {
return env.name === environment.name
},
configResolved(config) {
root = config.root
bundledDev = !!config.experimental.bundledDev
},
buildStart() {
if (
this.environment.mode === 'build' ||
(bundledDev &&
this.environment.name === VITE_ENVIRONMENT_NAMES.client)
) {
// Vite app builds can run multiple Rolldown build phases with fresh
// plugin drivers. The compiler host closes over this hook context for
// load/resolve, so do not reuse it after a previous driver was closed.
compilers.delete(this.environment.name)
}
},
watchChange(id) {
if (bundledDev && this.environment.mode === 'dev') {
compilers.get(this.environment.name)?.invalidateModule(id)
}
},
transform: {
filter: {
id: {
exclude: new RegExp(`${SERVER_FN_LOOKUP}$`),
include: TRANSFORM_ID_REGEX,
},
code: {
include: transformCodeFilter,
},
},
async handler(code, id) {
let compiler = compilers.get(this.environment.name)
if (!compiler) {
// Default to 'dev' mode for unknown environments (conservative: no caching)
const mode = this.environment.mode === 'build' ? 'build' : 'dev'
compiler = createStartCompiler({
env: environment.type,
envName: environment.name,
root,
mode,
framework: opts.framework,
providerEnvName: opts.providerEnvName,
generateFunctionId: opts.generateFunctionId,
compilerTransforms,
compilerPlugins,
serverFnProviderModuleDirectives,
onServerFnsById,
getKnownServerFns: () => serverFnsById,
encodeModuleSpecifierInDev:
mode === 'dev'
? createViteDevServerFnModuleSpecifierEncoder(root)
: undefined,
loadModule: async (id: string) => {
const code = await loadViteModuleFromEnvironment(
this.environment,
id,
{
load: (options) => this.load(options),
error: (message) => this.error(message),
devId: `${id}?${SERVER_FN_LOOKUP}`,
},
)
if (code !== undefined) {
compiler!.ingestModule({ code, id })
}
},
resolveId: async (source: string, importer?: string) => {
const r = await this.resolve(source, importer)
if (r) {
if (!r.external) {
// Keep import-protection's own virtual ids (e.g. mock-edge)
// `\0`-prefixed: `loadModule`/`this.load()` routes them to the
// import-protection `load` handler by matching on the `\0`
// prefix. Stripping it via cleanId() makes the load fall
// through to vite:load-fallback, which fs.readFile()s the
// bare id and throws ENOENT in build mode (#7725).
if (r.id.startsWith('\0tanstack-start-import-protection:')) {
return r.id
}
return cleanId(r.id)
}
}
return null
},
})
compilers.set(this.environment.name, compiler)
}
// Detect which kinds are present in this file before parsing
const detectedKinds = detectKindsInCode(code, environment.type, {
compilerTransforms,
})
const result = await compiler.compile({
id,
code,
detectedKinds,
warn: (message) => this.warn(message),
})
return result
},
},
hotUpdate(ctx) {
const compiler = compilers.get(this.environment.name)
const idsToInvalidate = new Set<string>()
const transitiveCompilerImportersToInvalidate = new Set<string>()
const importerModulesToInvalidate = new Set<EnvironmentModuleNode>()
const changedIds: Array<string> = []
ctx.modules.forEach((m) => {
if (m.id) {
idsToInvalidate.add(m.id)
changedIds.push(m.id)
}
})
const deletedIds = compiler?.invalidateModules(changedIds) ?? new Set()
ctx.modules.forEach((m) => {
if (m.id) {
if (deletedIds.has(cleanId(m.id))) {
transitiveCompilerImportersToInvalidate.add(cleanId(m.id))
m.importers.forEach((importer) => {
if (importer.id) {
idsToInvalidate.add(importer.id)
importerModulesToInvalidate.add(importer)
transitiveCompilerImportersToInvalidate.add(
cleanId(importer.id),
)
}
})
}
}
})
const finishHotUpdate = async () => {
if (
environment.type === 'server' &&
compiler &&
transitiveCompilerImportersToInvalidate.size > 0
) {
const seenImporters = new Set(
transitiveCompilerImportersToInvalidate,
)
const nestedImporters =
await compiler.getTransitiveImporters(seenImporters)
for (const nestedImporterId of nestedImporters) {
seenImporters.add(nestedImporterId)
}
for (const importerId of seenImporters) {
idsToInvalidate.add(importerId)
}
compiler.invalidateModules(seenImporters)
}
invalidateModuleNodes(this.environment, importerModulesToInvalidate)
invalidateServerFnLookupModules(this.environment, idsToInvalidate)
const compilerVirtualModules = invalidateCompilerVirtualModules(
this.environment,
idsToInvalidate,
compilerVirtualModuleIdPattern,
)
if (environment.type !== 'server') {
return mergeHotUpdateModules(ctx.modules, compilerVirtualModules)
}
invalidateModuleNodes(this.environment, ctx.modules)
const providerIdsToInvalidate =
getServerFnProviderIds(idsToInvalidate)
compiler?.invalidateModules(providerIdsToInvalidate)
const providerModules = invalidateServerFnProviderModules(
this.environment,
[...idsToInvalidate, ...providerIdsToInvalidate],
)
return mergeHotUpdateModules(ctx.modules, [
...compilerVirtualModules,
...providerModules,
])
}
return finishHotUpdate()
},
}
}
return [
...opts.environments.map(perEnvServerFnPlugin),
{
name: 'tanstack-start-core:capture-server-fn-module-lookup',
// we only need this plugin in dev mode
apply: 'serve',
applyToEnvironment(env) {
return !!opts.environments.find((e) => e.name === env.name)
},
transform: {
filter: {
id: new RegExp(`${SERVER_FN_LOOKUP}$`),
},
handler(code, id) {
const compiler = compilers.get(this.environment.name)
compiler?.ingestModule({ code, id: cleanId(id) })
},
},
},
{
name: 'tanstack-start-core:compiler-virtual-module',
enforce: 'pre',
load: {
filter: {
id: compilerVirtualModuleIdPattern ?? /$^/,
},
async handler(id) {
const environment = environmentByName.get(this.environment.name)
if (!environment || !compilerVirtualModuleIdPattern) {
return null
}
const loadVirtualModule = () =>
loadCompilerVirtualModule(compilerPlugins, {
id,
root,
env: environment.type,
envName: this.environment.name,
})
try {
return loadVirtualModule()
} catch (error) {
if (!(error instanceof MissingHydrateSourceError)) {
throw error
}
}
const sourceId = cleanId(id)
await loadViteModuleFromEnvironment(this.environment, sourceId, {
load: (options) => this.load(options),
error: (message) => this.error(message),
})
return loadVirtualModule()
},
},
},
// Validate server function ID in dev mode
{
name: 'tanstack-start-core:validate-server-fn-id',
apply: 'serve',
load: {
filter: {
id: new RegExp(resolveViteId(validateServerFnIdVirtualModule)),
},
async handler(id) {
const parsed = parseIdQuery(id)
const fnId = parsed.query.id
if (fnId && serverFnsById[fnId]) {
return `export {}`
}
// ID not yet registered — the source file may not have been
// transformed in this dev session yet (e.g. cold restart with
// cached client). Try to decode the ID, discover the source
// file, trigger its compilation, and re-check.
if (fnId) {
try {
const decoded = JSON.parse(
Buffer.from(fnId, 'base64url').toString('utf8'),
)
if (
typeof decoded.file === 'string' &&
typeof decoded.export === 'string'
) {
// Use the Vite when to decode the module specifier
// back to the original source file path.
const sourceFile = decodeViteDevServerModuleSpecifier(
decoded.file,
)
if (sourceFile) {
// Resolve to absolute path
const absPath = resolvePath(root, sourceFile)
// Trigger transform of the source file in this environment,
// which will compile createServerFn calls and populate
// serverFnsById as a side effect.
if (this.environment.mode !== 'dev') {
this.error(
`could not validate server function ID ${fnId}: unknown environment mode ${this.environment.mode}`,
)
}
await this.environment.transformRequest(
`${absPath}?${SERVER_FN_LOOKUP}`,
)
// Re-check after lazy compilation
if (serverFnsById[fnId]) {
return `export {}`
}
}
}
} catch {
// Decoding or fetching failed — fall through to error
}
}
this.error(`Invalid server function ID: ${fnId}`)
},
},
},
// Manifest plugin for server environments
createVirtualModule({
name: 'tanstack-start-core:server-fn-resolver',
moduleId: VIRTUAL_MODULES.serverFnResolver,
enforce: 'pre',
applyToEnvironment: (env) => {
return appliedResolverEnvironments.has(env.name)
},
load() {
if (this.environment.name !== opts.providerEnvName) {
const mod = opts.environments.find(
(e) => e.name === this.environment.name,
)?.getServerFnById
if (mod) {
return mod
}
this.error(
`No getServerFnById implementation found for caller environment: ${this.environment.name}`,
)
}
if (this.environment.mode !== 'build') {
return getDevServerFnValidatorModule()
}
// When SSR is the provider, server-only-referenced functions aren't in the manifest,
// so no isClientReferenced check is needed.
// When SSR is NOT the provider (custom provider env), server-only-referenced
// functions ARE in the manifest and need the isClientReferenced check to
// block direct client HTTP requests to server-only-referenced functions.
return generateServerFnResolverModule({
serverFnsById,
includeClientReferencedCheck: !ssrIsProvider,
})
},
}),
]
}