wrangler 0.0.0-ece06ea → 0.0.0-eebdb6c
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/package.json +22 -15
- package/pages/functions/buildWorker.ts +57 -0
- package/pages/functions/filepath-routing.test.ts +32 -0
- package/pages/functions/filepath-routing.ts +225 -0
- package/pages/functions/identifiers.ts +78 -0
- package/pages/functions/routes.ts +158 -0
- package/pages/functions/template-worker.ts +135 -0
- package/src/__tests__/index.test.ts +254 -120
- package/src/__tests__/jest.setup.ts +22 -0
- package/src/__tests__/kv.test.ts +1098 -0
- package/src/__tests__/mock-cfetch.ts +171 -0
- package/src/__tests__/mock-dialogs.ts +65 -0
- package/src/__tests__/run-in-tmp.ts +19 -0
- package/src/__tests__/run-wrangler.ts +32 -0
- package/src/api/form_data.ts +70 -97
- package/src/api/inspect.ts +0 -11
- package/src/api/preview.ts +29 -24
- package/src/api/worker.ts +34 -40
- package/src/cfetch/index.ts +103 -0
- package/src/cfetch/internal.ts +69 -0
- package/src/cli.ts +6 -7
- package/src/config.ts +14 -7
- package/src/dev.tsx +274 -131
- package/src/dialogs.tsx +4 -12
- package/src/index.tsx +304 -245
- package/src/kv.tsx +101 -45
- package/src/module-collection.ts +64 -0
- package/src/pages.tsx +681 -104
- package/src/proxy.ts +103 -0
- package/src/publish.ts +54 -58
- package/src/sites.tsx +5 -6
- package/src/tail.tsx +5 -3
- package/src/user.tsx +9 -16
- package/wrangler-dist/cli.js +36633 -49770
- package/wrangler-dist/cli.js.map +3 -3
- package/src/__tests__/fixtures/init/.gitkeep +0 -0
- package/src/__tests__/mock-cfetch.js +0 -46
- package/src/cfetch.ts +0 -72
- package/src/util/fetch.ts +0 -74
package/src/pages.tsx
CHANGED
|
@@ -1,24 +1,49 @@
|
|
|
1
|
+
/* eslint-disable no-shadow */
|
|
2
|
+
|
|
3
|
+
import assert from "assert";
|
|
1
4
|
import type { BuilderCallback } from "yargs";
|
|
2
5
|
import { join } from "path";
|
|
3
6
|
import { tmpdir } from "os";
|
|
4
|
-
import { existsSync } from "fs";
|
|
5
|
-
import type { ChildProcess } from "child_process";
|
|
7
|
+
import { existsSync, lstatSync, readFileSync } from "fs";
|
|
6
8
|
import { execSync, spawn } from "child_process";
|
|
7
|
-
import
|
|
9
|
+
import { URL } from "url";
|
|
10
|
+
import { getType } from "mime";
|
|
11
|
+
import open from "open";
|
|
12
|
+
import { watch } from "chokidar";
|
|
13
|
+
import type { BuildResult } from "esbuild";
|
|
14
|
+
import { buildWorker } from "../pages/functions/buildWorker";
|
|
15
|
+
import type { Config } from "../pages/functions/routes";
|
|
16
|
+
import { writeRoutesModule } from "../pages/functions/routes";
|
|
17
|
+
import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
|
|
18
|
+
|
|
19
|
+
// Defer importing miniflare until we really need it. This takes ~0.5s
|
|
20
|
+
// and also modifies some `stream/web` and `undici` prototypes, so we
|
|
21
|
+
// don't want to do this if pages commands aren't being called.
|
|
22
|
+
import type { Headers, Request, fetch } from "@miniflare/core";
|
|
8
23
|
import type { MiniflareOptions } from "miniflare";
|
|
9
|
-
import type { RequestInfo, RequestInit } from "@miniflare/core";
|
|
10
|
-
import httpProxyMiddleware from "http-proxy-middleware";
|
|
11
24
|
|
|
12
|
-
|
|
25
|
+
const EXIT_CALLBACKS = [];
|
|
26
|
+
const EXIT = (message?: string, code?: number) => {
|
|
27
|
+
if (message) console.log(message);
|
|
28
|
+
if (code) process.exitCode = code;
|
|
29
|
+
EXIT_CALLBACKS.forEach((callback) => callback());
|
|
30
|
+
process.exit(code);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
process.on("SIGINT", () => EXIT());
|
|
34
|
+
process.on("SIGTERM", () => EXIT());
|
|
13
35
|
|
|
14
|
-
|
|
36
|
+
function isWindows() {
|
|
37
|
+
return process.platform === "win32";
|
|
38
|
+
}
|
|
15
39
|
|
|
16
40
|
const SECONDS_TO_WAIT_FOR_PROXY = 5;
|
|
17
41
|
|
|
18
|
-
|
|
42
|
+
async function sleep(ms: number) {
|
|
19
43
|
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
44
|
+
}
|
|
20
45
|
|
|
21
|
-
|
|
46
|
+
function getPids(pid: number) {
|
|
22
47
|
const pids: number[] = [pid];
|
|
23
48
|
let command: string, regExp: RegExp;
|
|
24
49
|
|
|
@@ -43,9 +68,9 @@ const getPids = (pid: number) => {
|
|
|
43
68
|
} catch {}
|
|
44
69
|
|
|
45
70
|
return pids;
|
|
46
|
-
}
|
|
71
|
+
}
|
|
47
72
|
|
|
48
|
-
|
|
73
|
+
function getPort(pid: number) {
|
|
49
74
|
let command: string, regExp: RegExp;
|
|
50
75
|
|
|
51
76
|
if (isWindows()) {
|
|
@@ -70,44 +95,34 @@ const getPort = (pid: number) => {
|
|
|
70
95
|
`Error scanning for ports of process with PID ${pid}: ${thrown}`
|
|
71
96
|
);
|
|
72
97
|
}
|
|
73
|
-
}
|
|
98
|
+
}
|
|
74
99
|
|
|
75
|
-
|
|
76
|
-
directory,
|
|
100
|
+
async function spawnProxyProcess({
|
|
77
101
|
port,
|
|
78
|
-
|
|
102
|
+
command,
|
|
79
103
|
}: {
|
|
80
|
-
directory?: string;
|
|
81
104
|
port?: number;
|
|
82
|
-
|
|
83
|
-
})
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (proxy) proxy.kill();
|
|
89
|
-
return undefined;
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
if (directory !== undefined) {
|
|
93
|
-
console.log(`Serving ${directory}...`);
|
|
94
|
-
const args = ["serve", directory];
|
|
95
|
-
if (port) args.push("-p", port.toString());
|
|
96
|
-
proxy = spawn("npx", args, { shell: isWindows() });
|
|
97
|
-
} else {
|
|
98
|
-
const command = remaining;
|
|
99
|
-
if (command.length === 0)
|
|
100
|
-
return exit(
|
|
101
|
-
"Must specify a directory of static assets to serve or a command to run."
|
|
102
|
-
);
|
|
103
|
-
|
|
104
|
-
console.log(`Running ${command.join(" ")}...`);
|
|
105
|
-
proxy = spawn(
|
|
106
|
-
command[0].toString(),
|
|
107
|
-
command.slice(1).map((value) => value.toString()),
|
|
108
|
-
{ shell: isWindows() }
|
|
105
|
+
command: (string | number)[];
|
|
106
|
+
}): Promise<void | number> {
|
|
107
|
+
if (command.length === 0)
|
|
108
|
+
return EXIT(
|
|
109
|
+
"Must specify a directory of static assets to serve or a command to run.",
|
|
110
|
+
1
|
|
109
111
|
);
|
|
110
|
-
|
|
112
|
+
|
|
113
|
+
console.log(`Running ${command.join(" ")}...`);
|
|
114
|
+
const proxy = spawn(
|
|
115
|
+
command[0].toString(),
|
|
116
|
+
command.slice(1).map((value) => value.toString()),
|
|
117
|
+
{
|
|
118
|
+
shell: isWindows(),
|
|
119
|
+
env: {
|
|
120
|
+
BROWSER: "none",
|
|
121
|
+
...process.env,
|
|
122
|
+
},
|
|
123
|
+
}
|
|
124
|
+
);
|
|
125
|
+
EXIT_CALLBACKS.push(() => proxy.kill());
|
|
111
126
|
|
|
112
127
|
proxy.stdout.on("data", (data) => {
|
|
113
128
|
console.log(`[proxy]: ${data}`);
|
|
@@ -136,16 +151,532 @@ const spawnProxyProcess = async ({
|
|
|
136
151
|
.filter((port) => port !== undefined)[0];
|
|
137
152
|
|
|
138
153
|
if (port === undefined) {
|
|
139
|
-
return
|
|
140
|
-
"Could not automatically
|
|
154
|
+
return EXIT(
|
|
155
|
+
"Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
|
|
156
|
+
1
|
|
141
157
|
);
|
|
142
158
|
} else {
|
|
143
159
|
console.log(`Automatically determined the proxy port to be ${port}.`);
|
|
144
160
|
}
|
|
145
161
|
}
|
|
146
162
|
|
|
147
|
-
return
|
|
148
|
-
}
|
|
163
|
+
return port;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function escapeRegex(str: string) {
|
|
167
|
+
return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
type Replacements = Record<string, string>;
|
|
171
|
+
|
|
172
|
+
function replacer(str: string, replacements: Replacements) {
|
|
173
|
+
for (const [replacement, value] of Object.entries(replacements)) {
|
|
174
|
+
str = str.replace(`:${replacement}`, value);
|
|
175
|
+
}
|
|
176
|
+
return str;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function generateRulesMatcher<T>(
|
|
180
|
+
rules?: Record<string, T>,
|
|
181
|
+
replacer: (match: T, replacements: Replacements) => T = (match) => match
|
|
182
|
+
) {
|
|
183
|
+
// TODO: How can you test cross-host rules?
|
|
184
|
+
if (!rules) return () => [];
|
|
185
|
+
|
|
186
|
+
const compiledRules = Object.entries(rules)
|
|
187
|
+
.map(([rule, match]) => {
|
|
188
|
+
const crossHost = rule.startsWith("https://");
|
|
189
|
+
|
|
190
|
+
rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
|
|
191
|
+
|
|
192
|
+
const host_matches = rule.matchAll(
|
|
193
|
+
/(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
|
|
194
|
+
);
|
|
195
|
+
for (const match of host_matches) {
|
|
196
|
+
rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const path_matches = rule.matchAll(/:(\w+)/g);
|
|
200
|
+
for (const match of path_matches) {
|
|
201
|
+
rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
rule = "^" + rule + "$";
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
const regExp = new RegExp(rule);
|
|
208
|
+
return [{ crossHost, regExp }, match];
|
|
209
|
+
} catch {}
|
|
210
|
+
})
|
|
211
|
+
.filter((value) => value !== undefined) as [
|
|
212
|
+
{ crossHost: boolean; regExp: RegExp },
|
|
213
|
+
T
|
|
214
|
+
][];
|
|
215
|
+
|
|
216
|
+
return ({ request }: { request: Request }) => {
|
|
217
|
+
const { pathname, host } = new URL(request.url);
|
|
218
|
+
|
|
219
|
+
return compiledRules
|
|
220
|
+
.map(([{ crossHost, regExp }, match]) => {
|
|
221
|
+
const test = crossHost ? `https://${host}${pathname}` : pathname;
|
|
222
|
+
const result = regExp.exec(test);
|
|
223
|
+
if (result) {
|
|
224
|
+
return replacer(match, result.groups || {});
|
|
225
|
+
}
|
|
226
|
+
})
|
|
227
|
+
.filter((value) => value !== undefined) as T[];
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function generateHeadersMatcher(headersFile: string) {
|
|
232
|
+
if (existsSync(headersFile)) {
|
|
233
|
+
const contents = readFileSync(headersFile).toString();
|
|
234
|
+
|
|
235
|
+
// TODO: Log errors
|
|
236
|
+
const lines = contents
|
|
237
|
+
.split("\n")
|
|
238
|
+
.map((line) => line.trim())
|
|
239
|
+
.filter((line) => !line.startsWith("#") && line !== "");
|
|
240
|
+
|
|
241
|
+
const rules: Record<string, Record<string, string>> = {};
|
|
242
|
+
let rule: { path: string; headers: Record<string, string> } | undefined =
|
|
243
|
+
undefined;
|
|
244
|
+
|
|
245
|
+
for (const line of lines) {
|
|
246
|
+
if (/^([^\s]+:\/\/|^\/)/.test(line)) {
|
|
247
|
+
if (rule && Object.keys(rule.headers).length > 0) {
|
|
248
|
+
rules[rule.path] = rule.headers;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const path = validateURL(line);
|
|
252
|
+
if (path) {
|
|
253
|
+
rule = {
|
|
254
|
+
path,
|
|
255
|
+
headers: {},
|
|
256
|
+
};
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (!line.includes(":")) continue;
|
|
262
|
+
|
|
263
|
+
const [rawName, ...rawValue] = line.split(":");
|
|
264
|
+
const name = rawName.trim().toLowerCase();
|
|
265
|
+
const value = rawValue.join(":").trim();
|
|
266
|
+
|
|
267
|
+
if (name === "") continue;
|
|
268
|
+
if (!rule) continue;
|
|
269
|
+
|
|
270
|
+
const existingValues = rule.headers[name];
|
|
271
|
+
rule.headers[name] = existingValues
|
|
272
|
+
? `${existingValues}, ${value}`
|
|
273
|
+
: value;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (rule && Object.keys(rule.headers).length > 0) {
|
|
277
|
+
rules[rule.path] = rule.headers;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
|
|
281
|
+
Object.fromEntries(
|
|
282
|
+
Object.entries(match).map(([name, value]) => [
|
|
283
|
+
name,
|
|
284
|
+
replacer(value, replacements),
|
|
285
|
+
])
|
|
286
|
+
)
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
return (request: Request) => {
|
|
290
|
+
const matches = rulesMatcher({
|
|
291
|
+
request,
|
|
292
|
+
});
|
|
293
|
+
if (matches) return matches;
|
|
294
|
+
};
|
|
295
|
+
} else {
|
|
296
|
+
return () => undefined;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function generateRedirectsMatcher(redirectsFile: string) {
|
|
301
|
+
if (existsSync(redirectsFile)) {
|
|
302
|
+
const contents = readFileSync(redirectsFile).toString();
|
|
303
|
+
|
|
304
|
+
// TODO: Log errors
|
|
305
|
+
const lines = contents
|
|
306
|
+
.split("\n")
|
|
307
|
+
.map((line) => line.trim())
|
|
308
|
+
.filter((line) => !line.startsWith("#") && line !== "");
|
|
309
|
+
|
|
310
|
+
const rules = Object.fromEntries(
|
|
311
|
+
lines
|
|
312
|
+
.map((line) => line.split(" "))
|
|
313
|
+
.filter((tokens) => tokens.length === 2 || tokens.length === 3)
|
|
314
|
+
.map((tokens) => {
|
|
315
|
+
const from = validateURL(tokens[0], true, false, false);
|
|
316
|
+
const to = validateURL(tokens[1], false, true, true);
|
|
317
|
+
let status: number | undefined = parseInt(tokens[2]) || 302;
|
|
318
|
+
status = [301, 302, 303, 307, 308].includes(status)
|
|
319
|
+
? status
|
|
320
|
+
: undefined;
|
|
321
|
+
|
|
322
|
+
return from && to && status ? [from, { to, status }] : undefined;
|
|
323
|
+
})
|
|
324
|
+
.filter((rule) => rule !== undefined) as [
|
|
325
|
+
string,
|
|
326
|
+
{ to: string; status?: number }
|
|
327
|
+
][]
|
|
328
|
+
);
|
|
329
|
+
|
|
330
|
+
const rulesMatcher = generateRulesMatcher(
|
|
331
|
+
rules,
|
|
332
|
+
({ status, to }, replacements) => ({
|
|
333
|
+
status,
|
|
334
|
+
to: replacer(to, replacements),
|
|
335
|
+
})
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
return (request: Request) => {
|
|
339
|
+
const match = rulesMatcher({
|
|
340
|
+
request,
|
|
341
|
+
})[0];
|
|
342
|
+
if (match) return match;
|
|
343
|
+
};
|
|
344
|
+
} else {
|
|
345
|
+
return () => undefined;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function extractPathname(
|
|
350
|
+
path = "/",
|
|
351
|
+
includeSearch: boolean,
|
|
352
|
+
includeHash: boolean
|
|
353
|
+
) {
|
|
354
|
+
if (!path.startsWith("/")) path = `/${path}`;
|
|
355
|
+
const url = new URL(`//${path}`, "relative://");
|
|
356
|
+
return `${url.pathname}${includeSearch ? url.search : ""}${
|
|
357
|
+
includeHash ? url.hash : ""
|
|
358
|
+
}`;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function validateURL(
|
|
362
|
+
token: string,
|
|
363
|
+
onlyRelative = false,
|
|
364
|
+
includeSearch = false,
|
|
365
|
+
includeHash = false
|
|
366
|
+
) {
|
|
367
|
+
const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
|
|
368
|
+
if (host && host.groups && host.groups.host) {
|
|
369
|
+
if (onlyRelative) return;
|
|
370
|
+
|
|
371
|
+
return `https://${host.groups.host}${extractPathname(
|
|
372
|
+
host.groups.path,
|
|
373
|
+
includeSearch,
|
|
374
|
+
includeHash
|
|
375
|
+
)}`;
|
|
376
|
+
} else {
|
|
377
|
+
if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
|
|
378
|
+
|
|
379
|
+
const path = /^\//.exec(token);
|
|
380
|
+
if (path) {
|
|
381
|
+
try {
|
|
382
|
+
return extractPathname(token, includeSearch, includeHash);
|
|
383
|
+
} catch {}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return "";
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function hasFileExtension(pathname: string) {
|
|
390
|
+
return /\/.+\.[a-z0-9]+$/i.test(pathname);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
|
|
394
|
+
// Defer importing miniflare until we really need it
|
|
395
|
+
const { Headers, Request, Response } = await import("@miniflare/core");
|
|
396
|
+
|
|
397
|
+
const headersFile = join(directory, "_headers");
|
|
398
|
+
const redirectsFile = join(directory, "_redirects");
|
|
399
|
+
const workerFile = join(directory, "_worker.js");
|
|
400
|
+
|
|
401
|
+
const ignoredFiles = [headersFile, redirectsFile, workerFile];
|
|
402
|
+
|
|
403
|
+
const assetExists = (path: string) => {
|
|
404
|
+
path = join(directory, path);
|
|
405
|
+
return (
|
|
406
|
+
existsSync(path) &&
|
|
407
|
+
lstatSync(path).isFile() &&
|
|
408
|
+
!ignoredFiles.includes(path)
|
|
409
|
+
);
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
const getAsset = (path: string) => {
|
|
413
|
+
if (assetExists(path)) {
|
|
414
|
+
return join(directory, path);
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
|
|
419
|
+
let headersMatcher = generateHeadersMatcher(headersFile);
|
|
420
|
+
|
|
421
|
+
watch([headersFile, redirectsFile], {
|
|
422
|
+
persistent: true,
|
|
423
|
+
}).on("change", (path) => {
|
|
424
|
+
switch (path) {
|
|
425
|
+
case headersFile: {
|
|
426
|
+
console.log("_headers modified. Re-evaluating...");
|
|
427
|
+
headersMatcher = generateHeadersMatcher(headersFile);
|
|
428
|
+
break;
|
|
429
|
+
}
|
|
430
|
+
case redirectsFile: {
|
|
431
|
+
console.log("_redirects modified. Re-evaluating...");
|
|
432
|
+
redirectsMatcher = generateRedirectsMatcher(redirectsFile);
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
const serveAsset = (file: string) => {
|
|
439
|
+
return readFileSync(file);
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
const generateResponse = (request: Request) => {
|
|
443
|
+
const url = new URL(request.url);
|
|
444
|
+
|
|
445
|
+
const deconstructedResponse: {
|
|
446
|
+
status: number;
|
|
447
|
+
headers: Headers;
|
|
448
|
+
body?: Buffer;
|
|
449
|
+
} = {
|
|
450
|
+
status: 200,
|
|
451
|
+
headers: new Headers(),
|
|
452
|
+
body: undefined,
|
|
453
|
+
};
|
|
454
|
+
|
|
455
|
+
const match = redirectsMatcher(request);
|
|
456
|
+
if (match) {
|
|
457
|
+
const { status, to } = match;
|
|
458
|
+
|
|
459
|
+
let location = to;
|
|
460
|
+
let search;
|
|
461
|
+
|
|
462
|
+
if (to.startsWith("/")) {
|
|
463
|
+
search = new URL(location, "http://fakehost").search;
|
|
464
|
+
} else {
|
|
465
|
+
search = new URL(location).search;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
location = `${location}${search ? "" : url.search}`;
|
|
469
|
+
|
|
470
|
+
if (status && [301, 302, 303, 307, 308].includes(status)) {
|
|
471
|
+
deconstructedResponse.status = status;
|
|
472
|
+
} else {
|
|
473
|
+
deconstructedResponse.status = 302;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
deconstructedResponse.headers.set("Location", location);
|
|
477
|
+
return deconstructedResponse;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
if (!request.method?.match(/^(get|head)$/i)) {
|
|
481
|
+
deconstructedResponse.status = 405;
|
|
482
|
+
return deconstructedResponse;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const notFound = () => {
|
|
486
|
+
let cwd = url.pathname;
|
|
487
|
+
while (cwd) {
|
|
488
|
+
cwd = cwd.slice(0, cwd.lastIndexOf("/"));
|
|
489
|
+
|
|
490
|
+
if ((asset = getAsset(`${cwd}/404.html`))) {
|
|
491
|
+
deconstructedResponse.status = 404;
|
|
492
|
+
deconstructedResponse.body = serveAsset(asset);
|
|
493
|
+
deconstructedResponse.headers.set(
|
|
494
|
+
"Content-Type",
|
|
495
|
+
getType(asset) || "application/octet-stream"
|
|
496
|
+
);
|
|
497
|
+
return deconstructedResponse;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if ((asset = getAsset(`/index.html`))) {
|
|
502
|
+
deconstructedResponse.body = serveAsset(asset);
|
|
503
|
+
deconstructedResponse.headers.set(
|
|
504
|
+
"Content-Type",
|
|
505
|
+
getType(asset) || "application/octet-stream"
|
|
506
|
+
);
|
|
507
|
+
return deconstructedResponse;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
deconstructedResponse.status = 404;
|
|
511
|
+
return deconstructedResponse;
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
let asset;
|
|
515
|
+
|
|
516
|
+
if (url.pathname.endsWith("/")) {
|
|
517
|
+
if ((asset = getAsset(`${url.pathname}/index.html`))) {
|
|
518
|
+
deconstructedResponse.body = serveAsset(asset);
|
|
519
|
+
deconstructedResponse.headers.set(
|
|
520
|
+
"Content-Type",
|
|
521
|
+
getType(asset) || "application/octet-stream"
|
|
522
|
+
);
|
|
523
|
+
return deconstructedResponse;
|
|
524
|
+
} else if (
|
|
525
|
+
(asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
|
|
526
|
+
) {
|
|
527
|
+
deconstructedResponse.status = 301;
|
|
528
|
+
deconstructedResponse.headers.set(
|
|
529
|
+
"Location",
|
|
530
|
+
`${url.pathname.slice(0, -1)}${url.search}`
|
|
531
|
+
);
|
|
532
|
+
return deconstructedResponse;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
if (url.pathname.endsWith("/index")) {
|
|
537
|
+
deconstructedResponse.status = 301;
|
|
538
|
+
deconstructedResponse.headers.set(
|
|
539
|
+
"Location",
|
|
540
|
+
`${url.pathname.slice(0, -"index".length)}${url.search}`
|
|
541
|
+
);
|
|
542
|
+
return deconstructedResponse;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if ((asset = getAsset(url.pathname))) {
|
|
546
|
+
if (url.pathname.endsWith(".html")) {
|
|
547
|
+
const extensionlessPath = url.pathname.slice(0, -".html".length);
|
|
548
|
+
if (getAsset(extensionlessPath) || extensionlessPath === "/") {
|
|
549
|
+
deconstructedResponse.body = serveAsset(asset);
|
|
550
|
+
deconstructedResponse.headers.set(
|
|
551
|
+
"Content-Type",
|
|
552
|
+
getType(asset) || "application/octet-stream"
|
|
553
|
+
);
|
|
554
|
+
return deconstructedResponse;
|
|
555
|
+
} else {
|
|
556
|
+
deconstructedResponse.status = 301;
|
|
557
|
+
deconstructedResponse.headers.set(
|
|
558
|
+
"Location",
|
|
559
|
+
`${extensionlessPath}${url.search}`
|
|
560
|
+
);
|
|
561
|
+
return deconstructedResponse;
|
|
562
|
+
}
|
|
563
|
+
} else {
|
|
564
|
+
deconstructedResponse.body = serveAsset(asset);
|
|
565
|
+
deconstructedResponse.headers.set(
|
|
566
|
+
"Content-Type",
|
|
567
|
+
getType(asset) || "application/octet-stream"
|
|
568
|
+
);
|
|
569
|
+
return deconstructedResponse;
|
|
570
|
+
}
|
|
571
|
+
} else if (hasFileExtension(url.pathname)) {
|
|
572
|
+
notFound();
|
|
573
|
+
return deconstructedResponse;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
if ((asset = getAsset(`${url.pathname}.html`))) {
|
|
577
|
+
deconstructedResponse.body = serveAsset(asset);
|
|
578
|
+
deconstructedResponse.headers.set(
|
|
579
|
+
"Content-Type",
|
|
580
|
+
getType(asset) || "application/octet-stream"
|
|
581
|
+
);
|
|
582
|
+
return deconstructedResponse;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
if ((asset = getAsset(`${url.pathname}/index.html`))) {
|
|
586
|
+
deconstructedResponse.status = 301;
|
|
587
|
+
deconstructedResponse.headers.set(
|
|
588
|
+
"Location",
|
|
589
|
+
`${url.pathname}/${url.search}`
|
|
590
|
+
);
|
|
591
|
+
return deconstructedResponse;
|
|
592
|
+
} else {
|
|
593
|
+
notFound();
|
|
594
|
+
return deconstructedResponse;
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
const attachHeaders = (
|
|
599
|
+
request: Request,
|
|
600
|
+
deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
|
|
601
|
+
) => {
|
|
602
|
+
const headers = deconstructedResponse.headers;
|
|
603
|
+
const newHeaders = new Headers({});
|
|
604
|
+
const matches = headersMatcher(request) || [];
|
|
605
|
+
|
|
606
|
+
matches.forEach((match) => {
|
|
607
|
+
Object.entries(match).forEach(([name, value]) => {
|
|
608
|
+
newHeaders.append(name, `${value}`);
|
|
609
|
+
});
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
const combinedHeaders = {
|
|
613
|
+
...Object.fromEntries(headers.entries()),
|
|
614
|
+
...Object.fromEntries(newHeaders.entries()),
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
deconstructedResponse.headers = new Headers({});
|
|
618
|
+
Object.entries(combinedHeaders).forEach(([name, value]) => {
|
|
619
|
+
if (value) deconstructedResponse.headers.set(name, value);
|
|
620
|
+
});
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
return async (input, init) => {
|
|
624
|
+
const request = new Request(input, init);
|
|
625
|
+
const deconstructedResponse = generateResponse(request);
|
|
626
|
+
attachHeaders(request, deconstructedResponse);
|
|
627
|
+
|
|
628
|
+
const headers = new Headers();
|
|
629
|
+
|
|
630
|
+
[...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
|
|
631
|
+
if (value) headers.set(name, value);
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
return new Response(deconstructedResponse.body, {
|
|
635
|
+
headers,
|
|
636
|
+
status: deconstructedResponse.status,
|
|
637
|
+
});
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
const RUNNING_BUILDERS: BuildResult[] = [];
|
|
642
|
+
|
|
643
|
+
async function buildFunctions({
|
|
644
|
+
scriptPath,
|
|
645
|
+
functionsDirectory,
|
|
646
|
+
onEnd,
|
|
647
|
+
}: {
|
|
648
|
+
scriptPath: string;
|
|
649
|
+
functionsDirectory: string;
|
|
650
|
+
onEnd?: () => void;
|
|
651
|
+
}) {
|
|
652
|
+
RUNNING_BUILDERS.forEach(
|
|
653
|
+
(runningBuilder) => runningBuilder.stop && runningBuilder.stop()
|
|
654
|
+
);
|
|
655
|
+
|
|
656
|
+
const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
|
|
657
|
+
|
|
658
|
+
const config: Config = await generateConfigFromFileTree({
|
|
659
|
+
baseDir: functionsDirectory,
|
|
660
|
+
baseURL: "/",
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
await writeRoutesModule({
|
|
664
|
+
config,
|
|
665
|
+
srcDir: functionsDirectory,
|
|
666
|
+
outfile: routesModule,
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
RUNNING_BUILDERS.push(
|
|
670
|
+
await buildWorker({
|
|
671
|
+
routesModule,
|
|
672
|
+
outfile: scriptPath,
|
|
673
|
+
minify: false, // TODO: Expose option to enable
|
|
674
|
+
sourcemap: true,
|
|
675
|
+
watch: true,
|
|
676
|
+
onEnd,
|
|
677
|
+
})
|
|
678
|
+
);
|
|
679
|
+
}
|
|
149
680
|
|
|
150
681
|
export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
|
|
151
682
|
return yargs.command(
|
|
@@ -222,23 +753,49 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
|
|
|
222
753
|
const functionsDirectory = "./functions";
|
|
223
754
|
const usingFunctions = existsSync(functionsDirectory);
|
|
224
755
|
|
|
225
|
-
const
|
|
226
|
-
directory,
|
|
227
|
-
port: requestedProxyPort,
|
|
228
|
-
remaining: remaining as (string | number)[],
|
|
229
|
-
});
|
|
230
|
-
if (proxy === undefined) return undefined;
|
|
756
|
+
const command = remaining as (string | number)[];
|
|
231
757
|
|
|
232
|
-
|
|
758
|
+
let proxyPort: number | void;
|
|
759
|
+
|
|
760
|
+
if (directory === undefined) {
|
|
761
|
+
proxyPort = await spawnProxyProcess({
|
|
762
|
+
port: requestedProxyPort,
|
|
763
|
+
command,
|
|
764
|
+
});
|
|
765
|
+
if (proxyPort === undefined) return undefined;
|
|
766
|
+
}
|
|
233
767
|
|
|
234
768
|
let miniflareArgs: MiniflareOptions = {};
|
|
235
769
|
|
|
770
|
+
let scriptReady = true;
|
|
771
|
+
|
|
236
772
|
if (usingFunctions) {
|
|
237
773
|
const scriptPath = join(tmpdir(), "./functionsWorker.js");
|
|
774
|
+
|
|
775
|
+
console.log(`Compiling worker to "${scriptPath}"...`);
|
|
776
|
+
|
|
777
|
+
await buildFunctions({
|
|
778
|
+
scriptPath,
|
|
779
|
+
functionsDirectory,
|
|
780
|
+
onEnd: () => {
|
|
781
|
+
scriptReady = true;
|
|
782
|
+
},
|
|
783
|
+
});
|
|
784
|
+
|
|
785
|
+
watch([functionsDirectory], {
|
|
786
|
+
persistent: true,
|
|
787
|
+
}).on("all", async () => {
|
|
788
|
+
await buildFunctions({
|
|
789
|
+
scriptPath,
|
|
790
|
+
functionsDirectory,
|
|
791
|
+
onEnd: () => {
|
|
792
|
+
scriptReady = true;
|
|
793
|
+
},
|
|
794
|
+
});
|
|
795
|
+
});
|
|
796
|
+
|
|
238
797
|
miniflareArgs = {
|
|
239
798
|
scriptPath,
|
|
240
|
-
buildWatchPaths: [functionsDirectory],
|
|
241
|
-
buildCommand: `npx @cloudflare/pages-functions-compiler build ${functionsDirectory} --outfile ${scriptPath}`,
|
|
242
799
|
};
|
|
243
800
|
} else {
|
|
244
801
|
const scriptPath =
|
|
@@ -246,23 +803,44 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
|
|
|
246
803
|
? join(directory, singleWorkerScriptPath)
|
|
247
804
|
: singleWorkerScriptPath;
|
|
248
805
|
|
|
249
|
-
if (
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
806
|
+
if (existsSync(scriptPath)) {
|
|
807
|
+
miniflareArgs = {
|
|
808
|
+
scriptPath,
|
|
809
|
+
};
|
|
810
|
+
} else {
|
|
811
|
+
console.log("No functions. Shimming...");
|
|
812
|
+
miniflareArgs = {
|
|
813
|
+
// TODO: The fact that these request/response hacks are necessary is ridiculous.
|
|
814
|
+
// We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
|
|
815
|
+
script: `
|
|
816
|
+
export default {
|
|
817
|
+
async fetch(request, env, context) {
|
|
818
|
+
const response = await env.ASSETS.fetch(request.url, request)
|
|
819
|
+
return new Response(response.body, response)
|
|
820
|
+
}
|
|
821
|
+
}`,
|
|
822
|
+
};
|
|
253
823
|
}
|
|
254
|
-
|
|
255
|
-
miniflareArgs = {
|
|
256
|
-
scriptPath,
|
|
257
|
-
};
|
|
258
824
|
}
|
|
259
825
|
|
|
260
|
-
|
|
261
|
-
const {
|
|
826
|
+
// Defer importing miniflare until we really need it
|
|
827
|
+
const { Miniflare, Log, LogLevel } = await import("miniflare");
|
|
828
|
+
const { Response, fetch } = await import("@miniflare/core");
|
|
829
|
+
|
|
830
|
+
// Should only be called if no proxyPort, using `assert.fail()` here
|
|
831
|
+
// means the type of `assetsFetch` is still `typeof fetch`
|
|
832
|
+
const assetsFetch = proxyPort
|
|
833
|
+
? () => assert.fail()
|
|
834
|
+
: await generateAssetsFetch(directory);
|
|
262
835
|
const miniflare = new Miniflare({
|
|
836
|
+
port,
|
|
263
837
|
watch: true,
|
|
264
838
|
modules: true,
|
|
265
839
|
|
|
840
|
+
log: new Log(LogLevel.ERROR, { prefix: "pages" }),
|
|
841
|
+
logUnhandledRejections: true,
|
|
842
|
+
sourceMap: true,
|
|
843
|
+
|
|
266
844
|
kvNamespaces: kvs.map((kv) => kv.toString()),
|
|
267
845
|
|
|
268
846
|
durableObjects: Object.fromEntries(
|
|
@@ -271,24 +849,21 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
|
|
|
271
849
|
)
|
|
272
850
|
),
|
|
273
851
|
|
|
852
|
+
// User bindings
|
|
274
853
|
bindings: {
|
|
275
|
-
// User bindings
|
|
276
854
|
...Object.fromEntries(
|
|
277
855
|
bindings.map((binding) => binding.toString().split("="))
|
|
278
856
|
),
|
|
857
|
+
},
|
|
279
858
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
init?: RequestInit | undefined
|
|
285
|
-
) => {
|
|
859
|
+
// env.ASSETS.fetch
|
|
860
|
+
serviceBindings: {
|
|
861
|
+
async ASSETS(request) {
|
|
862
|
+
if (proxyPort) {
|
|
286
863
|
try {
|
|
287
|
-
let request = new Request(input, init);
|
|
288
864
|
const url = new URL(request.url);
|
|
289
865
|
url.host = `127.0.0.1:${proxyPort}`;
|
|
290
|
-
|
|
291
|
-
return await fetch(request);
|
|
866
|
+
return await fetch(url, request);
|
|
292
867
|
} catch (thrown) {
|
|
293
868
|
console.error(`Could not proxy request: ${thrown}`);
|
|
294
869
|
|
|
@@ -298,7 +873,19 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
|
|
|
298
873
|
{ status: 502 }
|
|
299
874
|
);
|
|
300
875
|
}
|
|
301
|
-
}
|
|
876
|
+
} else {
|
|
877
|
+
try {
|
|
878
|
+
return await assetsFetch(request);
|
|
879
|
+
} catch (thrown) {
|
|
880
|
+
console.error(`Could not serve static asset: ${thrown}`);
|
|
881
|
+
|
|
882
|
+
// TODO: Pretty error page
|
|
883
|
+
return new Response(
|
|
884
|
+
`[wrangler] Could not serve static asset: ${thrown}`,
|
|
885
|
+
{ status: 502 }
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
302
889
|
},
|
|
303
890
|
},
|
|
304
891
|
|
|
@@ -308,37 +895,27 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
|
|
|
308
895
|
|
|
309
896
|
...miniflareArgs,
|
|
310
897
|
});
|
|
311
|
-
const miniflareServer = await miniflare.createServer();
|
|
312
|
-
|
|
313
|
-
miniflareServer.listen(0, () => {
|
|
314
|
-
const address = miniflareServer.address();
|
|
315
|
-
if (typeof address === "string")
|
|
316
|
-
return exit(
|
|
317
|
-
"Could not determine Miniflare's port. Please report this issue to the Wrangler team."
|
|
318
|
-
);
|
|
319
898
|
|
|
320
|
-
|
|
899
|
+
// Wait for esbuild to finish building the script
|
|
900
|
+
while (!scriptReady) {}
|
|
321
901
|
|
|
322
|
-
|
|
902
|
+
try {
|
|
903
|
+
// `startServer` might throw if user code contains errors
|
|
904
|
+
const server = await miniflare.startServer();
|
|
905
|
+
console.log(`Serving at http://127.0.0.1:${port}/`);
|
|
323
906
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
target: `http://127.0.0.1:${miniflarePort}`,
|
|
328
|
-
})
|
|
329
|
-
);
|
|
330
|
-
|
|
331
|
-
app.use(
|
|
332
|
-
"/",
|
|
333
|
-
httpProxyMiddleware.createProxyMiddleware({
|
|
334
|
-
target: `http://127.0.0.1:${proxyPort}`,
|
|
335
|
-
})
|
|
336
|
-
);
|
|
907
|
+
if (process.env.BROWSER !== "none") {
|
|
908
|
+
await open(`http://127.0.0.1:${port}/`);
|
|
909
|
+
}
|
|
337
910
|
|
|
338
|
-
|
|
339
|
-
|
|
911
|
+
EXIT_CALLBACKS.push(() => {
|
|
912
|
+
server.close();
|
|
913
|
+
miniflare.dispose().catch((err) => miniflare.log.error(err));
|
|
340
914
|
});
|
|
341
|
-
})
|
|
915
|
+
} catch (e) {
|
|
916
|
+
miniflare.log.error(e);
|
|
917
|
+
EXIT("Could not start Miniflare.", 1);
|
|
918
|
+
}
|
|
342
919
|
}
|
|
343
920
|
);
|
|
344
921
|
};
|