wrangler 0.0.0-e4e9eaf → 0.0.0-e9a1820

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/pages.tsx ADDED
@@ -0,0 +1,851 @@
1
+ /* eslint-disable no-shadow */
2
+
3
+ import assert from "assert";
4
+ import type { BuilderCallback } from "yargs";
5
+ import { join } from "path";
6
+ import { tmpdir } from "os";
7
+ import { existsSync, lstatSync, readFileSync } from "fs";
8
+ import { execSync, spawn } from "child_process";
9
+ import { URL } from "url";
10
+ import { getType } from "mime";
11
+ import open from "open";
12
+ import { watch } from "chokidar";
13
+
14
+ // Defer importing miniflare until we really need it. This takes ~0.5s
15
+ // and also modifies some `stream/web` and `undici` prototypes, so we
16
+ // don't want to do this if pages commands aren't being called.
17
+ import type { Headers, Request, fetch } from "@miniflare/core";
18
+ import type { MiniflareOptions } from "miniflare";
19
+
20
+ type Exit = (message?: string) => undefined;
21
+
22
+ const isWindows = () => process.platform === "win32";
23
+
24
+ const SECONDS_TO_WAIT_FOR_PROXY = 5;
25
+
26
+ const sleep = async (ms: number) =>
27
+ await new Promise((resolve) => setTimeout(resolve, ms));
28
+
29
+ const getPids = (pid: number) => {
30
+ const pids: number[] = [pid];
31
+ let command: string, regExp: RegExp;
32
+
33
+ if (isWindows()) {
34
+ command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
35
+ regExp = new RegExp(/(\d+)/);
36
+ } else {
37
+ command = `pgrep -P ${pid}`;
38
+ regExp = new RegExp(/(\d+)/);
39
+ }
40
+
41
+ try {
42
+ const newPids = (
43
+ execSync(command)
44
+ .toString()
45
+ .split("\n")
46
+ .map((line) => line.match(regExp))
47
+ .filter((line) => line !== null) as RegExpExecArray[]
48
+ ).map((match) => parseInt(match[1]));
49
+
50
+ pids.push(...newPids.map(getPids).flat());
51
+ } catch {}
52
+
53
+ return pids;
54
+ };
55
+
56
+ const getPort = (pid: number) => {
57
+ let command: string, regExp: RegExp;
58
+
59
+ if (isWindows()) {
60
+ command = "\\windows\\system32\\netstat.exe -nao";
61
+ regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
62
+ } else {
63
+ command = "lsof -nPi";
64
+ regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
65
+ }
66
+
67
+ try {
68
+ const matches = execSync(command)
69
+ .toString()
70
+ .split("\n")
71
+ .map((line) => line.match(regExp))
72
+ .filter((line) => line !== null) as RegExpExecArray[];
73
+
74
+ const match = matches[0];
75
+ if (match) return parseInt(match[1]);
76
+ } catch (thrown) {
77
+ console.error(
78
+ `Error scanning for ports of process with PID ${pid}: ${thrown}`
79
+ );
80
+ }
81
+ };
82
+
83
+ const spawnProxyProcess = async ({
84
+ port,
85
+ command,
86
+ }: {
87
+ port?: number;
88
+ command: (string | number)[];
89
+ }) => {
90
+ const exit: Exit = (message) => {
91
+ if (message) console.error(message);
92
+ if (proxy) proxy.kill();
93
+ return undefined;
94
+ };
95
+
96
+ if (command.length === 0)
97
+ return exit(
98
+ "Must specify a directory of static assets to serve or a command to run."
99
+ );
100
+
101
+ console.log(`Running ${command.join(" ")}...`);
102
+ const proxy = spawn(
103
+ command[0].toString(),
104
+ command.slice(1).map((value) => value.toString()),
105
+ {
106
+ shell: isWindows(),
107
+ env: {
108
+ BROWSER: "none",
109
+ ...process.env,
110
+ },
111
+ }
112
+ );
113
+
114
+ proxy.stdout.on("data", (data) => {
115
+ console.log(`[proxy]: ${data}`);
116
+ });
117
+
118
+ proxy.stderr.on("data", (data) => {
119
+ console.error(`[proxy]: ${data}`);
120
+ });
121
+
122
+ proxy.on("close", (code) => {
123
+ console.error(`Proxy exited with status ${code}.`);
124
+ });
125
+
126
+ // Wait for proxy process to start...
127
+ while (!proxy.pid) {}
128
+
129
+ if (port === undefined) {
130
+ console.log(
131
+ `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
132
+ );
133
+ console.log("To skip, specify the proxy port with --proxy.");
134
+ await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
135
+
136
+ port = getPids(proxy.pid)
137
+ .map(getPort)
138
+ .filter((port) => port !== undefined)[0];
139
+
140
+ if (port === undefined) {
141
+ return exit(
142
+ "Could not automatically determine proxy port. Please specify the proxy port with --proxy."
143
+ );
144
+ } else {
145
+ console.log(`Automatically determined the proxy port to be ${port}.`);
146
+ }
147
+ }
148
+
149
+ return { port, exit };
150
+ };
151
+
152
+ const escapeRegex = (str: string) => {
153
+ return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
154
+ };
155
+
156
+ export type Replacements = Record<string, string>;
157
+
158
+ export const replacer = (str: string, replacements: Replacements) => {
159
+ for (const [replacement, value] of Object.entries(replacements)) {
160
+ str = str.replace(`:${replacement}`, value);
161
+ }
162
+ return str;
163
+ };
164
+
165
+ export const generateRulesMatcher = <T,>(
166
+ rules?: Record<string, T>,
167
+ replacer: (match: T, replacements: Replacements) => T = (match) => match
168
+ ) => {
169
+ // TODO: How can you test cross-host rules?
170
+ if (!rules) return () => [];
171
+
172
+ const compiledRules = Object.entries(rules)
173
+ .map(([rule, match]) => {
174
+ const crossHost = rule.startsWith("https://");
175
+
176
+ rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
177
+
178
+ const host_matches = rule.matchAll(
179
+ /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
180
+ );
181
+ for (const match of host_matches) {
182
+ rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
183
+ }
184
+
185
+ const path_matches = rule.matchAll(/:(\w+)/g);
186
+ for (const match of path_matches) {
187
+ rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
188
+ }
189
+
190
+ rule = "^" + rule + "$";
191
+
192
+ try {
193
+ const regExp = new RegExp(rule);
194
+ return [{ crossHost, regExp }, match];
195
+ } catch {}
196
+ })
197
+ .filter((value) => value !== undefined) as [
198
+ { crossHost: boolean; regExp: RegExp },
199
+ T
200
+ ][];
201
+
202
+ return ({ request }: { request: Request }) => {
203
+ const { pathname, host } = new URL(request.url);
204
+
205
+ return compiledRules
206
+ .map(([{ crossHost, regExp }, match]) => {
207
+ const test = crossHost ? `https://${host}${pathname}` : pathname;
208
+ const result = regExp.exec(test);
209
+ if (result) {
210
+ return replacer(match, result.groups || {});
211
+ }
212
+ })
213
+ .filter((value) => value !== undefined) as T[];
214
+ };
215
+ };
216
+
217
+ const generateHeadersMatcher = (headersFile: string) => {
218
+ if (existsSync(headersFile)) {
219
+ const contents = readFileSync(headersFile).toString();
220
+
221
+ // TODO: Log errors
222
+ const lines = contents
223
+ .split("\n")
224
+ .map((line) => line.trim())
225
+ .filter((line) => !line.startsWith("#") && line !== "");
226
+
227
+ const rules: Record<string, Record<string, string>> = {};
228
+ let rule: { path: string; headers: Record<string, string> } | undefined =
229
+ undefined;
230
+
231
+ for (const line of lines) {
232
+ if (/^([^\s]+:\/\/|^\/)/.test(line)) {
233
+ if (rule && Object.keys(rule.headers).length > 0) {
234
+ rules[rule.path] = rule.headers;
235
+ }
236
+
237
+ const path = validateURL(line);
238
+ if (path) {
239
+ rule = {
240
+ path,
241
+ headers: {},
242
+ };
243
+ continue;
244
+ }
245
+ }
246
+
247
+ if (!line.includes(":")) continue;
248
+
249
+ const [rawName, ...rawValue] = line.split(":");
250
+ const name = rawName.trim().toLowerCase();
251
+ const value = rawValue.join(":").trim();
252
+
253
+ if (name === "") continue;
254
+ if (!rule) continue;
255
+
256
+ const existingValues = rule.headers[name];
257
+ rule.headers[name] = existingValues
258
+ ? `${existingValues}, ${value}`
259
+ : value;
260
+ }
261
+
262
+ if (rule && Object.keys(rule.headers).length > 0) {
263
+ rules[rule.path] = rule.headers;
264
+ }
265
+
266
+ const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
267
+ Object.fromEntries(
268
+ Object.entries(match).map(([name, value]) => [
269
+ name,
270
+ replacer(value, replacements),
271
+ ])
272
+ )
273
+ );
274
+
275
+ return (request: Request) => {
276
+ const matches = rulesMatcher({
277
+ request,
278
+ });
279
+ if (matches) return matches;
280
+ };
281
+ } else {
282
+ return () => undefined;
283
+ }
284
+ };
285
+
286
+ const generateRedirectsMatcher = (redirectsFile: string) => {
287
+ if (existsSync(redirectsFile)) {
288
+ const contents = readFileSync(redirectsFile).toString();
289
+
290
+ // TODO: Log errors
291
+ const lines = contents
292
+ .split("\n")
293
+ .map((line) => line.trim())
294
+ .filter((line) => !line.startsWith("#") && line !== "");
295
+
296
+ const rules = Object.fromEntries(
297
+ lines
298
+ .map((line) => line.split(" "))
299
+ .filter((tokens) => tokens.length === 2 || tokens.length === 3)
300
+ .map((tokens) => {
301
+ const from = validateURL(tokens[0], true, false, false);
302
+ const to = validateURL(tokens[1], false, true, true);
303
+ let status: number | undefined = parseInt(tokens[2]) || 302;
304
+ status = [301, 302, 303, 307, 308].includes(status)
305
+ ? status
306
+ : undefined;
307
+
308
+ return from && to && status ? [from, { to, status }] : undefined;
309
+ })
310
+ .filter((rule) => rule !== undefined) as [
311
+ string,
312
+ { to: string; status?: number }
313
+ ][]
314
+ );
315
+
316
+ const rulesMatcher = generateRulesMatcher(
317
+ rules,
318
+ ({ status, to }, replacements) => ({
319
+ status,
320
+ to: replacer(to, replacements),
321
+ })
322
+ );
323
+
324
+ return (request: Request) => {
325
+ const match = rulesMatcher({
326
+ request,
327
+ })[0];
328
+ if (match) return match;
329
+ };
330
+ } else {
331
+ return () => undefined;
332
+ }
333
+ };
334
+
335
+ const extractPathname = (
336
+ path = "/",
337
+ includeSearch: boolean,
338
+ includeHash: boolean
339
+ ) => {
340
+ if (!path.startsWith("/")) path = `/${path}`;
341
+ const url = new URL(`//${path}`, "relative://");
342
+ return `${url.pathname}${includeSearch ? url.search : ""}${
343
+ includeHash ? url.hash : ""
344
+ }`;
345
+ };
346
+
347
+ const validateURL = (
348
+ token: string,
349
+ onlyRelative = false,
350
+ includeSearch = false,
351
+ includeHash = false
352
+ ) => {
353
+ const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
354
+ if (host && host.groups && host.groups.host) {
355
+ if (onlyRelative) return;
356
+
357
+ return `https://${host.groups.host}${extractPathname(
358
+ host.groups.path,
359
+ includeSearch,
360
+ includeHash
361
+ )}`;
362
+ } else {
363
+ if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
364
+
365
+ const path = /^\//.exec(token);
366
+ if (path) {
367
+ try {
368
+ return extractPathname(token, includeSearch, includeHash);
369
+ } catch {}
370
+ }
371
+ }
372
+ return "";
373
+ };
374
+
375
+ const hasFileExtension = (pathname: string) =>
376
+ /\/.+\.[a-z0-9]+$/i.test(pathname);
377
+
378
+ const generateAssetsFetch = async (
379
+ directory: string
380
+ ): Promise<typeof fetch> => {
381
+ // Defer importing miniflare until we really need it
382
+ const { Headers, Request, Response } = await import("@miniflare/core");
383
+
384
+ const headersFile = join(directory, "_headers");
385
+ const redirectsFile = join(directory, "_redirects");
386
+ const workerFile = join(directory, "_worker.js");
387
+
388
+ const ignoredFiles = [headersFile, redirectsFile, workerFile];
389
+
390
+ const assetExists = (path: string) => {
391
+ path = join(directory, path);
392
+ return (
393
+ existsSync(path) &&
394
+ lstatSync(path).isFile() &&
395
+ !ignoredFiles.includes(path)
396
+ );
397
+ };
398
+
399
+ const getAsset = (path: string) => {
400
+ if (assetExists(path)) {
401
+ return join(directory, path);
402
+ }
403
+ };
404
+
405
+ let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
406
+ let headersMatcher = generateHeadersMatcher(headersFile);
407
+
408
+ watch([headersFile, redirectsFile], {
409
+ persistent: true,
410
+ }).on("change", (path) => {
411
+ switch (path) {
412
+ case headersFile: {
413
+ console.log("_headers modified. Re-evaluating...");
414
+ headersMatcher = generateHeadersMatcher(headersFile);
415
+ break;
416
+ }
417
+ case redirectsFile: {
418
+ console.log("_redirects modified. Re-evaluating...");
419
+ redirectsMatcher = generateRedirectsMatcher(redirectsFile);
420
+ break;
421
+ }
422
+ }
423
+ });
424
+
425
+ const serveAsset = (file: string) => {
426
+ return readFileSync(file);
427
+ };
428
+
429
+ const generateResponse = (request: Request) => {
430
+ const url = new URL(request.url);
431
+
432
+ const deconstructedResponse: {
433
+ status: number;
434
+ headers: Headers;
435
+ body?: Buffer;
436
+ } = {
437
+ status: 200,
438
+ headers: new Headers(),
439
+ body: undefined,
440
+ };
441
+
442
+ const match = redirectsMatcher(request);
443
+ if (match) {
444
+ const { status, to } = match;
445
+
446
+ let location = to;
447
+ let search;
448
+
449
+ if (to.startsWith("/")) {
450
+ search = new URL(location, "http://fakehost").search;
451
+ } else {
452
+ search = new URL(location).search;
453
+ }
454
+
455
+ location = `${location}${search ? "" : url.search}`;
456
+
457
+ if (status && [301, 302, 303, 307, 308].includes(status)) {
458
+ deconstructedResponse.status = status;
459
+ } else {
460
+ deconstructedResponse.status = 302;
461
+ }
462
+
463
+ deconstructedResponse.headers.set("Location", location);
464
+ return deconstructedResponse;
465
+ }
466
+
467
+ if (!request.method?.match(/^(get|head)$/i)) {
468
+ deconstructedResponse.status = 405;
469
+ return deconstructedResponse;
470
+ }
471
+
472
+ const notFound = () => {
473
+ let cwd = url.pathname;
474
+ while (cwd) {
475
+ cwd = cwd.slice(0, cwd.lastIndexOf("/"));
476
+
477
+ if ((asset = getAsset(`${cwd}/404.html`))) {
478
+ deconstructedResponse.status = 404;
479
+ deconstructedResponse.body = serveAsset(asset);
480
+ deconstructedResponse.headers.set(
481
+ "Content-Type",
482
+ getType(asset) || "application/octet-stream"
483
+ );
484
+ return deconstructedResponse;
485
+ }
486
+ }
487
+
488
+ if ((asset = getAsset(`/index.html`))) {
489
+ deconstructedResponse.body = serveAsset(asset);
490
+ deconstructedResponse.headers.set(
491
+ "Content-Type",
492
+ getType(asset) || "application/octet-stream"
493
+ );
494
+ return deconstructedResponse;
495
+ }
496
+
497
+ deconstructedResponse.status = 404;
498
+ return deconstructedResponse;
499
+ };
500
+
501
+ let asset;
502
+
503
+ if (url.pathname.endsWith("/")) {
504
+ if ((asset = getAsset(`${url.pathname}/index.html`))) {
505
+ deconstructedResponse.body = serveAsset(asset);
506
+ deconstructedResponse.headers.set(
507
+ "Content-Type",
508
+ getType(asset) || "application/octet-stream"
509
+ );
510
+ return deconstructedResponse;
511
+ } else if (
512
+ (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
513
+ ) {
514
+ deconstructedResponse.status = 301;
515
+ deconstructedResponse.headers.set(
516
+ "Location",
517
+ `${url.pathname.slice(0, -1)}${url.search}`
518
+ );
519
+ return deconstructedResponse;
520
+ }
521
+ }
522
+
523
+ if (url.pathname.endsWith("/index")) {
524
+ deconstructedResponse.status = 301;
525
+ deconstructedResponse.headers.set(
526
+ "Location",
527
+ `${url.pathname.slice(0, -"index".length)}${url.search}`
528
+ );
529
+ return deconstructedResponse;
530
+ }
531
+
532
+ if ((asset = getAsset(url.pathname))) {
533
+ if (url.pathname.endsWith(".html")) {
534
+ const extensionlessPath = url.pathname.slice(0, -".html".length);
535
+ if (getAsset(extensionlessPath) || extensionlessPath === "/") {
536
+ deconstructedResponse.body = serveAsset(asset);
537
+ deconstructedResponse.headers.set(
538
+ "Content-Type",
539
+ getType(asset) || "application/octet-stream"
540
+ );
541
+ return deconstructedResponse;
542
+ } else {
543
+ deconstructedResponse.status = 301;
544
+ deconstructedResponse.headers.set(
545
+ "Location",
546
+ `${extensionlessPath}${url.search}`
547
+ );
548
+ return deconstructedResponse;
549
+ }
550
+ } else {
551
+ deconstructedResponse.body = serveAsset(asset);
552
+ deconstructedResponse.headers.set(
553
+ "Content-Type",
554
+ getType(asset) || "application/octet-stream"
555
+ );
556
+ return deconstructedResponse;
557
+ }
558
+ } else if (hasFileExtension(url.pathname)) {
559
+ notFound();
560
+ return deconstructedResponse;
561
+ }
562
+
563
+ if ((asset = getAsset(`${url.pathname}.html`))) {
564
+ deconstructedResponse.body = serveAsset(asset);
565
+ deconstructedResponse.headers.set(
566
+ "Content-Type",
567
+ getType(asset) || "application/octet-stream"
568
+ );
569
+ return deconstructedResponse;
570
+ }
571
+
572
+ if ((asset = getAsset(`${url.pathname}/index.html`))) {
573
+ deconstructedResponse.status = 301;
574
+ deconstructedResponse.headers.set(
575
+ "Location",
576
+ `${url.pathname}/${url.search}`
577
+ );
578
+ return deconstructedResponse;
579
+ } else {
580
+ notFound();
581
+ return deconstructedResponse;
582
+ }
583
+ };
584
+
585
+ const attachHeaders = (
586
+ request: Request,
587
+ deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
588
+ ) => {
589
+ const headers = deconstructedResponse.headers;
590
+ const newHeaders = new Headers({});
591
+ const matches = headersMatcher(request) || [];
592
+
593
+ matches.forEach((match) => {
594
+ Object.entries(match).forEach(([name, value]) => {
595
+ newHeaders.append(name, `${value}`);
596
+ });
597
+ });
598
+
599
+ const combinedHeaders = {
600
+ ...Object.fromEntries(headers.entries()),
601
+ ...Object.fromEntries(newHeaders.entries()),
602
+ };
603
+
604
+ deconstructedResponse.headers = new Headers({});
605
+ Object.entries(combinedHeaders).forEach(([name, value]) => {
606
+ if (value) deconstructedResponse.headers.set(name, value);
607
+ });
608
+ };
609
+
610
+ return async (input, init) => {
611
+ const request = new Request(input, init);
612
+ const deconstructedResponse = generateResponse(request);
613
+ attachHeaders(request, deconstructedResponse);
614
+
615
+ const headers = new Headers();
616
+
617
+ [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
618
+ if (value) headers.set(name, value);
619
+ });
620
+
621
+ return new Response(deconstructedResponse.body, {
622
+ headers,
623
+ status: deconstructedResponse.status,
624
+ });
625
+ };
626
+ };
627
+
628
+ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
629
+ return yargs.command(
630
+ "dev [directory] [-- command]",
631
+ "🧑‍💻 Develop your full-stack Pages application locally",
632
+ (yargs) => {
633
+ return yargs
634
+ .positional("directory", {
635
+ type: "string",
636
+ demandOption: undefined,
637
+ description: "The directory of static assets to serve",
638
+ })
639
+ .positional("command", {
640
+ type: "string",
641
+ demandOption: undefined,
642
+ description: "The proxy command to run",
643
+ })
644
+ .options({
645
+ local: {
646
+ type: "boolean",
647
+ default: true,
648
+ description: "Run on my machine",
649
+ },
650
+ port: {
651
+ type: "number",
652
+ default: 8788,
653
+ description: "The port to listen on (serve from)",
654
+ },
655
+ proxy: {
656
+ type: "number",
657
+ description:
658
+ "The port to proxy (where the static assets are served)",
659
+ },
660
+ "script-path": {
661
+ type: "string",
662
+ default: "_worker.js",
663
+ description:
664
+ "The location of the single Worker script if not using functions",
665
+ },
666
+ binding: {
667
+ type: "array",
668
+ description: "Bind variable/secret (KEY=VALUE)",
669
+ alias: "b",
670
+ },
671
+ kv: {
672
+ type: "array",
673
+ description: "KV namespace to bind",
674
+ alias: "k",
675
+ },
676
+ do: {
677
+ type: "array",
678
+ description: "Durable Object to bind (NAME=CLASS)",
679
+ alias: "o",
680
+ },
681
+ // TODO: Miniflare user options
682
+ });
683
+ },
684
+ async ({
685
+ local,
686
+ directory,
687
+ port,
688
+ proxy: requestedProxyPort,
689
+ "script-path": singleWorkerScriptPath,
690
+ binding: bindings = [],
691
+ kv: kvs = [],
692
+ do: durableObjects = [],
693
+ "--": remaining = [],
694
+ }) => {
695
+ if (!local) {
696
+ console.error("Only local mode is supported at the moment.");
697
+ return;
698
+ }
699
+
700
+ const functionsDirectory = "./functions";
701
+ const usingFunctions = existsSync(functionsDirectory);
702
+
703
+ const command = remaining as (string | number)[];
704
+
705
+ let proxyPort: number | undefined;
706
+ let exit: Exit = (message) => {
707
+ console.error(message);
708
+ return undefined;
709
+ };
710
+
711
+ if (directory === undefined) {
712
+ const proxy = await spawnProxyProcess({
713
+ port: requestedProxyPort,
714
+ command,
715
+ });
716
+ if (proxy === undefined) return undefined;
717
+
718
+ exit = proxy.exit;
719
+ proxyPort = proxy.port;
720
+
721
+ process.on("SIGINT", () => exit());
722
+ process.on("SIGTERM", () => exit());
723
+ }
724
+
725
+ let miniflareArgs: MiniflareOptions = {};
726
+
727
+ if (usingFunctions) {
728
+ const scriptPath = join(tmpdir(), "./functionsWorker.js");
729
+ miniflareArgs = {
730
+ scriptPath,
731
+ buildWatchPaths: [functionsDirectory],
732
+ buildCommand: `npx @cloudflare/pages-functions-compiler build ${functionsDirectory} --outfile ${scriptPath}`,
733
+ };
734
+ } else {
735
+ const scriptPath =
736
+ directory !== undefined
737
+ ? join(directory, singleWorkerScriptPath)
738
+ : singleWorkerScriptPath;
739
+
740
+ if (!existsSync(scriptPath)) {
741
+ return exit(
742
+ `No Worker script found at ${scriptPath}. Please either create a functions directory or create a single Worker at ${scriptPath}.`
743
+ );
744
+ }
745
+
746
+ miniflareArgs = {
747
+ scriptPath,
748
+ };
749
+ }
750
+
751
+ // Defer importing miniflare until we really need it
752
+ const { Miniflare, Log, LogLevel } = await import("miniflare");
753
+ const { Response, fetch } = await import("@miniflare/core");
754
+
755
+ // Should only be called if no proxyPort, using `assert.fail()` here
756
+ // means the type of `assetsFetch` is still `typeof fetch`
757
+ const assetsFetch = proxyPort
758
+ ? () => assert.fail()
759
+ : await generateAssetsFetch(directory);
760
+ const miniflare = new Miniflare({
761
+ port,
762
+ watch: true,
763
+ modules: true,
764
+
765
+ log: new Log(LogLevel.ERROR, { prefix: "pages" }),
766
+ logUnhandledRejections: true,
767
+ sourceMap: true,
768
+
769
+ kvNamespaces: kvs.map((kv) => kv.toString()),
770
+
771
+ durableObjects: Object.fromEntries(
772
+ durableObjects.map((durableObject) =>
773
+ durableObject.toString().split("=")
774
+ )
775
+ ),
776
+
777
+ // User bindings
778
+ bindings: {
779
+ ...Object.fromEntries(
780
+ bindings.map((binding) => binding.toString().split("="))
781
+ ),
782
+ },
783
+
784
+ // env.ASSETS.fetch
785
+ serviceBindings: {
786
+ async ASSETS(request) {
787
+ if (proxyPort) {
788
+ try {
789
+ const url = new URL(request.url);
790
+ url.host = `127.0.0.1:${proxyPort}`;
791
+ return await fetch(url, request);
792
+ } catch (thrown) {
793
+ console.error(`Could not proxy request: ${thrown}`);
794
+
795
+ // TODO: Pretty error page
796
+ return new Response(
797
+ `[wrangler] Could not proxy request: ${thrown}`,
798
+ { status: 502 }
799
+ );
800
+ }
801
+ } else {
802
+ try {
803
+ return await assetsFetch(request);
804
+ } catch (thrown) {
805
+ console.error(`Could not serve static asset: ${thrown}`);
806
+
807
+ // TODO: Pretty error page
808
+ return new Response(
809
+ `[wrangler] Could not serve static asset: ${thrown}`,
810
+ { status: 502 }
811
+ );
812
+ }
813
+ }
814
+ },
815
+ },
816
+
817
+ kvPersist: true,
818
+ durableObjectsPersist: true,
819
+ cachePersist: true,
820
+
821
+ ...miniflareArgs,
822
+ });
823
+
824
+ try {
825
+ // `startServer` might throw if user code contains errors
826
+ const server = await miniflare.startServer();
827
+ console.log(`Serving at http://127.0.0.1:${port}/`);
828
+
829
+ if (process.env.BROWSER !== "none") {
830
+ await open(`http://127.0.0.1:${port}/`);
831
+ }
832
+
833
+ process.on("SIGINT", () => {
834
+ server.close();
835
+ miniflare.dispose().catch((err) => {
836
+ miniflare.log.error(err);
837
+ });
838
+ });
839
+ process.on("SIGTERM", () => {
840
+ server.close();
841
+ miniflare.dispose().catch((err) => {
842
+ miniflare.log.error(err);
843
+ });
844
+ });
845
+ } catch (e) {
846
+ miniflare.log.error(e);
847
+ process.exitCode = 1;
848
+ }
849
+ }
850
+ );
851
+ };