This repository has been archived by the owner on Oct 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
371 lines (327 loc) · 9.77 KB
/
index.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
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
import { fileURLToPath } from 'node:url';
import { resolve } from 'node:path';
import {
DevEnvironment as ViteDevEnvironment,
BuildEnvironment,
createIdResolver,
type EnvironmentOptions,
} from 'vite';
import { HotChannel, HotPayload, ResolvedConfig, Plugin } from 'vite';
import {
SourcelessWorkerOptions,
unstable_getMiniflareWorkerOptions,
} from 'wrangler';
import {
Miniflare,
Response as MiniflareResponse,
type MessageEvent,
type WebSocket,
} from 'miniflare';
import * as debugDumps from './debug-dumps';
import { getModuleFallbackCallback, ResolveIdFunction } from './moduleFallback';
export type DevEnvironment = ViteDevEnvironment & {
metadata: EnvironmentMetadata;
api: {
getHandler: ({
entrypoint,
}: {
entrypoint: string;
}) => Promise<(req: Request) => Response | Promise<Response>>;
};
};
export type CloudflareEnvironmentOptions = {
config?: string;
};
const runtimeName = 'workerd';
/**
* Metadata regarding the environment that consumers can use to get more information about the env when needed
*/
export type EnvironmentMetadata = {
runtimeName: string;
};
export function cloudflare(
userOptions: CloudflareEnvironmentOptions = {},
): typeof cloudflareEnvironment {
return (
environmentName: string,
pluginConsumerOptions: CloudflareEnvironmentOptions = {},
) => {
// we deep merge the options from the caller into the user options here, we do this so
// that consumers of this plugin are able to override/augment/tweak the options if need be
const pluginOptions = deepMergeOptions(userOptions, pluginConsumerOptions);
return cloudflareEnvironment(environmentName, pluginOptions);
};
}
/**
* Deep merged the a set of options onto another and returns the result of the operation
* (the function does not modify the argument options themselves)
* @param target the target/base options object
* @param source the new options to merge into the target
* @returns the target options object merged with the options from the source object
*/
function deepMergeOptions(
target: CloudflareEnvironmentOptions,
source: CloudflareEnvironmentOptions,
): CloudflareEnvironmentOptions {
// the "deep merging" right now is very trivial... with a realistic/more complex
// options structure we'd have to do a real deep merge here
return {
config: target.config ?? source.config,
};
}
const defaultWranglerConfig = 'wrangler.toml';
export function cloudflareEnvironment(
environmentName: string,
options: CloudflareEnvironmentOptions = {},
): Plugin[] {
const resolvedWranglerConfigPath = resolve(
options.config ?? defaultWranglerConfig,
);
options.config = resolvedWranglerConfigPath;
return [
{
name: 'vite-plugin-cloudflare-environment',
async config() {
return {
environments: {
[environmentName]: createCloudflareEnvironment(options),
},
};
},
hotUpdate(ctx) {
if (this.environment.name !== environmentName) {
return;
}
if (ctx.file === resolvedWranglerConfigPath) {
ctx.server.restart();
}
},
},
];
}
export function createCloudflareEnvironment(
options: CloudflareEnvironmentOptions,
): EnvironmentOptions {
return {
// @ts-ignore
metadata: { runtimeName },
consumer: 'server',
webCompatible: true,
dev: {
createEnvironment(name, config) {
return createCloudflareDevEnvironment(name, config, options);
},
},
build: {
createEnvironment(name, config) {
return createCloudflareBuildEnvironment(name, config, options);
},
},
};
}
async function createCloudflareBuildEnvironment(
name: string,
config: ResolvedConfig,
_cloudflareOptions: CloudflareEnvironmentOptions,
): Promise<BuildEnvironment> {
const buildEnv = new BuildEnvironment(name, config);
// Nothing too special to do here, the default build env is probably ok for now
return buildEnv;
}
async function createCloudflareDevEnvironment(
name: string,
config: ResolvedConfig,
cloudflareOptions: CloudflareEnvironmentOptions,
): Promise<DevEnvironment> {
const { bindings: bindingsFromToml, ...optionsFromToml } =
getOptionsFromWranglerConfig(cloudflareOptions.config!);
const esmResolveId = createIdResolver(config, {});
// for `require` calls we want a resolver that prioritized node/cjs modules
const cjsResolveId = createIdResolver(config, {
conditions: ['node'],
mainFields: ['main'],
webCompatible: false,
isRequire: true,
extensions: ['.cjs', '.cts', '.js', '.ts', '.jsx', '.tsx', '.json'],
});
const resolveId: ResolveIdFunction = (
id,
importer,
{ resolveMethod } = {
resolveMethod: 'import',
},
) => {
const resolveIdFn =
resolveMethod === 'import' ? esmResolveId : cjsResolveId;
return resolveIdFn(devEnv, id, importer);
};
const mf = new Miniflare({
modulesRoot: fileURLToPath(new URL('./', import.meta.url)),
modules: [
{
type: 'ESModule',
path: fileURLToPath(new URL('worker/index.js', import.meta.url)),
},
{
// we declare the workerd-custom-import as a CommonJS module, thanks to this
// require is made available in the module and we are able to handle cjs imports, etc...
type: 'CommonJS',
path: fileURLToPath(
new URL('workerd-custom-import.cjs', import.meta.url),
),
},
],
unsafeEvalBinding: 'UNSAFE_EVAL',
bindings: {
...bindingsFromToml,
ROOT: config.root,
},
serviceBindings: {
__viteFetchModule: async request => {
const args = await request.json();
try {
const result: any = await devEnv.fetchModule(...(args as [any, any]));
await debugDumps.dump__viteFetchModuleLog(args, result);
return new MiniflareResponse(JSON.stringify(result));
} catch (error) {
console.error('[fetchModule]', args, error);
throw error;
}
},
__debugDump: debugDumps.__debugDumpBinding,
},
unsafeUseModuleFallbackService: true,
unsafeModuleFallbackService: getModuleFallbackCallback(resolveId),
...optionsFromToml,
});
const resp = await mf.dispatchFetch('http:0.0.0.0/__init-module-runner', {
headers: {
upgrade: 'websocket',
},
});
if (!resp.ok) {
throw new Error('Error: failed to initialize the module runner!');
}
const webSocket = resp.webSocket;
if (!webSocket) {
console.error(
'\x1b[33m⚠️ failed to create a websocket for HMR (hmr disabled)\x1b[0m',
);
}
const hot = webSocket ? createHotChannel(webSocket!) : false;
const devEnv = new ViteDevEnvironment(name, config, {
hot,
}) as DevEnvironment;
let entrypointSet = false;
devEnv.api = {
async getHandler({ entrypoint }) {
if (!entrypointSet) {
const resp = await mf.dispatchFetch('http:0.0.0.0/__set-entrypoint', {
headers: [['x-vite-workerd-entrypoint', entrypoint]],
});
if (resp.ok) {
entrypointSet = resp.ok;
} else {
throw new Error(
'failed to set entrypoint (the error should be logged in the terminal)',
);
}
}
return async (req: Request) => {
// TODO: ideally we should pass the request itself with close to no tweaks needed... this needs to be investigated
return await mf.dispatchFetch(req.url, {
method: req.method,
body: req.body,
duplex: 'half',
headers: [
// note: we disable encoding since this causes issues when the miniflare response
// gets piped into the node one
['accept-encoding', 'identity'],
...req.headers,
],
});
};
},
};
return devEnv;
}
function createHotChannel(webSocket: WebSocket): HotChannel {
webSocket.accept();
const listenersMap = new Map<string, Set<Function>>();
let hotDispose: () => void;
return {
send(...args) {
let payload: HotPayload;
if (typeof args[0] === 'string') {
payload = {
type: 'custom',
event: args[0],
data: args[1],
};
} else {
payload = args[0];
}
webSocket.send(JSON.stringify(payload));
},
on(event, listener) {
if (!listenersMap.get(event)) {
listenersMap.set(event, new Set());
}
listenersMap.get(event).add(listener);
},
off(event, listener) {
listenersMap.get(event)?.delete(listener);
},
listen() {
function eventListener(event: MessageEvent) {
const payload = JSON.parse(event.data.toString());
if (!listenersMap.get(payload.event)) {
listenersMap.set(payload.event, new Set());
}
for (const fn of listenersMap.get(payload.event)) {
fn(payload.data);
}
}
webSocket.addEventListener('message', eventListener);
hotDispose = () => {
webSocket.removeEventListener('message', eventListener);
};
},
close() {
hotDispose?.();
hotDispose = undefined;
},
};
}
function getOptionsFromWranglerConfig(configPath: string) {
let configOptions: SourcelessWorkerOptions;
try {
const { workerOptions } = unstable_getMiniflareWorkerOptions(configPath);
configOptions = workerOptions;
} catch (e) {
console.warn(`WARNING: unable to read config file at "${configPath}"`);
return {};
}
const {
bindings,
textBlobBindings,
dataBlobBindings,
wasmBindings,
kvNamespaces,
r2Buckets,
d1Databases,
compatibilityDate,
compatibilityFlags,
} = configOptions;
return {
bindings,
textBlobBindings,
dataBlobBindings,
wasmBindings,
kvNamespaces,
r2Buckets,
d1Databases,
compatibilityDate,
compatibilityFlags,
};
}