Repository navigation
Expand file tree
/
Copy pathexample-webcontainer-start.ts
More file actions
247 lines (210 loc) · 7.38 KB
/
Copy pathexample-webcontainer-start.ts
File metadata and controls
247 lines (210 loc) · 7.38 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
import type { ExampleRuntime } from './example-workspace'
export const tanStackStartAsyncContextCompatibility =
'tanstack-start-async-context'
export const tanStackStartViteConfigPath = '/.tanstack/vite.config.mjs'
const tanStackStartAsyncContextPluginPath =
'/.tanstack/async-context-plugin.mjs'
const viteConfigPaths = [
'/vite.config.ts',
'/vite.config.mts',
'/vite.config.js',
'/vite.config.mjs',
] as const
const tanStackNoExternal = [
'@tanstack/start**',
'@tanstack/react-start**',
'@tanstack/router**',
'@tanstack/react-router**',
] as const
export function getTanStackStartOxcRuntimeSpecifier(
rolldownPackageSource: string,
) {
const packageJson: unknown = JSON.parse(rolldownPackageSource)
if (!isRecord(packageJson) || !isRecord(packageJson.dependencies)) {
throw new Error(
'Could not determine the Oxc runtime version from Rolldown.',
)
}
const typesVersion = packageJson.dependencies['@oxc-project/types']
if (
typeof typesVersion !== 'string' ||
!/^=?\d+\.\d+\.\d+$/.test(typesVersion)
) {
throw new Error(
'Could not determine the Oxc runtime version from Rolldown.',
)
}
return `@oxc-project/runtime@${typesVersion.replace(/^=/, '')}`
}
export function prepareTanStackStartWebContainerFiles(
files: Record<string, string>,
runtime: ExampleRuntime,
): Record<string, string> {
if (runtime.compatibility !== tanStackStartAsyncContextCompatibility) {
return { ...files }
}
const authoredConfigPath = viteConfigPaths.find(
(path) => files[path] !== undefined,
)
if (!authoredConfigPath) {
throw new Error(
'TanStack Start async-context compatibility requires an ESM vite.config file.',
)
}
if (
files[tanStackStartViteConfigPath] !== undefined ||
files[tanStackStartAsyncContextPluginPath] !== undefined
) {
throw new Error(
'The example contains files reserved for the TanStack Start runtime.',
)
}
return {
...files,
[tanStackStartViteConfigPath]: createViteConfigSource(authoredConfigPath),
[tanStackStartAsyncContextPluginPath]:
tanStackStartAsyncContextPluginSource,
}
}
/**
* Rolldown 1.2.9+ stamps `__napiBindingTarget` after load. In WebContainer
* the native linux addon and the WASI loader disagree on that stamp.
* Point the loader at the matching wasm32-wasi package instead.
*/
export function getRolldownWasiBindingSpecifier(rolldownPackageSource: string) {
const packageJson: unknown = JSON.parse(rolldownPackageSource)
if (!isRecord(packageJson) || typeof packageJson.version !== 'string') {
throw new Error('Could not determine the Rolldown version.')
}
if (!/^\d+\.\d+\.\d+/.test(packageJson.version)) {
throw new Error('Could not determine the Rolldown version.')
}
return `@rolldown/binding-wasm32-wasi@${packageJson.version}`
}
export function getWebContainerStartEnv(runtime: ExampleRuntime) {
const env: Record<string, string> = {
__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: '.webcontainer-api.io',
}
if (runtime.compatibility === tanStackStartAsyncContextCompatibility) {
env.NAPI_RS_NATIVE_LIBRARY_PATH = '@rolldown/binding-wasm32-wasi'
// Nitro's default node-worker never finishes loading in WebContainer.
env.NITRO_DEV_RUNNER = 'self'
}
return env
}
export function getWebContainerStartCommand(runtime: ExampleRuntime) {
if (runtime.compatibility !== tanStackStartAsyncContextCompatibility) {
return {
command: runtime.start.command,
args: [...runtime.start.args],
}
}
if (
(runtime.start.command !== 'npm' && runtime.start.command !== 'pnpm') ||
runtime.start.args[0] !== 'run'
) {
throw new Error(
'TanStack Start async-context compatibility requires an npm or pnpm run start command.',
)
}
const args = [...runtime.start.args]
// npm needs `--` to forward args. pnpm would pass the `--` itself on to Vite, which ignores what follows.
if (runtime.start.command === 'npm' && !args.includes('--')) args.push('--')
args.push('--config', tanStackStartViteConfigPath.slice(1))
return { command: runtime.start.command, args }
}
function createViteConfigSource(authoredConfigPath: string) {
const authoredConfigImport = `..${authoredConfigPath}`
return `import authoredConfig from ${JSON.stringify(authoredConfigImport)}
import { defineConfig, mergeConfig } from 'vite'
import { tanStackStartAsyncContextPlugin } from './async-context-plugin.mjs'
const noExternal = ${JSON.stringify(tanStackNoExternal)}
export default defineConfig(async (configEnv) => {
const resolvedAuthoredConfig =
typeof authoredConfig === 'function'
? await authoredConfig(configEnv)
: await authoredConfig
return mergeConfig(resolvedAuthoredConfig, {
plugins: [tanStackStartAsyncContextPlugin()],
resolve: { noExternal },
ssr: { noExternal },
nitro: { devServer: { runner: 'self' } },
})
})
`
}
export const tanStackStartAsyncContextPluginSource = `import { transformWithOxc } from 'vite'
const scriptIdPattern = /\\.[cm]?[jt]sx?(?:$|\\?)/
export const oxcAsyncGeneratorRuntimeId =
'@oxc-project/runtime/helpers/wrapAsyncGenerator'
export const serializableAsyncGeneratorRuntimeSpecifier =
'virtual:tanstack-webcontainer-serializable-async-generator'
export const serializableAsyncGeneratorRuntimeId =
'\\0tanstack:webcontainer-serializable-async-generator'
export function tanStackStartAsyncContextPlugin() {
return {
name: 'tanstack:webcontainer-start-async-context',
enforce: 'post',
resolveId: {
order: 'pre',
handler(source) {
if (source === serializableAsyncGeneratorRuntimeSpecifier) {
return serializableAsyncGeneratorRuntimeId
}
},
},
load(id) {
if (id !== serializableAsyncGeneratorRuntimeId) return
return \`import wrapAsyncGenerator from \${JSON.stringify(oxcAsyncGeneratorRuntimeId)}
export default function wrapSerializableAsyncGenerator(generator) {
const createIterator = wrapAsyncGenerator(generator)
return function () {
const iterator = createIterator.apply(this, arguments)
if (Object.prototype.propertyIsEnumerable.call(iterator, '_invoke')) {
Object.defineProperty(iterator, '_invoke', { enumerable: false })
}
return iterator
}
}
\`
},
transform: {
order: 'post',
async handler(code, id, options) {
const environment = this.environment
const isServer = environment
? environment.config.consumer === 'server'
: options?.ssr === true
if (
!isServer ||
id.includes('/.tanstack/') ||
(!scriptIdPattern.test(id) &&
!id.startsWith('virtual:') &&
!id.startsWith('\\0')) ||
(!code.includes('async') && !code.includes('await'))
) {
return
}
const filename =
id.startsWith('virtual:') || id.startsWith('\\0')
? '/tanstack-start-virtual-module.js'
: id.split('?')[0]
const result = await transformWithOxc(code, filename, {
target: 'es2016',
sourcemap: true,
})
return {
code: result.code.replaceAll(
oxcAsyncGeneratorRuntimeId,
serializableAsyncGeneratorRuntimeSpecifier,
),
map: result.map,
}
},
},
}
}
`
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}