-
Notifications
You must be signed in to change notification settings - Fork 35
/
dev-server.ts
272 lines (245 loc) · 7.68 KB
/
dev-server.ts
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
import { getRequestListener } from '@hono/node-server'
import { minimatch } from 'minimatch'
import type { Plugin as VitePlugin, ViteDevServer, Connect } from 'vite'
import fs from 'fs'
import type http from 'http'
import path from 'path'
import type { Env, Fetch, EnvFunc, Adapter, LoadModule } from './types.js'
export type DevServerOptions = {
entry?: string
export?: string
injectClientScript?: boolean
exclude?: (string | RegExp)[]
ignoreWatching?: (string | RegExp)[]
env?: Env | EnvFunc
loadModule?: LoadModule
/**
* This can be used to inject environment variables into the worker from your wrangler.toml for example,
* by making use of the helper function `getPlatformProxy` from `wrangler`.
*
* @example
*
* ```ts
* import { defineConfig } from 'vite'
* import devServer from '@hono/vite-dev-server'
* import getPlatformProxy from 'wrangler'
*
* export default defineConfig(async () => {
* const { env, dispose } = await getPlatformProxy()
* return {
* plugins: [
* devServer({
* adapter: {
* env,
* onServerClose: dispose
* },
* }),
* ],
* }
* })
* ```
*
*
*/
adapter?: Adapter | Promise<Adapter> | (() => Adapter | Promise<Adapter>)
}
export const defaultOptions: Required<Omit<DevServerOptions, 'env' | 'adapter' | 'loadModule'>> = {
entry: './src/index.ts',
export: 'default',
injectClientScript: true,
exclude: [
/.*\.css$/,
/.*\.ts$/,
/.*\.tsx$/,
/^\/@.+$/,
/\?t\=\d+$/,
/^\/favicon\.ico$/,
/^\/static\/.+/,
/^\/node_modules\/.*/,
],
ignoreWatching: [/\.wrangler/, /\.mf/],
}
export function devServer(options?: DevServerOptions): VitePlugin {
let publicDirPath = ''
const entry = options?.entry ?? defaultOptions.entry
const plugin: VitePlugin = {
name: '@hono/vite-dev-server',
configResolved(config) {
publicDirPath = config.publicDir
},
configureServer: async (server) => {
async function createMiddleware(server: ViteDevServer): Promise<Connect.HandleFunction> {
return async function (
req: http.IncomingMessage,
res: http.ServerResponse,
next: Connect.NextFunction
): Promise<void> {
if (req.url) {
const filePath = path.join(publicDirPath, req.url)
try {
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
return next()
}
} catch {
// do nothing
}
}
const exclude = options?.exclude ?? defaultOptions.exclude
for (const pattern of exclude) {
if (req.url) {
if (pattern instanceof RegExp) {
if (pattern.test(req.url)) {
return next()
}
} else if (minimatch(req.url?.toString(), pattern)) {
return next()
}
}
}
let loadModule: LoadModule
if (options?.loadModule) {
loadModule = options.loadModule
} else {
loadModule = async (server, entry) => {
const appModule = await server.ssrLoadModule(entry)
const exportName = options?.export ?? defaultOptions.export
const app = appModule[exportName] as { fetch: Fetch }
if (!app) {
throw new Error(`Failed to find a named export "${exportName}" from ${entry}`)
}
return app
}
}
let app: { fetch: Fetch }
try {
app = await loadModule(server, entry)
} catch (e) {
return next(e)
}
getRequestListener(
async (request) => {
let env: Env = {}
if (options?.env) {
if (typeof options.env === 'function') {
env = { ...env, ...(await options.env()) }
} else {
env = { ...env, ...options.env }
}
}
const adapter = await getAdapterFromOptions(options)
if (adapter?.env) {
env = { ...env, ...adapter.env }
}
const executionContext = adapter?.executionContext ?? {
waitUntil: async (fn) => fn,
passThroughOnException: () => {
throw new Error('`passThroughOnException` is not supported')
},
}
const response = await app.fetch(request, env, executionContext)
/**
* If the response is not instance of `Response`, throw it so that it can be handled
* by our custom errorHandler and passed through to Vite
*/
if (!(response instanceof Response)) {
throw response
}
if (
options?.injectClientScript !== false &&
response.headers.get('content-type')?.match(/^text\/html/)
) {
const script = '<script>import("/@vite/client")</script>'
return injectStringToResponse(response, script)
}
return response
},
{
overrideGlobalObjects: false,
errorHandler: (e) => {
let err: Error
if (e instanceof Error) {
err = e
server.ssrFixStacktrace(err)
} else if (typeof e === 'string') {
err = new Error(`The response is not an instance of "Response", but: ${e}`)
} else {
err = new Error(`Unknown error: ${e}`)
}
next(err)
},
}
)(req, res)
}
}
server.middlewares.use(await createMiddleware(server))
server.httpServer?.on('close', async () => {
const adapter = await getAdapterFromOptions(options)
if (adapter?.onServerClose) {
await adapter.onServerClose()
}
})
},
config: () => {
return {
server: {
watch: {
ignored: options?.ignoreWatching ?? defaultOptions.ignoreWatching,
},
},
}
},
}
return plugin
}
const getAdapterFromOptions = async (
options: DevServerOptions | undefined
): Promise<Adapter | undefined> => {
let adapter = options?.adapter
if (typeof adapter === 'function') {
adapter = adapter()
}
if (adapter instanceof Promise) {
adapter = await adapter
}
return adapter
}
function injectStringToResponse(response: Response, content: string) {
const stream = response.body
const newContent = new TextEncoder().encode(content)
if (!stream) {
return null
}
const reader = stream.getReader()
const newContentReader = new ReadableStream({
start(controller) {
controller.enqueue(newContent)
controller.close()
},
}).getReader()
const combinedStream = new ReadableStream({
async start(controller) {
for (;;) {
const [existingResult, newContentResult] = await Promise.all([
reader.read(),
newContentReader.read(),
])
if (existingResult.done && newContentResult.done) {
controller.close()
break
}
if (!existingResult.done) {
controller.enqueue(existingResult.value)
}
if (!newContentResult.done) {
controller.enqueue(newContentResult.value)
}
}
},
})
const headers = new Headers(response.headers)
headers.delete('content-length')
return new Response(combinedStream, {
headers,
status: response.status,
})
}