wrangler 2.0.22 → 2.0.23
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/miniflare-dist/index.mjs +464 -4
- package/package.json +10 -3
- package/src/__tests__/dev.test.tsx +92 -4
- package/src/__tests__/kv.test.ts +80 -59
- package/src/__tests__/publish.test.ts +76 -0
- package/src/__tests__/version.test.ts +35 -0
- package/src/api/dev.ts +43 -9
- package/src/bundle.ts +30 -4
- package/src/config/config.ts +7 -0
- package/src/config/validation.ts +9 -1
- package/src/create-worker-preview.ts +3 -1
- package/src/dev/dev.tsx +28 -3
- package/src/dev/local.tsx +28 -10
- package/src/dev/remote.tsx +0 -4
- package/src/dev.tsx +82 -28
- package/src/index.tsx +40 -3
- package/src/miniflare-cli/assets.ts +543 -0
- package/src/miniflare-cli/index.ts +36 -4
- package/src/pages/dev.tsx +79 -638
- package/src/publish.ts +13 -0
- package/src/user/choose-account.tsx +20 -11
- package/templates/pages-shim.ts +9 -0
- package/wrangler-dist/cli.d.ts +32 -3
- package/wrangler-dist/cli.js +578 -5756
package/src/pages/dev.tsx
CHANGED
|
@@ -1,26 +1,16 @@
|
|
|
1
1
|
import { execSync, spawn } from "node:child_process";
|
|
2
|
-
import { existsSync
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
|
-
import { join, resolve
|
|
5
|
-
import { URL } from "node:url";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
6
5
|
import { watch } from "chokidar";
|
|
7
|
-
import {
|
|
8
|
-
import { getVarsForDev } from "../dev/dev-vars";
|
|
6
|
+
import { unstable_dev } from "../api";
|
|
9
7
|
import { FatalError } from "../errors";
|
|
10
8
|
import { logger } from "../logger";
|
|
11
9
|
import * as metrics from "../metrics";
|
|
12
|
-
import { getRequestContextCheckOptions } from "../miniflare-cli/request-context";
|
|
13
|
-
import openInBrowser from "../open-in-browser";
|
|
14
10
|
import { buildFunctions } from "./build";
|
|
15
11
|
import { SECONDS_TO_WAIT_FOR_PROXY } from "./constants";
|
|
16
12
|
import { CLEANUP, CLEANUP_CALLBACKS, pagesBetaWarning } from "./utils";
|
|
17
|
-
import type {
|
|
18
|
-
import type {
|
|
19
|
-
fetch as miniflareFetch,
|
|
20
|
-
Headers as MiniflareHeaders,
|
|
21
|
-
} from "@miniflare/core";
|
|
22
|
-
import type { MiniflareOptions, Request as MiniflareRequest } from "miniflare";
|
|
23
|
-
import type { Argv, ArgumentsCamelCase } from "yargs";
|
|
13
|
+
import type { ArgumentsCamelCase, Argv } from "yargs";
|
|
24
14
|
|
|
25
15
|
type PagesDevArgs = {
|
|
26
16
|
directory?: string;
|
|
@@ -33,6 +23,8 @@ type PagesDevArgs = {
|
|
|
33
23
|
kv?: (string | number)[];
|
|
34
24
|
do?: (string | number)[];
|
|
35
25
|
"live-reload": boolean;
|
|
26
|
+
"local-protocol"?: "https" | "http";
|
|
27
|
+
"experimental-enable-local-persistence": boolean;
|
|
36
28
|
"node-compat": boolean;
|
|
37
29
|
};
|
|
38
30
|
|
|
@@ -89,6 +81,15 @@ export function Options(yargs: Argv): Argv<PagesDevArgs> {
|
|
|
89
81
|
default: false,
|
|
90
82
|
description: "Auto reload HTML pages when change is detected",
|
|
91
83
|
},
|
|
84
|
+
"local-protocol": {
|
|
85
|
+
describe: "Protocol to listen to requests on, defaults to http.",
|
|
86
|
+
choices: ["http", "https"] as const,
|
|
87
|
+
},
|
|
88
|
+
"experimental-enable-local-persistence": {
|
|
89
|
+
type: "boolean",
|
|
90
|
+
default: false,
|
|
91
|
+
describe: "Enable persistence for this session (only for local mode)",
|
|
92
|
+
},
|
|
92
93
|
"node-compat": {
|
|
93
94
|
describe: "Enable node.js compatibility",
|
|
94
95
|
default: false,
|
|
@@ -100,7 +101,6 @@ export function Options(yargs: Argv): Argv<PagesDevArgs> {
|
|
|
100
101
|
type: "string",
|
|
101
102
|
hidden: true,
|
|
102
103
|
},
|
|
103
|
-
// // TODO: Miniflare user options
|
|
104
104
|
})
|
|
105
105
|
.epilogue(pagesBetaWarning);
|
|
106
106
|
}
|
|
@@ -115,6 +115,8 @@ export const Handler = async ({
|
|
|
115
115
|
kv: kvs = [],
|
|
116
116
|
do: durableObjects = [],
|
|
117
117
|
"live-reload": liveReload,
|
|
118
|
+
"local-protocol": localProtocol,
|
|
119
|
+
"experimental-enable-local-persistence": experimentalEnableLocalPersistence,
|
|
118
120
|
"node-compat": nodeCompat,
|
|
119
121
|
config: config,
|
|
120
122
|
_: [_pages, _dev, ...remaining],
|
|
@@ -133,9 +135,9 @@ export const Handler = async ({
|
|
|
133
135
|
const functionsDirectory = "./functions";
|
|
134
136
|
const usingFunctions = existsSync(functionsDirectory);
|
|
135
137
|
|
|
136
|
-
const command = remaining
|
|
138
|
+
const command = remaining;
|
|
137
139
|
|
|
138
|
-
let proxyPort: number |
|
|
140
|
+
let proxyPort: number | undefined;
|
|
139
141
|
|
|
140
142
|
if (directory === undefined) {
|
|
141
143
|
proxyPort = await spawnProxyProcess({
|
|
@@ -143,17 +145,20 @@ export const Handler = async ({
|
|
|
143
145
|
command,
|
|
144
146
|
});
|
|
145
147
|
if (proxyPort === undefined) return undefined;
|
|
148
|
+
} else {
|
|
149
|
+
directory = resolve(directory);
|
|
146
150
|
}
|
|
147
151
|
|
|
148
|
-
let miniflareArgs: MiniflareOptions = {};
|
|
149
|
-
|
|
150
152
|
let scriptReadyResolve: () => void;
|
|
151
153
|
const scriptReadyPromise = new Promise<void>(
|
|
152
|
-
(
|
|
154
|
+
(promiseResolve) => (scriptReadyResolve = promiseResolve)
|
|
153
155
|
);
|
|
154
156
|
|
|
157
|
+
let scriptPath: string;
|
|
158
|
+
|
|
155
159
|
if (usingFunctions) {
|
|
156
160
|
const outfile = join(tmpdir(), `./functionsWorker-${Math.random()}.js`);
|
|
161
|
+
scriptPath = outfile;
|
|
157
162
|
|
|
158
163
|
if (nodeCompat) {
|
|
159
164
|
console.warn(
|
|
@@ -191,160 +196,83 @@ export const Handler = async ({
|
|
|
191
196
|
});
|
|
192
197
|
await metrics.sendMetricsEvent("build pages functions");
|
|
193
198
|
});
|
|
194
|
-
|
|
195
|
-
miniflareArgs = {
|
|
196
|
-
scriptPath: outfile,
|
|
197
|
-
};
|
|
198
199
|
} else {
|
|
199
200
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
200
201
|
scriptReadyResolve!();
|
|
201
202
|
|
|
202
|
-
|
|
203
|
+
scriptPath =
|
|
203
204
|
directory !== undefined
|
|
204
205
|
? join(directory, singleWorkerScriptPath)
|
|
205
206
|
: singleWorkerScriptPath;
|
|
206
207
|
|
|
207
|
-
if (existsSync(scriptPath)) {
|
|
208
|
-
miniflareArgs = {
|
|
209
|
-
scriptPath,
|
|
210
|
-
};
|
|
211
|
-
} else {
|
|
208
|
+
if (!existsSync(scriptPath)) {
|
|
212
209
|
logger.log("No functions. Shimming...");
|
|
213
|
-
|
|
214
|
-
// cfFetch sets the `cf` object that a function could expect
|
|
215
|
-
// If there are no functions, there's no reason to set this up (and not make that network call)
|
|
216
|
-
cfFetch: false,
|
|
217
|
-
// TODO: The fact that these request/response hacks are necessary is ridiculous.
|
|
218
|
-
// We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
|
|
219
|
-
script: `
|
|
220
|
-
export default {
|
|
221
|
-
async fetch(request, env, context) {
|
|
222
|
-
const response = await env.ASSETS.fetch(request.url, request)
|
|
223
|
-
return new Response(response.body, response)
|
|
224
|
-
}
|
|
225
|
-
}`,
|
|
226
|
-
};
|
|
210
|
+
scriptPath = resolve(__dirname, "../templates/pages-shim.ts");
|
|
227
211
|
}
|
|
228
212
|
}
|
|
229
213
|
|
|
230
|
-
// Defer importing miniflare until we really need it
|
|
231
|
-
const { Miniflare, Log, LogLevel } = await import("miniflare");
|
|
232
|
-
const { Response, fetch } = await import("@miniflare/core");
|
|
233
|
-
|
|
234
|
-
// Wait for esbuild to finish building before starting Miniflare.
|
|
235
|
-
// This must be before the call to `new Miniflare`, as that will
|
|
236
|
-
// asynchronously start loading the script. `await startServer()`
|
|
237
|
-
// internally just waits for that promise to resolve.
|
|
238
214
|
await scriptReadyPromise;
|
|
239
215
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
} as Config);
|
|
252
|
-
|
|
253
|
-
const miniflare = new Miniflare({
|
|
254
|
-
port,
|
|
255
|
-
watch: true,
|
|
256
|
-
modules: true,
|
|
257
|
-
|
|
258
|
-
log: new Log(LogLevel.ERROR, { prefix: "pages" }),
|
|
259
|
-
logUnhandledRejections: true,
|
|
260
|
-
sourceMap: true,
|
|
261
|
-
|
|
262
|
-
kvNamespaces: kvs.map((kv) => kv.toString()),
|
|
263
|
-
|
|
264
|
-
durableObjects: Object.fromEntries(
|
|
265
|
-
durableObjects.map((durableObject) => durableObject.toString().split("="))
|
|
266
|
-
),
|
|
267
|
-
|
|
268
|
-
// User bindings
|
|
269
|
-
bindings: {
|
|
270
|
-
...vars,
|
|
271
|
-
...Object.fromEntries(
|
|
216
|
+
const { stop, waitUntilExit } = await unstable_dev(
|
|
217
|
+
scriptPath,
|
|
218
|
+
{
|
|
219
|
+
port,
|
|
220
|
+
watch: true,
|
|
221
|
+
localProtocol,
|
|
222
|
+
liveReload,
|
|
223
|
+
|
|
224
|
+
compatibilityDate: "2021-11-02",
|
|
225
|
+
nodeCompat,
|
|
226
|
+
vars: Object.fromEntries(
|
|
272
227
|
bindings
|
|
273
228
|
.map((binding) => binding.toString().split("="))
|
|
274
229
|
.map(([key, ...values]) => [key, values.join("=")])
|
|
275
230
|
),
|
|
276
|
-
|
|
231
|
+
kv: kvs.map((val) => ({
|
|
232
|
+
binding: val.toString(),
|
|
233
|
+
id: "",
|
|
234
|
+
})),
|
|
235
|
+
durableObjects: durableObjects.map((durableObject) => {
|
|
236
|
+
const [name, class_name] = durableObject.toString().split("=");
|
|
237
|
+
return {
|
|
238
|
+
name,
|
|
239
|
+
class_name,
|
|
240
|
+
};
|
|
241
|
+
}),
|
|
277
242
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
if (proxyPort) {
|
|
282
|
-
try {
|
|
283
|
-
const url = new URL(request.url);
|
|
284
|
-
url.host = `localhost:${proxyPort}`;
|
|
285
|
-
return await fetch(url, request);
|
|
286
|
-
} catch (thrown) {
|
|
287
|
-
logger.error(`Could not proxy request: ${thrown}`);
|
|
288
|
-
|
|
289
|
-
// TODO: Pretty error page
|
|
290
|
-
return new Response(
|
|
291
|
-
`[wrangler] Could not proxy request: ${thrown}`,
|
|
292
|
-
{ status: 502 }
|
|
293
|
-
);
|
|
294
|
-
}
|
|
295
|
-
} else {
|
|
296
|
-
try {
|
|
297
|
-
return await assetsFetch(request);
|
|
298
|
-
} catch (thrown) {
|
|
299
|
-
logger.error(`Could not serve static asset: ${thrown}`);
|
|
300
|
-
|
|
301
|
-
// TODO: Pretty error page
|
|
302
|
-
return new Response(
|
|
303
|
-
`[wrangler] Could not serve static asset: ${thrown}`,
|
|
304
|
-
{ status: 502 }
|
|
305
|
-
);
|
|
306
|
-
}
|
|
307
|
-
}
|
|
243
|
+
enablePagesAssetsServiceBinding: {
|
|
244
|
+
proxyPort,
|
|
245
|
+
directory,
|
|
308
246
|
},
|
|
247
|
+
forceLocal: true,
|
|
248
|
+
experimentalEnableLocalPersistence,
|
|
249
|
+
showInteractiveDevSession: undefined,
|
|
250
|
+
inspect: true,
|
|
251
|
+
logLevel: "error",
|
|
252
|
+
logPrefix: "pages",
|
|
309
253
|
},
|
|
254
|
+
true
|
|
255
|
+
);
|
|
256
|
+
await metrics.sendMetricsEvent("run pages dev");
|
|
310
257
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
...requestContextCheckOptions,
|
|
317
|
-
...miniflareArgs,
|
|
258
|
+
waitUntilExit().then(() => {
|
|
259
|
+
CLEANUP();
|
|
260
|
+
stop();
|
|
261
|
+
process.exit(0);
|
|
318
262
|
});
|
|
319
263
|
|
|
320
|
-
|
|
321
|
-
// `startServer` might throw if user code contains errors
|
|
322
|
-
const server = await miniflare.startServer();
|
|
323
|
-
logger.log(`Serving at http://localhost:${port}/`);
|
|
324
|
-
await metrics.sendMetricsEvent("run pages dev");
|
|
325
|
-
|
|
326
|
-
if (process.env.BROWSER !== "none") {
|
|
327
|
-
await openInBrowser(`http://localhost:${port}/`);
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
if (directory !== undefined && liveReload) {
|
|
331
|
-
watch([directory], {
|
|
332
|
-
persistent: true,
|
|
333
|
-
ignoreInitial: true,
|
|
334
|
-
}).on("all", async () => {
|
|
335
|
-
await miniflare.reload();
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
CLEANUP_CALLBACKS.push(() => {
|
|
340
|
-
server.close();
|
|
341
|
-
miniflare.dispose().catch((err) => miniflare.log.error(err));
|
|
342
|
-
});
|
|
343
|
-
} catch (e) {
|
|
344
|
-
miniflare.log.error(e as Error);
|
|
264
|
+
process.on("exit", () => {
|
|
345
265
|
CLEANUP();
|
|
346
|
-
|
|
347
|
-
}
|
|
266
|
+
stop();
|
|
267
|
+
});
|
|
268
|
+
process.on("SIGINT", () => {
|
|
269
|
+
CLEANUP();
|
|
270
|
+
stop();
|
|
271
|
+
});
|
|
272
|
+
process.on("SIGTERM", () => {
|
|
273
|
+
CLEANUP();
|
|
274
|
+
stop();
|
|
275
|
+
});
|
|
348
276
|
};
|
|
349
277
|
|
|
350
278
|
function isWindows() {
|
|
@@ -352,7 +280,7 @@ function isWindows() {
|
|
|
352
280
|
}
|
|
353
281
|
|
|
354
282
|
async function sleep(ms: number) {
|
|
355
|
-
await new Promise((
|
|
283
|
+
await new Promise((promiseResolve) => setTimeout(promiseResolve, ms));
|
|
356
284
|
}
|
|
357
285
|
|
|
358
286
|
function getPids(pid: number) {
|
|
@@ -415,7 +343,7 @@ async function spawnProxyProcess({
|
|
|
415
343
|
}: {
|
|
416
344
|
port?: number;
|
|
417
345
|
command: (string | number)[];
|
|
418
|
-
}): Promise<
|
|
346
|
+
}): Promise<undefined | number> {
|
|
419
347
|
if (command.length === 0) {
|
|
420
348
|
CLEANUP();
|
|
421
349
|
throw new FatalError(
|
|
@@ -479,490 +407,3 @@ async function spawnProxyProcess({
|
|
|
479
407
|
|
|
480
408
|
return port;
|
|
481
409
|
}
|
|
482
|
-
|
|
483
|
-
function escapeRegex(str: string) {
|
|
484
|
-
return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
type Replacements = Record<string, string>;
|
|
488
|
-
|
|
489
|
-
function replacer(str: string, replacements: Replacements) {
|
|
490
|
-
for (const [replacement, value] of Object.entries(replacements)) {
|
|
491
|
-
str = str.replace(`:${replacement}`, value);
|
|
492
|
-
}
|
|
493
|
-
return str;
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
function generateRulesMatcher<T>(
|
|
497
|
-
rules?: Record<string, T>,
|
|
498
|
-
replacerFn: (match: T, replacements: Replacements) => T = (match) => match
|
|
499
|
-
) {
|
|
500
|
-
// TODO: How can you test cross-host rules?
|
|
501
|
-
if (!rules) return () => [];
|
|
502
|
-
|
|
503
|
-
const compiledRules = Object.entries(rules)
|
|
504
|
-
.map(([rule, match]) => {
|
|
505
|
-
const crossHost = rule.startsWith("https://");
|
|
506
|
-
|
|
507
|
-
rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
|
|
508
|
-
|
|
509
|
-
const host_matches = rule.matchAll(
|
|
510
|
-
/(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
|
|
511
|
-
);
|
|
512
|
-
for (const hostMatch of host_matches) {
|
|
513
|
-
rule = rule.split(hostMatch[0]).join(`(?<${hostMatch[1]}>[^/.]+)`);
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
const path_matches = rule.matchAll(/:(\w+)/g);
|
|
517
|
-
for (const pathMatch of path_matches) {
|
|
518
|
-
rule = rule.split(pathMatch[0]).join(`(?<${pathMatch[1]}>[^/]+)`);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
rule = "^" + rule + "$";
|
|
522
|
-
|
|
523
|
-
try {
|
|
524
|
-
const regExp = new RegExp(rule);
|
|
525
|
-
return [{ crossHost, regExp }, match];
|
|
526
|
-
} catch {}
|
|
527
|
-
})
|
|
528
|
-
.filter((value) => value !== undefined) as [
|
|
529
|
-
{ crossHost: boolean; regExp: RegExp },
|
|
530
|
-
T
|
|
531
|
-
][];
|
|
532
|
-
|
|
533
|
-
return ({ request }: { request: MiniflareRequest }) => {
|
|
534
|
-
const { pathname, host } = new URL(request.url);
|
|
535
|
-
|
|
536
|
-
return compiledRules
|
|
537
|
-
.map(([{ crossHost, regExp }, match]) => {
|
|
538
|
-
const test = crossHost ? `https://${host}${pathname}` : pathname;
|
|
539
|
-
const result = regExp.exec(test);
|
|
540
|
-
if (result) {
|
|
541
|
-
return replacerFn(match, result.groups || {});
|
|
542
|
-
}
|
|
543
|
-
})
|
|
544
|
-
.filter((value) => value !== undefined) as T[];
|
|
545
|
-
};
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
function generateHeadersMatcher(headersFile: string) {
|
|
549
|
-
if (existsSync(headersFile)) {
|
|
550
|
-
const contents = readFileSync(headersFile).toString();
|
|
551
|
-
|
|
552
|
-
// TODO: Log errors
|
|
553
|
-
const lines = contents
|
|
554
|
-
.split("\n")
|
|
555
|
-
.map((line) => line.trim())
|
|
556
|
-
.filter((line) => !line.startsWith("#") && line !== "");
|
|
557
|
-
|
|
558
|
-
const rules: Record<string, Record<string, string>> = {};
|
|
559
|
-
let rule: { path: string; headers: Record<string, string> } | undefined =
|
|
560
|
-
undefined;
|
|
561
|
-
|
|
562
|
-
for (const line of lines) {
|
|
563
|
-
if (/^([^\s]+:\/\/|^\/)/.test(line)) {
|
|
564
|
-
if (rule && Object.keys(rule.headers).length > 0) {
|
|
565
|
-
rules[rule.path] = rule.headers;
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
const path = validateURL(line);
|
|
569
|
-
if (path) {
|
|
570
|
-
rule = {
|
|
571
|
-
path,
|
|
572
|
-
headers: {},
|
|
573
|
-
};
|
|
574
|
-
continue;
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
if (!line.includes(":")) continue;
|
|
579
|
-
|
|
580
|
-
const [rawName, ...rawValue] = line.split(":");
|
|
581
|
-
const name = rawName.trim().toLowerCase();
|
|
582
|
-
const value = rawValue.join(":").trim();
|
|
583
|
-
|
|
584
|
-
if (name === "") continue;
|
|
585
|
-
if (!rule) continue;
|
|
586
|
-
|
|
587
|
-
const existingValues = rule.headers[name];
|
|
588
|
-
rule.headers[name] = existingValues
|
|
589
|
-
? `${existingValues}, ${value}`
|
|
590
|
-
: value;
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
if (rule && Object.keys(rule.headers).length > 0) {
|
|
594
|
-
rules[rule.path] = rule.headers;
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
|
|
598
|
-
Object.fromEntries(
|
|
599
|
-
Object.entries(match).map(([name, value]) => [
|
|
600
|
-
name,
|
|
601
|
-
replacer(value, replacements),
|
|
602
|
-
])
|
|
603
|
-
)
|
|
604
|
-
);
|
|
605
|
-
|
|
606
|
-
return (request: MiniflareRequest) => {
|
|
607
|
-
const matches = rulesMatcher({
|
|
608
|
-
request,
|
|
609
|
-
});
|
|
610
|
-
if (matches) return matches;
|
|
611
|
-
};
|
|
612
|
-
} else {
|
|
613
|
-
return () => undefined;
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
function generateRedirectsMatcher(redirectsFile: string) {
|
|
618
|
-
if (existsSync(redirectsFile)) {
|
|
619
|
-
const contents = readFileSync(redirectsFile).toString();
|
|
620
|
-
|
|
621
|
-
// TODO: Log errors
|
|
622
|
-
const lines = contents
|
|
623
|
-
.split("\n")
|
|
624
|
-
.map((line) => line.trim())
|
|
625
|
-
.filter((line) => !line.startsWith("#") && line !== "");
|
|
626
|
-
|
|
627
|
-
const rules = Object.fromEntries(
|
|
628
|
-
lines
|
|
629
|
-
.map((line) => line.split(" "))
|
|
630
|
-
.filter((tokens) => tokens.length === 2 || tokens.length === 3)
|
|
631
|
-
.map((tokens) => {
|
|
632
|
-
const from = validateURL(tokens[0], true, false, false);
|
|
633
|
-
const to = validateURL(tokens[1], false, true, true);
|
|
634
|
-
let status: number | undefined = parseInt(tokens[2]) || 302;
|
|
635
|
-
status = [301, 302, 303, 307, 308].includes(status)
|
|
636
|
-
? status
|
|
637
|
-
: undefined;
|
|
638
|
-
|
|
639
|
-
return from && to && status ? [from, { to, status }] : undefined;
|
|
640
|
-
})
|
|
641
|
-
.filter((rule) => rule !== undefined) as [
|
|
642
|
-
string,
|
|
643
|
-
{ to: string; status?: number }
|
|
644
|
-
][]
|
|
645
|
-
);
|
|
646
|
-
|
|
647
|
-
const rulesMatcher = generateRulesMatcher(
|
|
648
|
-
rules,
|
|
649
|
-
({ status, to }, replacements) => ({
|
|
650
|
-
status,
|
|
651
|
-
to: replacer(to, replacements),
|
|
652
|
-
})
|
|
653
|
-
);
|
|
654
|
-
|
|
655
|
-
return (request: MiniflareRequest) => {
|
|
656
|
-
const match = rulesMatcher({
|
|
657
|
-
request,
|
|
658
|
-
})[0];
|
|
659
|
-
if (match) return match;
|
|
660
|
-
};
|
|
661
|
-
} else {
|
|
662
|
-
return () => undefined;
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
function extractPathname(
|
|
667
|
-
path = "/",
|
|
668
|
-
includeSearch: boolean,
|
|
669
|
-
includeHash: boolean
|
|
670
|
-
) {
|
|
671
|
-
if (!path.startsWith("/")) path = `/${path}`;
|
|
672
|
-
const url = new URL(`//${path}`, "relative://");
|
|
673
|
-
return `${url.pathname}${includeSearch ? url.search : ""}${
|
|
674
|
-
includeHash ? url.hash : ""
|
|
675
|
-
}`;
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
function validateURL(
|
|
679
|
-
token: string,
|
|
680
|
-
onlyRelative = false,
|
|
681
|
-
includeSearch = false,
|
|
682
|
-
includeHash = false
|
|
683
|
-
) {
|
|
684
|
-
const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
|
|
685
|
-
if (host && host.groups && host.groups.host) {
|
|
686
|
-
if (onlyRelative) return;
|
|
687
|
-
|
|
688
|
-
return `https://${host.groups.host}${extractPathname(
|
|
689
|
-
host.groups.path,
|
|
690
|
-
includeSearch,
|
|
691
|
-
includeHash
|
|
692
|
-
)}`;
|
|
693
|
-
} else {
|
|
694
|
-
if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
|
|
695
|
-
|
|
696
|
-
const path = /^\//.exec(token);
|
|
697
|
-
if (path) {
|
|
698
|
-
try {
|
|
699
|
-
return extractPathname(token, includeSearch, includeHash);
|
|
700
|
-
} catch {}
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
return "";
|
|
704
|
-
}
|
|
705
|
-
|
|
706
|
-
function hasFileExtension(pathname: string) {
|
|
707
|
-
return /\/.+\.[a-z0-9]+$/i.test(pathname);
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
async function generateAssetsFetch(
|
|
711
|
-
directory: string
|
|
712
|
-
): Promise<typeof miniflareFetch> {
|
|
713
|
-
// Defer importing miniflare until we really need it
|
|
714
|
-
const { Headers, Request, Response } = await import("@miniflare/core");
|
|
715
|
-
|
|
716
|
-
const headersFile = join(directory, "_headers");
|
|
717
|
-
const redirectsFile = join(directory, "_redirects");
|
|
718
|
-
const workerFile = join(directory, "_worker.js");
|
|
719
|
-
|
|
720
|
-
const ignoredFiles = [headersFile, redirectsFile, workerFile];
|
|
721
|
-
|
|
722
|
-
const assetExists = (path: string) => {
|
|
723
|
-
path = join(directory, path);
|
|
724
|
-
return (
|
|
725
|
-
existsSync(path) &&
|
|
726
|
-
lstatSync(path).isFile() &&
|
|
727
|
-
!ignoredFiles.includes(path)
|
|
728
|
-
);
|
|
729
|
-
};
|
|
730
|
-
|
|
731
|
-
const getAsset = (path: string) => {
|
|
732
|
-
if (assetExists(path)) {
|
|
733
|
-
return join(directory, path);
|
|
734
|
-
}
|
|
735
|
-
};
|
|
736
|
-
|
|
737
|
-
let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
|
|
738
|
-
let headersMatcher = generateHeadersMatcher(headersFile);
|
|
739
|
-
|
|
740
|
-
watch([headersFile, redirectsFile], {
|
|
741
|
-
persistent: true,
|
|
742
|
-
}).on("change", (path) => {
|
|
743
|
-
switch (path) {
|
|
744
|
-
case headersFile: {
|
|
745
|
-
logger.log("_headers modified. Re-evaluating...");
|
|
746
|
-
headersMatcher = generateHeadersMatcher(headersFile);
|
|
747
|
-
break;
|
|
748
|
-
}
|
|
749
|
-
case redirectsFile: {
|
|
750
|
-
logger.log("_redirects modified. Re-evaluating...");
|
|
751
|
-
redirectsMatcher = generateRedirectsMatcher(redirectsFile);
|
|
752
|
-
break;
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
});
|
|
756
|
-
|
|
757
|
-
const serveAsset = (file: string) => {
|
|
758
|
-
return readFileSync(file);
|
|
759
|
-
};
|
|
760
|
-
|
|
761
|
-
const generateResponse = (request: MiniflareRequest) => {
|
|
762
|
-
const url = new URL(request.url);
|
|
763
|
-
|
|
764
|
-
const deconstructedResponse: {
|
|
765
|
-
status: number;
|
|
766
|
-
headers: MiniflareHeaders;
|
|
767
|
-
body?: Buffer;
|
|
768
|
-
} = {
|
|
769
|
-
status: 200,
|
|
770
|
-
headers: new Headers(),
|
|
771
|
-
body: undefined,
|
|
772
|
-
};
|
|
773
|
-
|
|
774
|
-
const match = redirectsMatcher(request);
|
|
775
|
-
if (match) {
|
|
776
|
-
const { status, to } = match;
|
|
777
|
-
|
|
778
|
-
let location = to;
|
|
779
|
-
let search;
|
|
780
|
-
|
|
781
|
-
if (to.startsWith("/")) {
|
|
782
|
-
search = new URL(location, "http://fakehost").search;
|
|
783
|
-
} else {
|
|
784
|
-
search = new URL(location).search;
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
location = `${location}${search ? "" : url.search}`;
|
|
788
|
-
|
|
789
|
-
if (status && [301, 302, 303, 307, 308].includes(status)) {
|
|
790
|
-
deconstructedResponse.status = status;
|
|
791
|
-
} else {
|
|
792
|
-
deconstructedResponse.status = 302;
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
deconstructedResponse.headers.set("Location", location);
|
|
796
|
-
return deconstructedResponse;
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
if (!request.method?.match(/^(get|head)$/i)) {
|
|
800
|
-
deconstructedResponse.status = 405;
|
|
801
|
-
return deconstructedResponse;
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
const notFound = () => {
|
|
805
|
-
let cwd = url.pathname;
|
|
806
|
-
while (cwd) {
|
|
807
|
-
cwd = cwd.slice(0, cwd.lastIndexOf("/"));
|
|
808
|
-
|
|
809
|
-
if ((asset = getAsset(`${cwd}/404.html`))) {
|
|
810
|
-
deconstructedResponse.status = 404;
|
|
811
|
-
deconstructedResponse.body = serveAsset(asset);
|
|
812
|
-
deconstructedResponse.headers.set(
|
|
813
|
-
"Content-Type",
|
|
814
|
-
getType(asset) || "application/octet-stream"
|
|
815
|
-
);
|
|
816
|
-
return deconstructedResponse;
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
if ((asset = getAsset(`/index.html`))) {
|
|
821
|
-
deconstructedResponse.body = serveAsset(asset);
|
|
822
|
-
deconstructedResponse.headers.set(
|
|
823
|
-
"Content-Type",
|
|
824
|
-
getType(asset) || "application/octet-stream"
|
|
825
|
-
);
|
|
826
|
-
return deconstructedResponse;
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
deconstructedResponse.status = 404;
|
|
830
|
-
return deconstructedResponse;
|
|
831
|
-
};
|
|
832
|
-
|
|
833
|
-
let asset;
|
|
834
|
-
|
|
835
|
-
if (url.pathname.endsWith("/")) {
|
|
836
|
-
if ((asset = getAsset(`${url.pathname}/index.html`))) {
|
|
837
|
-
deconstructedResponse.body = serveAsset(asset);
|
|
838
|
-
deconstructedResponse.headers.set(
|
|
839
|
-
"Content-Type",
|
|
840
|
-
getType(asset) || "application/octet-stream"
|
|
841
|
-
);
|
|
842
|
-
return deconstructedResponse;
|
|
843
|
-
} else if (
|
|
844
|
-
(asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
|
|
845
|
-
) {
|
|
846
|
-
deconstructedResponse.status = 301;
|
|
847
|
-
deconstructedResponse.headers.set(
|
|
848
|
-
"Location",
|
|
849
|
-
`${url.pathname.slice(0, -1)}${url.search}`
|
|
850
|
-
);
|
|
851
|
-
return deconstructedResponse;
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
if (url.pathname.endsWith("/index")) {
|
|
856
|
-
deconstructedResponse.status = 301;
|
|
857
|
-
deconstructedResponse.headers.set(
|
|
858
|
-
"Location",
|
|
859
|
-
`${url.pathname.slice(0, -"index".length)}${url.search}`
|
|
860
|
-
);
|
|
861
|
-
return deconstructedResponse;
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
if ((asset = getAsset(url.pathname))) {
|
|
865
|
-
if (url.pathname.endsWith(".html")) {
|
|
866
|
-
const extensionlessPath = url.pathname.slice(0, -".html".length);
|
|
867
|
-
if (getAsset(extensionlessPath) || extensionlessPath === "/") {
|
|
868
|
-
deconstructedResponse.body = serveAsset(asset);
|
|
869
|
-
deconstructedResponse.headers.set(
|
|
870
|
-
"Content-Type",
|
|
871
|
-
getType(asset) || "application/octet-stream"
|
|
872
|
-
);
|
|
873
|
-
return deconstructedResponse;
|
|
874
|
-
} else {
|
|
875
|
-
deconstructedResponse.status = 301;
|
|
876
|
-
deconstructedResponse.headers.set(
|
|
877
|
-
"Location",
|
|
878
|
-
`${extensionlessPath}${url.search}`
|
|
879
|
-
);
|
|
880
|
-
return deconstructedResponse;
|
|
881
|
-
}
|
|
882
|
-
} else {
|
|
883
|
-
deconstructedResponse.body = serveAsset(asset);
|
|
884
|
-
deconstructedResponse.headers.set(
|
|
885
|
-
"Content-Type",
|
|
886
|
-
getType(asset) || "application/octet-stream"
|
|
887
|
-
);
|
|
888
|
-
return deconstructedResponse;
|
|
889
|
-
}
|
|
890
|
-
} else if (hasFileExtension(url.pathname)) {
|
|
891
|
-
notFound();
|
|
892
|
-
return deconstructedResponse;
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
if ((asset = getAsset(`${url.pathname}.html`))) {
|
|
896
|
-
deconstructedResponse.body = serveAsset(asset);
|
|
897
|
-
deconstructedResponse.headers.set(
|
|
898
|
-
"Content-Type",
|
|
899
|
-
getType(asset) || "application/octet-stream"
|
|
900
|
-
);
|
|
901
|
-
return deconstructedResponse;
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
if ((asset = getAsset(`${url.pathname}/index.html`))) {
|
|
905
|
-
deconstructedResponse.status = 301;
|
|
906
|
-
deconstructedResponse.headers.set(
|
|
907
|
-
"Location",
|
|
908
|
-
`${url.pathname}/${url.search}`
|
|
909
|
-
);
|
|
910
|
-
return deconstructedResponse;
|
|
911
|
-
} else {
|
|
912
|
-
notFound();
|
|
913
|
-
return deconstructedResponse;
|
|
914
|
-
}
|
|
915
|
-
};
|
|
916
|
-
|
|
917
|
-
const attachHeaders = (
|
|
918
|
-
request: MiniflareRequest,
|
|
919
|
-
deconstructedResponse: {
|
|
920
|
-
status: number;
|
|
921
|
-
headers: MiniflareHeaders;
|
|
922
|
-
body?: Buffer;
|
|
923
|
-
}
|
|
924
|
-
) => {
|
|
925
|
-
const headers = deconstructedResponse.headers;
|
|
926
|
-
const newHeaders = new Headers({});
|
|
927
|
-
const matches = headersMatcher(request) || [];
|
|
928
|
-
|
|
929
|
-
matches.forEach((match) => {
|
|
930
|
-
Object.entries(match).forEach(([name, value]) => {
|
|
931
|
-
newHeaders.append(name, `${value}`);
|
|
932
|
-
});
|
|
933
|
-
});
|
|
934
|
-
|
|
935
|
-
const combinedHeaders = {
|
|
936
|
-
...Object.fromEntries(headers.entries()),
|
|
937
|
-
...Object.fromEntries(newHeaders.entries()),
|
|
938
|
-
};
|
|
939
|
-
|
|
940
|
-
deconstructedResponse.headers = new Headers({});
|
|
941
|
-
Object.entries(combinedHeaders).forEach(([name, value]) => {
|
|
942
|
-
if (value) deconstructedResponse.headers.set(name, value);
|
|
943
|
-
});
|
|
944
|
-
};
|
|
945
|
-
|
|
946
|
-
return async (input, init) => {
|
|
947
|
-
const request = new Request(input, init);
|
|
948
|
-
const deconstructedResponse = generateResponse(request);
|
|
949
|
-
attachHeaders(request, deconstructedResponse);
|
|
950
|
-
|
|
951
|
-
const headers = new Headers();
|
|
952
|
-
|
|
953
|
-
[...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
|
|
954
|
-
if (value) headers.set(name, value);
|
|
955
|
-
});
|
|
956
|
-
|
|
957
|
-
return new Response(deconstructedResponse.body, {
|
|
958
|
-
headers,
|
|
959
|
-
status: deconstructedResponse.status,
|
|
960
|
-
});
|
|
961
|
-
};
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
const invalidAssetsFetch: typeof miniflareFetch = () => {
|
|
965
|
-
throw new Error(
|
|
966
|
-
"Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
|
|
967
|
-
);
|
|
968
|
-
};
|