wrangler 0.0.0-fb0eae7 → 0.0.0-fb43821

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 CHANGED
@@ -1,13 +1,13 @@
1
1
  import type { BuilderCallback } from "yargs";
2
2
  import { join } from "path";
3
3
  import { tmpdir } from "os";
4
- import { existsSync } from "fs";
5
- import type { ChildProcess } from "child_process";
4
+ import { existsSync, lstatSync, readFileSync } from "fs";
6
5
  import { execSync, spawn } from "child_process";
7
- import express from "express";
6
+ import { Headers, Request, Response } from "undici";
8
7
  import type { MiniflareOptions } from "miniflare";
9
- import type { RequestInfo, RequestInit } from "@miniflare/core";
10
- import httpProxyMiddleware from "http-proxy-middleware";
8
+ import type { RequestInfo, RequestInit } from "undici";
9
+ import open from "open";
10
+ import { watch } from "chokidar";
11
11
 
12
12
  type Exit = (message?: string) => undefined;
13
13
 
@@ -73,41 +73,35 @@ const getPort = (pid: number) => {
73
73
  };
74
74
 
75
75
  const spawnProxyProcess = async ({
76
- directory,
77
76
  port,
78
- remaining,
77
+ command,
79
78
  }: {
80
- directory?: string;
81
79
  port?: number;
82
- remaining: (string | number)[];
80
+ command: (string | number)[];
83
81
  }) => {
84
- let proxy: ChildProcess;
85
-
86
82
  const exit: Exit = (message) => {
87
83
  if (message) console.error(message);
88
84
  if (proxy) proxy.kill();
89
85
  return undefined;
90
86
  };
91
87
 
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() }
88
+ if (command.length === 0)
89
+ return exit(
90
+ "Must specify a directory of static assets to serve or a command to run."
109
91
  );
110
- }
92
+
93
+ console.log(`Running ${command.join(" ")}...`);
94
+ const proxy = spawn(
95
+ command[0].toString(),
96
+ command.slice(1).map((value) => value.toString()),
97
+ {
98
+ shell: isWindows(),
99
+ env: {
100
+ BROWSER: "none",
101
+ ...process.env,
102
+ },
103
+ }
104
+ );
111
105
 
112
106
  proxy.stdout.on("data", (data) => {
113
107
  console.log(`[proxy]: ${data}`);
@@ -137,14 +131,463 @@ const spawnProxyProcess = async ({
137
131
 
138
132
  if (port === undefined) {
139
133
  return exit(
140
- "Could not automatically determin proxy port. Please specify the proxy port with --proxy."
134
+ "Could not automatically determine proxy port. Please specify the proxy port with --proxy."
141
135
  );
142
136
  } else {
143
137
  console.log(`Automatically determined the proxy port to be ${port}.`);
144
138
  }
145
139
  }
146
140
 
147
- return { proxy, port, exit };
141
+ return { port, exit };
142
+ };
143
+
144
+ const escapeRegex = (str: string) => {
145
+ return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
146
+ };
147
+
148
+ export type Replacements = Record<string, string>;
149
+
150
+ export const replacer = (str: string, replacements: Replacements) => {
151
+ for (const [replacement, value] of Object.entries(replacements)) {
152
+ str = str.replace(`:${replacement}`, value);
153
+ }
154
+ return str;
155
+ };
156
+
157
+ export const generateRulesMatcher = <T,>(
158
+ rules?: Record<string, T>,
159
+ replacer: (match: T, replacements: Replacements) => T = (match) => match
160
+ ) => {
161
+ // TODO: How can you test cross-host rules?
162
+ if (!rules) return () => [];
163
+
164
+ const compiledRules = Object.entries(rules)
165
+ .map(([rule, match]) => {
166
+ const crossHost = rule.startsWith("https://");
167
+
168
+ rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
169
+
170
+ const host_matches = rule.matchAll(
171
+ /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
172
+ );
173
+ for (const match of host_matches) {
174
+ rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
175
+ }
176
+
177
+ const path_matches = rule.matchAll(/:(\w+)/g);
178
+ for (const match of path_matches) {
179
+ rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
180
+ }
181
+
182
+ rule = "^" + rule + "$";
183
+
184
+ try {
185
+ const regExp = new RegExp(rule);
186
+ return [{ crossHost, regExp }, match];
187
+ } catch {}
188
+ })
189
+ .filter((value) => value !== undefined) as [
190
+ { crossHost: boolean; regExp: RegExp },
191
+ T
192
+ ][];
193
+
194
+ return ({ request }: { request: Request }) => {
195
+ const { pathname, host } = new URL(request.url);
196
+
197
+ return compiledRules
198
+ .map(([{ crossHost, regExp }, match]) => {
199
+ const test = crossHost ? `https://${host}${pathname}` : pathname;
200
+ const result = regExp.exec(test);
201
+ if (result) {
202
+ return replacer(match, result.groups || {});
203
+ }
204
+ })
205
+ .filter((value) => value !== undefined) as T[];
206
+ };
207
+ };
208
+
209
+ const generateHeadersMatcher = (headersFile: string) => {
210
+ if (existsSync(headersFile)) {
211
+ const contents = readFileSync(headersFile).toString();
212
+
213
+ // TODO: Log errors
214
+ const lines = contents
215
+ .split("\n")
216
+ .map((line) => line.trim())
217
+ .filter((line) => !line.startsWith("#") && line !== "");
218
+
219
+ const rules: Record<string, Record<string, string>> = {};
220
+ let rule: { path: string; headers: Record<string, string> } | undefined =
221
+ undefined;
222
+
223
+ for (const line of lines) {
224
+ if (/^([^\s]+:\/\/|^\/)/.test(line)) {
225
+ if (rule && Object.keys(rule.headers).length > 0) {
226
+ rules[rule.path] = rule.headers;
227
+ }
228
+
229
+ const path = validateURL(line);
230
+ if (path) {
231
+ rule = {
232
+ path,
233
+ headers: {},
234
+ };
235
+ continue;
236
+ }
237
+ }
238
+
239
+ if (!line.includes(":")) continue;
240
+
241
+ const [rawName, ...rawValue] = line.split(":");
242
+ const name = rawName.trim().toLowerCase();
243
+ const value = rawValue.join(":").trim();
244
+
245
+ if (name === "") continue;
246
+ if (!rule) continue;
247
+
248
+ const existingValues = rule.headers[name];
249
+ rule.headers[name] = existingValues
250
+ ? `${existingValues}, ${value}`
251
+ : value;
252
+ }
253
+
254
+ if (rule && Object.keys(rule.headers).length > 0) {
255
+ rules[rule.path] = rule.headers;
256
+ }
257
+
258
+ const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
259
+ Object.fromEntries(
260
+ Object.entries(match).map(([name, value]) => [
261
+ name,
262
+ replacer(value, replacements),
263
+ ])
264
+ )
265
+ );
266
+
267
+ return (request: Request) => {
268
+ const matches = rulesMatcher({
269
+ request,
270
+ });
271
+ if (matches) return matches;
272
+ };
273
+ } else {
274
+ return () => undefined;
275
+ }
276
+ };
277
+
278
+ const generateRedirectsMatcher = (redirectsFile: string) => {
279
+ if (existsSync(redirectsFile)) {
280
+ const contents = readFileSync(redirectsFile).toString();
281
+
282
+ // TODO: Log errors
283
+ const lines = contents
284
+ .split("\n")
285
+ .map((line) => line.trim())
286
+ .filter((line) => !line.startsWith("#") && line !== "");
287
+
288
+ const rules = Object.fromEntries(
289
+ lines
290
+ .map((line) => line.split(" "))
291
+ .filter((tokens) => tokens.length === 2 || tokens.length === 3)
292
+ .map((tokens) => {
293
+ const from = validateURL(tokens[0], true, false, false);
294
+ const to = validateURL(tokens[1], false, true, true);
295
+ let status: number | undefined = parseInt(tokens[2]) || 302;
296
+ status = [301, 302, 303, 307, 308].includes(status)
297
+ ? status
298
+ : undefined;
299
+
300
+ return from && to && status ? [from, { to, status }] : undefined;
301
+ })
302
+ .filter((rule) => rule !== undefined) as [
303
+ string,
304
+ { to: string; status?: number }
305
+ ][]
306
+ );
307
+
308
+ const rulesMatcher = generateRulesMatcher(
309
+ rules,
310
+ ({ status, to }, replacements) => ({
311
+ status,
312
+ to: replacer(to, replacements),
313
+ })
314
+ );
315
+
316
+ return (request: Request) => {
317
+ const match = rulesMatcher({
318
+ request,
319
+ })[0];
320
+ if (match) return match;
321
+ };
322
+ } else {
323
+ return () => undefined;
324
+ }
325
+ };
326
+
327
+ const extractPathname = (
328
+ path = "/",
329
+ includeSearch: boolean,
330
+ includeHash: boolean
331
+ ) => {
332
+ if (!path.startsWith("/")) path = `/${path}`;
333
+ const url = new URL(`//${path}`, "relative://");
334
+ return `${url.pathname}${includeSearch ? url.search : ""}${
335
+ includeHash ? url.hash : ""
336
+ }`;
337
+ };
338
+
339
+ const validateURL = (
340
+ token: string,
341
+ onlyRelative = false,
342
+ includeSearch = false,
343
+ includeHash = false
344
+ ) => {
345
+ const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
346
+ if (host && host.groups && host.groups.host) {
347
+ if (onlyRelative) return;
348
+
349
+ return `https://${host.groups.host}${extractPathname(
350
+ host.groups.path,
351
+ includeSearch,
352
+ includeHash
353
+ )}`;
354
+ } else {
355
+ if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
356
+
357
+ const path = /^\//.exec(token);
358
+ if (path) {
359
+ try {
360
+ return extractPathname(token, includeSearch, includeHash);
361
+ } catch {}
362
+ }
363
+ }
364
+ return "";
365
+ };
366
+
367
+ const hasFileExtension = (pathname: string) =>
368
+ /\/.+\.[a-z0-9]+$/i.test(pathname);
369
+
370
+ const generateAssetsFetch = async (
371
+ directory: string
372
+ ): Promise<typeof fetch> => {
373
+ const headersFile = join(directory, "_headers");
374
+ const redirectsFile = join(directory, "_redirects");
375
+ const workerFile = join(directory, "_worker.js");
376
+
377
+ const ignoredFiles = [headersFile, redirectsFile, workerFile];
378
+
379
+ const assetExists = (path: string) => {
380
+ path = join(directory, path);
381
+ return (
382
+ existsSync(path) &&
383
+ lstatSync(path).isFile() &&
384
+ !ignoredFiles.includes(path)
385
+ );
386
+ };
387
+
388
+ const getAsset = (path: string) => {
389
+ if (assetExists(path)) {
390
+ return join(directory, path);
391
+ }
392
+ };
393
+
394
+ let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
395
+ let headersMatcher = generateHeadersMatcher(headersFile);
396
+
397
+ watch([headersFile, redirectsFile], {
398
+ persistent: true,
399
+ }).on("change", (path) => {
400
+ switch (path) {
401
+ case headersFile: {
402
+ console.log("_headers modified. Re-evaluating...");
403
+ headersMatcher = generateHeadersMatcher(headersFile);
404
+ break;
405
+ }
406
+ case redirectsFile: {
407
+ console.log("_redirects modified. Re-evaluating...");
408
+ redirectsMatcher = generateRedirectsMatcher(redirectsFile);
409
+ break;
410
+ }
411
+ }
412
+ });
413
+
414
+ const serveAsset = (file: string) => {
415
+ return readFileSync(file);
416
+ };
417
+
418
+ const generateResponse = (request: Request) => {
419
+ const url = new URL(request.url);
420
+
421
+ const deconstructedResponse: {
422
+ status: number;
423
+ headers: Headers;
424
+ body?: Buffer;
425
+ } = {
426
+ status: 200,
427
+ headers: new Headers(),
428
+ body: undefined,
429
+ };
430
+
431
+ const match = redirectsMatcher(request);
432
+ if (match) {
433
+ const { status, to } = match;
434
+
435
+ let location = to;
436
+ let search;
437
+
438
+ if (to.startsWith("/")) {
439
+ search = new URL(location, "http://fakehost").search;
440
+ } else {
441
+ search = new URL(location).search;
442
+ }
443
+
444
+ location = `${location}${search ? "" : url.search}`;
445
+
446
+ if (status && [301, 302, 303, 307, 308].includes(status)) {
447
+ deconstructedResponse.status = status;
448
+ } else {
449
+ deconstructedResponse.status = 302;
450
+ }
451
+
452
+ deconstructedResponse.headers.set("Location", location);
453
+ return deconstructedResponse;
454
+ }
455
+
456
+ if (!request.method?.match(/^(get|head)$/i)) {
457
+ deconstructedResponse.status = 405;
458
+ return deconstructedResponse;
459
+ }
460
+
461
+ const notFound = () => {
462
+ let cwd = url.pathname;
463
+ while (cwd) {
464
+ cwd = cwd.slice(0, cwd.lastIndexOf("/"));
465
+
466
+ if ((asset = getAsset(`${cwd}/404.html`))) {
467
+ deconstructedResponse.status = 404;
468
+ deconstructedResponse.body = serveAsset(asset);
469
+ return deconstructedResponse;
470
+ }
471
+ }
472
+
473
+ if ((asset = getAsset(`/index.html`))) {
474
+ deconstructedResponse.body = serveAsset(asset);
475
+ return deconstructedResponse;
476
+ }
477
+
478
+ deconstructedResponse.status = 404;
479
+ return deconstructedResponse;
480
+ };
481
+
482
+ let asset;
483
+
484
+ if (url.pathname.endsWith("/")) {
485
+ if ((asset = getAsset(`${url.pathname}/index.html`))) {
486
+ deconstructedResponse.body = serveAsset(asset);
487
+ return deconstructedResponse;
488
+ } else if (
489
+ (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
490
+ ) {
491
+ deconstructedResponse.status = 301;
492
+ deconstructedResponse.headers.set(
493
+ "Location",
494
+ `${url.pathname.slice(0, -1)}${url.search}`
495
+ );
496
+ return deconstructedResponse;
497
+ }
498
+ }
499
+
500
+ if (url.pathname.endsWith("/index")) {
501
+ deconstructedResponse.status = 301;
502
+ deconstructedResponse.headers.set(
503
+ "Location",
504
+ `${url.pathname.slice(0, -"index".length)}${url.search}`
505
+ );
506
+ return deconstructedResponse;
507
+ }
508
+
509
+ if ((asset = getAsset(url.pathname))) {
510
+ if (url.pathname.endsWith(".html")) {
511
+ const extensionlessPath = url.pathname.slice(0, -".html".length);
512
+ if (getAsset(extensionlessPath) || extensionlessPath === "/") {
513
+ deconstructedResponse.body = serveAsset(asset);
514
+ return deconstructedResponse;
515
+ } else {
516
+ deconstructedResponse.status = 301;
517
+ deconstructedResponse.headers.set(
518
+ "Location",
519
+ `${extensionlessPath}${url.search}`
520
+ );
521
+ return deconstructedResponse;
522
+ }
523
+ } else {
524
+ deconstructedResponse.body = serveAsset(asset);
525
+ return deconstructedResponse;
526
+ }
527
+ } else if (hasFileExtension(url.pathname)) {
528
+ notFound();
529
+ return deconstructedResponse;
530
+ }
531
+
532
+ if ((asset = getAsset(`${url.pathname}.html`))) {
533
+ deconstructedResponse.body = serveAsset(asset);
534
+ return deconstructedResponse;
535
+ }
536
+
537
+ if ((asset = getAsset(`${url.pathname}/index.html`))) {
538
+ deconstructedResponse.status = 301;
539
+ deconstructedResponse.headers.set(
540
+ "Location",
541
+ `${url.pathname}/${url.search}`
542
+ );
543
+ return deconstructedResponse;
544
+ } else {
545
+ notFound();
546
+ return deconstructedResponse;
547
+ }
548
+ };
549
+
550
+ const attachHeaders = (
551
+ request: Request,
552
+ deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
553
+ ) => {
554
+ const headers = deconstructedResponse.headers;
555
+ const newHeaders = new Headers({});
556
+ const matches = headersMatcher(request) || [];
557
+
558
+ matches.forEach((match) => {
559
+ Object.entries(match).forEach(([name, value]) => {
560
+ newHeaders.append(name, `${value}`);
561
+ });
562
+ });
563
+
564
+ const combinedHeaders = {
565
+ ...Object.fromEntries(headers.entries()),
566
+ ...Object.fromEntries(newHeaders.entries()),
567
+ };
568
+
569
+ deconstructedResponse.headers = new Headers({});
570
+ Object.entries(combinedHeaders).forEach(([name, value]) => {
571
+ if (value) deconstructedResponse.headers.set(name, value);
572
+ });
573
+ };
574
+
575
+ return (async (input, init) => {
576
+ const request = new Request(input, init);
577
+ const deconstructedResponse = generateResponse(request);
578
+ attachHeaders(request, deconstructedResponse);
579
+
580
+ const headers = new Headers();
581
+
582
+ [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
583
+ if (value) headers.set(name, value);
584
+ });
585
+
586
+ return new Response(deconstructedResponse.body, {
587
+ headers,
588
+ status: deconstructedResponse.status,
589
+ });
590
+ }) as any;
148
591
  };
149
592
 
150
593
  export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
@@ -222,14 +665,27 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
222
665
  const functionsDirectory = "./functions";
223
666
  const usingFunctions = existsSync(functionsDirectory);
224
667
 
225
- const proxy = await spawnProxyProcess({
226
- directory,
227
- port: requestedProxyPort,
228
- remaining: remaining as (string | number)[],
229
- });
230
- if (proxy === undefined) return undefined;
668
+ const command = remaining as (string | number)[];
231
669
 
232
- const { port: proxyPort, exit } = proxy;
670
+ let proxyPort: number | undefined;
671
+ let exit: Exit = (message) => {
672
+ console.error(message);
673
+ return undefined;
674
+ };
675
+
676
+ if (directory === undefined) {
677
+ const proxy = await spawnProxyProcess({
678
+ port: requestedProxyPort,
679
+ command,
680
+ });
681
+ if (proxy === undefined) return undefined;
682
+
683
+ exit = proxy.exit;
684
+ proxyPort = proxy.port;
685
+
686
+ process.on("SIGINT", () => exit());
687
+ process.on("SIGTERM", () => exit());
688
+ }
233
689
 
234
690
  let miniflareArgs: MiniflareOptions = {};
235
691
 
@@ -257,12 +713,25 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
257
713
  };
258
714
  }
259
715
 
260
- const { Miniflare } = await import("miniflare");
261
- const { Request, Response, fetch } = await import("@miniflare/core");
716
+ const { Miniflare, Log, LogLevel } = await import("miniflare");
717
+ const { fetch } = await import("@miniflare/core");
718
+
719
+ class MiniflareLogger extends Log {
720
+ log(message: string) {
721
+ message = message.replace("[mf:", "[pages:");
722
+ console.log(message);
723
+ }
724
+ }
725
+
262
726
  const miniflare = new Miniflare({
727
+ port,
263
728
  watch: true,
264
729
  modules: true,
265
730
 
731
+ log: new MiniflareLogger(LogLevel.ERROR),
732
+ logUnhandledRejections: true,
733
+ sourceMap: true,
734
+
266
735
  kvNamespaces: kvs.map((kv) => kv.toString()),
267
736
 
268
737
  durableObjects: Object.fromEntries(
@@ -283,20 +752,36 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
283
752
  input: RequestInfo,
284
753
  init?: RequestInit | undefined
285
754
  ) => {
286
- try {
287
- let request = new Request(input, init);
288
- const url = new URL(request.url);
289
- url.host = `127.0.0.1:${proxyPort}`;
290
- request = new Request(url.toString(), request);
291
- return await fetch(request);
292
- } catch (thrown) {
293
- console.error(`Could not proxy request: ${thrown}`);
294
-
295
- // TODO: Pretty error page
296
- return new Response(
297
- `[wrangler] Could not proxy request: ${thrown}`,
298
- { status: 502 }
299
- );
755
+ if (proxyPort) {
756
+ try {
757
+ let request = new Request(input, init);
758
+ const url = new URL(request.url);
759
+ url.host = `127.0.0.1:${proxyPort}`;
760
+ request = new Request(url.toString(), request);
761
+ return await fetch(request.url, request);
762
+ } catch (thrown) {
763
+ console.error(`Could not proxy request: ${thrown}`);
764
+
765
+ // TODO: Pretty error page
766
+ return new Response(
767
+ `[wrangler] Could not proxy request: ${thrown}`,
768
+ { status: 502 }
769
+ );
770
+ }
771
+ } else {
772
+ try {
773
+ return await (
774
+ await generateAssetsFetch(directory)
775
+ )(input as any, init as any);
776
+ } catch (thrown) {
777
+ console.error(`Could not serve static asset: ${thrown}`);
778
+
779
+ // TODO: Pretty error page
780
+ return new Response(
781
+ `[wrangler] Could not serve static asset: ${thrown}`,
782
+ { status: 502 }
783
+ );
784
+ }
300
785
  }
301
786
  },
302
787
  },
@@ -308,35 +793,24 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
308
793
 
309
794
  ...miniflareArgs,
310
795
  });
311
- const miniflareServer = await miniflare.createServer();
312
796
 
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
-
320
- const miniflarePort = address.port;
321
-
322
- const app = express();
323
-
324
- app.use(
325
- "/",
326
- httpProxyMiddleware.createProxyMiddleware({
327
- target: `http://127.0.0.1:${miniflarePort}`,
328
- })
329
- );
797
+ const server = await miniflare.startServer();
798
+ console.log(`Serving at http://127.0.0.1:${port}/`);
330
799
 
331
- app.use(
332
- "/",
333
- httpProxyMiddleware.createProxyMiddleware({
334
- target: `http://127.0.0.1:${proxyPort}`,
335
- })
336
- );
800
+ if (process.env.BROWSER !== "none") {
801
+ await open(`http://127.0.0.1:${port}/`);
802
+ }
337
803
 
338
- app.listen(port, () => {
339
- console.log(`Serving at http://127.0.0.1:${port}/`);
804
+ process.on("SIGINT", () => {
805
+ server.close();
806
+ miniflare.dispose().catch((err) => {
807
+ console.error(err);
808
+ });
809
+ });
810
+ process.on("SIGTERM", () => {
811
+ server.close();
812
+ miniflare.dispose().catch((err) => {
813
+ console.error(err);
340
814
  });
341
815
  });
342
816
  }