-
-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathimport-environment.ts
More file actions
251 lines (232 loc) · 8.94 KB
/
Copy pathimport-environment.ts
File metadata and controls
251 lines (232 loc) · 8.94 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
import assert from 'node:assert'
import fs from 'node:fs'
import path from 'node:path'
import { exactRegex } from '@rolldown/pluginutils'
import MagicString from 'magic-string'
import { stripLiteral } from 'strip-literal'
import type { Plugin, ResolvedConfig } from 'vite'
import type { RscPluginManager } from '../plugin'
import {
createVirtualPlugin,
normalizeRelativePath,
normalizeRollupOptionsInput,
} from './utils'
import { evalValue } from './vite-utils'
export const ENV_IMPORTS_MANIFEST_NAME = '__vite_rsc_env_imports_manifest.js'
const ENV_IMPORTS_MANIFEST_PLACEHOLDER = 'virtual:vite-rsc/env-imports-manifest'
const ENV_IMPORTS_ENTRY_FALLBACK = 'virtual:vite-rsc/env-imports-entry-fallback'
export type EnvironmentImportMeta = {
resolvedId: string
targetEnv: string
sourceEnv: string
specifier: string
}
// ensure at least one entry since otherwise rollup build fails
export function ensureEnvironmentImportsEntryFallback({
environments,
}: ResolvedConfig): void {
for (const [name, config] of Object.entries(environments)) {
if (name === 'client') continue
const input = normalizeRollupOptionsInput(
config.build?.rollupOptions?.input,
)
if (Object.keys(input).length === 0) {
config.build = config.build || {}
config.build.rollupOptions = config.build.rollupOptions || {}
config.build.rollupOptions.input = {
__vite_rsc_env_imports_entry_fallback: ENV_IMPORTS_ENTRY_FALLBACK,
}
}
}
}
export function vitePluginImportEnvironment(
manager: RscPluginManager,
): Plugin[] {
return [
{
name: 'rsc:import-environment',
resolveId: {
filter: { id: exactRegex(ENV_IMPORTS_MANIFEST_PLACEHOLDER) },
handler(source) {
// Use placeholder as external, renderChunk will replace with correct relative path
if (source === ENV_IMPORTS_MANIFEST_PLACEHOLDER) {
return { id: ENV_IMPORTS_MANIFEST_PLACEHOLDER, external: true }
}
},
},
buildStart() {
// Emit discovered entries during build
if (this.environment.mode !== 'build') return
// Collect unique entries targeting this environment (may be imported from multiple sources)
const emitted = new Set<string>()
for (const byTargetEnv of Object.values(
manager.environmentImportMetaMap,
)) {
const imports = byTargetEnv[this.environment.name]
if (!imports) continue
for (const meta of Object.values(imports)) {
if (!emitted.has(meta.resolvedId)) {
emitted.add(meta.resolvedId)
this.emitFile({
type: 'chunk',
id: meta.resolvedId,
})
}
}
}
},
transform: {
filter: { code: 'import.meta.viteRsc.import' },
async handler(code, id) {
if (!code.includes('import.meta.viteRsc.import')) return
const { server } = manager
const s = new MagicString(code)
for (const match of stripLiteral(code).matchAll(
/import\.meta\.viteRsc\.import\s*(<[\s\S]*?>)?\s*\(([\s\S]*?)\)/dg,
)) {
// match[2] is the arguments (after optional type parameter)
const [argStart, argEnd] = match.indices![2]!
const argCode = code.slice(argStart, argEnd).trim()
// Parse: ('./entry.ssr', { environment: 'ssr' })
const [specifier, options]: [string, { environment: string }] =
evalValue(`[${argCode}]`)
const environmentName = options.environment
// Resolve specifier relative to importer
let resolvedId: string
if (this.environment.mode === 'dev') {
const targetEnv = server.environments[environmentName]
assert(
targetEnv,
`[vite-rsc] unknown environment '${environmentName}'`,
)
const resolved = await targetEnv.pluginContainer.resolveId(
specifier,
id,
)
assert(
resolved,
`[vite-rsc] failed to resolve '${specifier}' in environment '${environmentName}'`,
)
resolvedId = resolved.id
} else {
// Build mode: resolve in target environment config
const targetEnvConfig =
manager.config.environments[environmentName]
assert(
targetEnvConfig,
`[vite-rsc] unknown environment '${environmentName}'`,
)
// Use this environment's resolver for now
const resolved = await this.resolve(specifier, id)
assert(
resolved,
`[vite-rsc] failed to resolve '${specifier}' in environment '${environmentName}'`,
)
resolvedId = resolved.id
}
// Track discovered entry, keyed by [sourceEnv][targetEnv][resolvedId]
const sourceEnv = this.environment.name
const targetEnv = environmentName
manager.environmentImportMetaMap[sourceEnv] ??= {}
manager.environmentImportMetaMap[sourceEnv]![targetEnv] ??= {}
manager.environmentImportMetaMap[sourceEnv]![targetEnv]![
resolvedId
] = {
resolvedId,
targetEnv,
sourceEnv,
specifier,
}
let replacement: string
if (this.environment.mode === 'dev') {
replacement = `globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(${JSON.stringify(environmentName)}, ${JSON.stringify(resolvedId)})`
} else {
// Build: emit manifest lookup with static import
// The manifest is generated in buildApp after all builds complete
// Use placeholder that renderChunk will replace with correct relative path
// Use relative ID for stable builds across different machines
const relativeId = manager.toRelativeId(resolvedId)
replacement = `(await import(${JSON.stringify(ENV_IMPORTS_MANIFEST_PLACEHOLDER)})).default[${JSON.stringify(relativeId)}]()`
}
const [start, end] = match.indices![0]!
s.overwrite(start, end, replacement)
}
if (s.hasChanged()) {
return {
code: s.toString(),
map: s.generateMap({ hires: 'boundary' }),
}
}
},
},
renderChunk(code, chunk) {
if (code.includes(ENV_IMPORTS_MANIFEST_PLACEHOLDER)) {
const replacement = normalizeRelativePath(
path.relative(
path.join(chunk.fileName, '..'),
ENV_IMPORTS_MANIFEST_NAME,
),
)
code = code.replaceAll(
ENV_IMPORTS_MANIFEST_PLACEHOLDER,
() => replacement,
)
return { code }
}
return
},
},
createVirtualPlugin(
ENV_IMPORTS_ENTRY_FALLBACK.slice('virtual:'.length),
() => {
// TODO: how to avoid warning during scan build?
// > Generated an empty chunk: "__vite_rsc_env_imports_entry_fallback".
return `export default "__vite_rsc_env_imports_entry_fallback";`
},
),
]
}
export function writeEnvironmentImportsManifest(
manager: RscPluginManager,
): void {
if (Object.keys(manager.environmentImportMetaMap).length === 0) {
return
}
// Write manifest to each source environment's output
for (const [sourceEnv, byTargetEnv] of Object.entries(
manager.environmentImportMetaMap,
)) {
const sourceOutDir = manager.config.environments[sourceEnv]!.build.outDir
const manifestPath = path.join(sourceOutDir, ENV_IMPORTS_MANIFEST_NAME)
let code = 'export default {\n'
for (const [_targetEnv, imports] of Object.entries(byTargetEnv)) {
// Lookup fileName from bundle
for (const [resolvedId, meta] of Object.entries(imports)) {
const bundle = manager.bundles[meta.targetEnv]
if (!bundle) {
throw new Error(
`[vite-rsc] missing bundle for environment import: ${meta.targetEnv}`,
)
}
const chunk = Object.values(bundle).find(
(c) => c.type === 'chunk' && c.facadeModuleId === resolvedId,
)
if (!chunk) {
throw new Error(
`[vite-rsc] missing output for environment import: ${resolvedId}`,
)
}
const targetOutDir =
manager.config.environments[meta.targetEnv]!.build.outDir
const relativePath = normalizeRelativePath(
path.relative(sourceOutDir, path.join(targetOutDir, chunk.fileName)),
)
// Use relative ID for stable builds across different machines
const relativeId = manager.toRelativeId(resolvedId)
code += ` ${JSON.stringify(relativeId)}: () => import(${JSON.stringify(relativePath)}),\n`
}
}
code += '}\n'
fs.writeFileSync(manifestPath, code)
}
}