wrangler 0.0.0-e043479 → 0.0.0-e0a0509
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/README.md +27 -14
- package/bin/wrangler.js +13 -1
- package/miniflare-dist/index.mjs +4886 -0
- package/package.json +38 -25
- package/pages/functions/buildPlugin.ts +92 -0
- package/pages/functions/buildWorker.ts +80 -4
- package/pages/functions/filepath-routing.test.ts +136 -25
- package/pages/functions/filepath-routing.ts +14 -3
- package/pages/functions/routes.ts +6 -1
- package/pages/functions/template-plugin.ts +146 -0
- package/pages/functions/template-worker.ts +21 -8
- package/src/__tests__/config-cache.test.ts +36 -0
- package/src/__tests__/configuration.test.ts +1294 -355
- package/src/__tests__/dev.test.tsx +592 -12
- package/src/__tests__/guess-worker-format.test.ts +37 -18
- package/src/__tests__/helpers/mock-account-id.ts +4 -0
- package/src/__tests__/helpers/mock-cfetch.ts +8 -4
- package/src/__tests__/helpers/mock-console.ts +20 -3
- package/src/__tests__/helpers/mock-dialogs.ts +26 -1
- package/src/__tests__/helpers/mock-http-server.ts +46 -0
- package/src/__tests__/helpers/mock-istty.ts +27 -0
- package/src/__tests__/helpers/mock-kv.ts +9 -16
- package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
- package/src/__tests__/helpers/run-in-tmp.ts +10 -0
- package/src/__tests__/helpers/write-worker-source.ts +31 -0
- package/src/__tests__/https-options.test.ts +130 -0
- package/src/__tests__/index.test.ts +129 -753
- package/src/__tests__/init.test.ts +1516 -0
- package/src/__tests__/jest.setup.ts +13 -5
- package/src/__tests__/kv.test.ts +208 -174
- package/src/__tests__/logger.test.ts +115 -0
- package/src/__tests__/pages.test.ts +327 -0
- package/src/__tests__/parse.test.ts +4 -0
- package/src/__tests__/publish.test.ts +3313 -505
- package/src/__tests__/r2.test.ts +38 -26
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +55 -34
- package/src/__tests__/tail.test.ts +146 -20
- package/src/__tests__/user.test.ts +131 -0
- package/src/__tests__/whoami.test.tsx +26 -7
- package/src/bundle.ts +43 -7
- package/src/cfetch/internal.ts +9 -5
- package/src/cli.ts +5 -11
- package/src/config/README.md +7 -7
- package/src/config/config.ts +69 -105
- package/src/config/environment.ts +93 -4
- package/src/config/index.ts +15 -4
- package/src/config/validation-helpers.ts +228 -23
- package/src/config/validation.ts +559 -154
- package/src/config-cache.ts +45 -0
- package/src/{api/preview.ts → create-worker-preview.ts} +41 -13
- package/src/{api/form_data.ts → create-worker-upload-form.ts} +33 -10
- package/src/dev/dev-vars.ts +36 -0
- package/src/dev/dev.tsx +418 -0
- package/src/dev/local.tsx +312 -0
- package/src/dev/remote.tsx +213 -0
- package/src/dev/use-esbuild.ts +118 -0
- package/src/dialogs.tsx +16 -6
- package/src/entry.ts +222 -12
- package/src/environment-variables.ts +3 -1
- package/src/errors.ts +11 -0
- package/src/https-options.ts +123 -0
- package/src/index.tsx +878 -482
- package/src/inspect.ts +25 -11
- package/src/intl-polyfill.d.ts +139 -0
- package/src/{kv.tsx → kv.ts} +7 -27
- package/src/logger.ts +66 -0
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +41 -0
- package/src/miniflare-cli/request-context.ts +40 -0
- package/src/module-collection.ts +94 -6
- package/src/open-in-browser.ts +18 -5
- package/src/package-manager.ts +9 -8
- package/src/pages.tsx +892 -62
- package/src/parse.ts +4 -2
- package/src/proxy.ts +128 -55
- package/src/publish.ts +305 -199
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +88 -33
- package/src/tail/index.ts +2 -2
- package/src/tail/printing.ts +13 -8
- package/src/update-check.ts +19 -0
- package/src/user.tsx +244 -104
- package/src/whoami.tsx +2 -1
- package/src/{api/worker.ts → worker.ts} +15 -29
- package/templates/gitignore +171 -0
- package/templates/static-asset-facade.js +1 -1
- package/wrangler-dist/cli.js +23568 -50489
- package/src/__tests__/helpers/mock-user.ts +0 -27
- package/src/__tests__/logout.test.ts +0 -50
- package/src/__tests__/sentry.test.ts +0 -146
- package/src/dev.tsx +0 -960
- package/src/guess-worker-format.ts +0 -68
- package/src/reporting.ts +0 -115
- package/wrangler-dist/cli.js.map +0 -7
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
|
|
2
|
+
import { dirname, join } from "path";
|
|
3
|
+
|
|
4
|
+
let cacheMessageShown = false;
|
|
5
|
+
|
|
6
|
+
const cacheFolder = "node_modules/.cache/wrangler";
|
|
7
|
+
|
|
8
|
+
const showCacheMessage = () => {
|
|
9
|
+
if (!cacheMessageShown) {
|
|
10
|
+
console.log(
|
|
11
|
+
`Using cached values in '${cacheFolder}'. This is used as a temporary store to improve the developer experience for some commands. It may be purged at any time. It doesn't contain any sensitive information, but it should not be commited into source control.`
|
|
12
|
+
);
|
|
13
|
+
cacheMessageShown = true;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const getConfigCache = <T>(fileName: string): Partial<T> => {
|
|
18
|
+
try {
|
|
19
|
+
const configCacheLocation = join(cacheFolder, fileName);
|
|
20
|
+
const configCache = JSON.parse(readFileSync(configCacheLocation, "utf-8"));
|
|
21
|
+
showCacheMessage();
|
|
22
|
+
return configCache;
|
|
23
|
+
} catch {
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const saveToConfigCache = <T>(
|
|
29
|
+
fileName: string,
|
|
30
|
+
newValues: Partial<T>
|
|
31
|
+
) => {
|
|
32
|
+
const configCacheLocation = join(cacheFolder, fileName);
|
|
33
|
+
const existingValues = getConfigCache(fileName);
|
|
34
|
+
|
|
35
|
+
mkdirSync(dirname(configCacheLocation), { recursive: true });
|
|
36
|
+
writeFileSync(
|
|
37
|
+
configCacheLocation,
|
|
38
|
+
JSON.stringify({ ...existingValues, ...newValues }, null, 2)
|
|
39
|
+
);
|
|
40
|
+
showCacheMessage();
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export const purgeConfigCaches = () => {
|
|
44
|
+
rmSync(cacheFolder, { recursive: true, force: true });
|
|
45
|
+
};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { URL } from "node:url";
|
|
2
2
|
import { fetch } from "undici";
|
|
3
|
-
import { fetchResult } from "
|
|
4
|
-
import {
|
|
3
|
+
import { fetchResult } from "./cfetch";
|
|
4
|
+
import { createWorkerUploadForm } from "./create-worker-upload-form";
|
|
5
|
+
import { logger } from "./logger";
|
|
5
6
|
import type { CfAccount, CfWorkerContext, CfWorkerInit } from "./worker";
|
|
6
7
|
|
|
7
8
|
/**
|
|
@@ -57,7 +58,8 @@ export interface CfPreviewToken {
|
|
|
57
58
|
*/
|
|
58
59
|
async function sessionToken(
|
|
59
60
|
account: CfAccount,
|
|
60
|
-
ctx: CfWorkerContext
|
|
61
|
+
ctx: CfWorkerContext,
|
|
62
|
+
abortSignal: AbortSignal
|
|
61
63
|
): Promise<CfPreviewToken> {
|
|
62
64
|
const { accountId } = account;
|
|
63
65
|
const initUrl = ctx.zone
|
|
@@ -65,9 +67,9 @@ async function sessionToken(
|
|
|
65
67
|
: `/accounts/${accountId}/workers/subdomain/edge-preview`;
|
|
66
68
|
|
|
67
69
|
const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
|
|
68
|
-
const { inspector_websocket, token } = (await (
|
|
69
|
-
await fetch(exchange_url)
|
|
70
|
-
).json()) as { inspector_websocket: string; token: string };
|
|
70
|
+
const { inspector_websocket, prewarm, token } = (await (
|
|
71
|
+
await fetch(exchange_url, { signal: abortSignal })
|
|
72
|
+
).json()) as { inspector_websocket: string; token: string; prewarm: string };
|
|
71
73
|
const { host } = new URL(inspector_websocket);
|
|
72
74
|
const query = `cf_workers_preview_token=${token}`;
|
|
73
75
|
|
|
@@ -75,9 +77,7 @@ async function sessionToken(
|
|
|
75
77
|
value: token,
|
|
76
78
|
host,
|
|
77
79
|
inspectorUrl: new URL(`${inspector_websocket}?${query}`),
|
|
78
|
-
prewarmUrl: new URL(
|
|
79
|
-
`https://${host}/cdn-cgi/workers/preview/prewarm?${query}`
|
|
80
|
-
),
|
|
80
|
+
prewarmUrl: new URL(prewarm),
|
|
81
81
|
};
|
|
82
82
|
}
|
|
83
83
|
|
|
@@ -93,14 +93,16 @@ function randomId(): string {
|
|
|
93
93
|
/**
|
|
94
94
|
* Creates a preview token.
|
|
95
95
|
*/
|
|
96
|
-
|
|
96
|
+
async function createPreviewToken(
|
|
97
97
|
account: CfAccount,
|
|
98
98
|
worker: CfWorkerInit,
|
|
99
|
-
ctx: CfWorkerContext
|
|
99
|
+
ctx: CfWorkerContext,
|
|
100
|
+
abortSignal: AbortSignal
|
|
100
101
|
): Promise<CfPreviewToken> {
|
|
101
102
|
const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(
|
|
102
103
|
account,
|
|
103
|
-
ctx
|
|
104
|
+
ctx,
|
|
105
|
+
abortSignal
|
|
104
106
|
);
|
|
105
107
|
|
|
106
108
|
const { accountId } = account;
|
|
@@ -114,7 +116,7 @@ export async function previewToken(
|
|
|
114
116
|
? { routes: ["*/*"] } // TODO: should we support routes here? how?
|
|
115
117
|
: { workers_dev: true };
|
|
116
118
|
|
|
117
|
-
const formData =
|
|
119
|
+
const formData = createWorkerUploadForm(worker);
|
|
118
120
|
formData.set("wrangler-session-config", JSON.stringify(mode));
|
|
119
121
|
|
|
120
122
|
const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
|
|
@@ -145,3 +147,29 @@ export async function previewToken(
|
|
|
145
147
|
prewarmUrl,
|
|
146
148
|
};
|
|
147
149
|
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A stub to create a Cloudflare Worker preview.
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* const {value, host} = await createWorker(init, acct);
|
|
156
|
+
*/
|
|
157
|
+
export async function createWorkerPreview(
|
|
158
|
+
init: CfWorkerInit,
|
|
159
|
+
account: CfAccount,
|
|
160
|
+
ctx: CfWorkerContext,
|
|
161
|
+
abortSignal: AbortSignal
|
|
162
|
+
): Promise<CfPreviewToken> {
|
|
163
|
+
const token = await createPreviewToken(account, init, ctx, abortSignal);
|
|
164
|
+
const response = await fetch(token.prewarmUrl.href, {
|
|
165
|
+
method: "POST",
|
|
166
|
+
signal: abortSignal,
|
|
167
|
+
headers: {
|
|
168
|
+
"cf-workers-preview-token": token.value,
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
if (!response.ok) {
|
|
172
|
+
logger.warn("worker failed to prewarm: ", response.statusText);
|
|
173
|
+
}
|
|
174
|
+
return token;
|
|
175
|
+
}
|
|
@@ -26,7 +26,7 @@ export function toMimeType(type: CfModuleType): string {
|
|
|
26
26
|
export interface WorkerMetadata {
|
|
27
27
|
/** The name of the entry point module. Only exists when the worker is in the ES module format */
|
|
28
28
|
main_module?: string;
|
|
29
|
-
/** The name of the entry point module. Only exists when the worker is in the
|
|
29
|
+
/** The name of the entry point module. Only exists when the worker is in the service-worker format */
|
|
30
30
|
body_part?: string;
|
|
31
31
|
compatibility_date?: string;
|
|
32
32
|
compatibility_flags?: string[];
|
|
@@ -38,6 +38,7 @@ export interface WorkerMetadata {
|
|
|
38
38
|
| { type: "json"; name: string; json: unknown }
|
|
39
39
|
| { type: "wasm_module"; name: string; part: string }
|
|
40
40
|
| { type: "text_blob"; name: string; part: string }
|
|
41
|
+
| { type: "data_blob"; name: string; part: string }
|
|
41
42
|
| {
|
|
42
43
|
type: "durable_object_namespace";
|
|
43
44
|
name: string;
|
|
@@ -51,7 +52,7 @@ export interface WorkerMetadata {
|
|
|
51
52
|
/**
|
|
52
53
|
* Creates a `FormData` upload from a `CfWorkerInit`.
|
|
53
54
|
*/
|
|
54
|
-
export function
|
|
55
|
+
export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
|
|
55
56
|
const formData = new FormData();
|
|
56
57
|
const {
|
|
57
58
|
main,
|
|
@@ -133,6 +134,21 @@ export function toFormData(worker: CfWorkerInit): FormData {
|
|
|
133
134
|
}
|
|
134
135
|
}
|
|
135
136
|
|
|
137
|
+
for (const [name, filePath] of Object.entries(bindings.data_blobs || {})) {
|
|
138
|
+
metadataBindings.push({
|
|
139
|
+
name,
|
|
140
|
+
type: "data_blob",
|
|
141
|
+
part: name,
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
formData.set(
|
|
145
|
+
name,
|
|
146
|
+
new File([readFileSync(filePath)], filePath, {
|
|
147
|
+
type: "application/octet-stream",
|
|
148
|
+
})
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
136
152
|
if (main.type === "commonjs") {
|
|
137
153
|
// This is a service-worker format worker.
|
|
138
154
|
for (const module of Object.values([...(modules || [])])) {
|
|
@@ -146,8 +162,12 @@ export function toFormData(worker: CfWorkerInit): FormData {
|
|
|
146
162
|
);
|
|
147
163
|
// And then remove it from the modules collection
|
|
148
164
|
modules = modules?.filter((m) => m !== module);
|
|
149
|
-
} else if (
|
|
150
|
-
|
|
165
|
+
} else if (
|
|
166
|
+
module.type === "compiled-wasm" ||
|
|
167
|
+
module.type === "text" ||
|
|
168
|
+
module.type === "buffer"
|
|
169
|
+
) {
|
|
170
|
+
// Convert all wasm/text/data modules into `wasm_module`/`text_blob`/`data_blob` bindings.
|
|
151
171
|
// The "name" of the module is a file path. We use it
|
|
152
172
|
// to instead be a "part" of the body, and a reference
|
|
153
173
|
// that we can use inside our source. This identifier has to be a valid
|
|
@@ -156,7 +176,12 @@ export function toFormData(worker: CfWorkerInit): FormData {
|
|
|
156
176
|
const name = module.name.replace(/[^a-zA-Z0-9_$]/g, "_");
|
|
157
177
|
metadataBindings.push({
|
|
158
178
|
name,
|
|
159
|
-
type:
|
|
179
|
+
type:
|
|
180
|
+
module.type === "compiled-wasm"
|
|
181
|
+
? "wasm_module"
|
|
182
|
+
: module.type === "text"
|
|
183
|
+
? "text_blob"
|
|
184
|
+
: "data_blob",
|
|
160
185
|
part: name,
|
|
161
186
|
});
|
|
162
187
|
|
|
@@ -167,15 +192,13 @@ export function toFormData(worker: CfWorkerInit): FormData {
|
|
|
167
192
|
type:
|
|
168
193
|
module.type === "compiled-wasm"
|
|
169
194
|
? "application/wasm"
|
|
170
|
-
: "text
|
|
195
|
+
: module.type === "text"
|
|
196
|
+
? "text/plain"
|
|
197
|
+
: "application/octet-stream",
|
|
171
198
|
})
|
|
172
199
|
);
|
|
173
200
|
// And then remove it from the modules collection
|
|
174
201
|
modules = modules?.filter((m) => m !== module);
|
|
175
|
-
} else if (module.type === "buffer") {
|
|
176
|
-
throw new Error(
|
|
177
|
-
'The "buffer" module type is not yet supported in service worker format workers'
|
|
178
|
-
);
|
|
179
202
|
}
|
|
180
203
|
}
|
|
181
204
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import dotenv from "dotenv";
|
|
4
|
+
import { logger } from "../logger";
|
|
5
|
+
import type { Config } from "../config";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Get the Worker `vars` bindings for a `wrangler dev` instance of a Worker.
|
|
9
|
+
*
|
|
10
|
+
* The `vars` bindings can be specified in the `wrangler.toml` configuration file.
|
|
11
|
+
* But "secret" `vars` are usually only provided at the server -
|
|
12
|
+
* either by creating them in the Dashboard UI, or using the `wrangler secret` command.
|
|
13
|
+
*
|
|
14
|
+
* It is useful during development, to provide these types of variable locally.
|
|
15
|
+
* When running `wrangler dev` we will look for a file called `.dev.vars`, situated
|
|
16
|
+
* next to the `wrangler.toml` file (or in the current working directory if there is no
|
|
17
|
+
* `wrangler.toml`).
|
|
18
|
+
*
|
|
19
|
+
* Any values in this file, formatted like a `dotenv` file, will add to or override `vars`
|
|
20
|
+
* bindings provided in the `wrangler.toml`.
|
|
21
|
+
*/
|
|
22
|
+
export function getVarsForDev(config: Config): Config["vars"] {
|
|
23
|
+
const configDir = path.resolve(path.dirname(config.configPath ?? "."));
|
|
24
|
+
const devVarsPath = path.resolve(configDir, ".dev.vars");
|
|
25
|
+
if (fs.existsSync(devVarsPath)) {
|
|
26
|
+
const devVarsRelativePath = path.relative(process.cwd(), devVarsPath);
|
|
27
|
+
logger.log(`Using vars defined in ${devVarsRelativePath}`);
|
|
28
|
+
const devVars = dotenv.parse(fs.readFileSync(devVarsPath, "utf8"));
|
|
29
|
+
return {
|
|
30
|
+
...config.vars,
|
|
31
|
+
...devVars,
|
|
32
|
+
};
|
|
33
|
+
} else {
|
|
34
|
+
return config.vars;
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/dev/dev.tsx
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { watch } from "chokidar";
|
|
3
|
+
import clipboardy from "clipboardy";
|
|
4
|
+
import commandExists from "command-exists";
|
|
5
|
+
import { Box, Text, useApp, useInput, useStdin } from "ink";
|
|
6
|
+
import React, { useState, useEffect, useRef } from "react";
|
|
7
|
+
import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
|
|
8
|
+
import onExit from "signal-exit";
|
|
9
|
+
import tmp from "tmp-promise";
|
|
10
|
+
import { fetch } from "undici";
|
|
11
|
+
import { runCustomBuild } from "../entry";
|
|
12
|
+
import { logger } from "../logger";
|
|
13
|
+
import openInBrowser from "../open-in-browser";
|
|
14
|
+
import { getAPIToken } from "../user";
|
|
15
|
+
import { Local } from "./local";
|
|
16
|
+
import { Remote } from "./remote";
|
|
17
|
+
import { useEsbuild } from "./use-esbuild";
|
|
18
|
+
import type { Config } from "../config";
|
|
19
|
+
import type { Entry } from "../entry";
|
|
20
|
+
import type { AssetPaths } from "../sites";
|
|
21
|
+
import type { CfWorkerInit } from "../worker";
|
|
22
|
+
import type { EsbuildBundle } from "./use-esbuild";
|
|
23
|
+
|
|
24
|
+
export type DevProps = {
|
|
25
|
+
name?: string;
|
|
26
|
+
entry: Entry;
|
|
27
|
+
port: number;
|
|
28
|
+
ip: string;
|
|
29
|
+
inspectorPort: number;
|
|
30
|
+
rules: Config["rules"];
|
|
31
|
+
accountId: string | undefined;
|
|
32
|
+
initialMode: "local" | "remote";
|
|
33
|
+
jsxFactory: string | undefined;
|
|
34
|
+
jsxFragment: string | undefined;
|
|
35
|
+
tsconfig: string | undefined;
|
|
36
|
+
upstreamProtocol: "https" | "http";
|
|
37
|
+
localProtocol: "https" | "http";
|
|
38
|
+
enableLocalPersistence: boolean;
|
|
39
|
+
bindings: CfWorkerInit["bindings"];
|
|
40
|
+
crons: Config["triggers"]["crons"];
|
|
41
|
+
public: string | undefined;
|
|
42
|
+
assetPaths: AssetPaths | undefined;
|
|
43
|
+
compatibilityDate: string;
|
|
44
|
+
compatibilityFlags: string[] | undefined;
|
|
45
|
+
usageModel: "bundled" | "unbound" | undefined;
|
|
46
|
+
minify: boolean | undefined;
|
|
47
|
+
nodeCompat: boolean | undefined;
|
|
48
|
+
build: {
|
|
49
|
+
command?: string | undefined;
|
|
50
|
+
cwd?: string | undefined;
|
|
51
|
+
watch_dir?: string | undefined;
|
|
52
|
+
};
|
|
53
|
+
env: string | undefined;
|
|
54
|
+
legacyEnv: boolean;
|
|
55
|
+
zone:
|
|
56
|
+
| {
|
|
57
|
+
id: string;
|
|
58
|
+
host: string;
|
|
59
|
+
}
|
|
60
|
+
| undefined;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export function DevImplementation(props: DevProps): JSX.Element {
|
|
64
|
+
const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
|
|
65
|
+
const directory = useTmpDir();
|
|
66
|
+
|
|
67
|
+
useCustomBuild(props.entry, props.build);
|
|
68
|
+
|
|
69
|
+
if (props.public && props.entry.format === "service-worker") {
|
|
70
|
+
throw new Error(
|
|
71
|
+
"You cannot use the service-worker format with a `public` directory."
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (props.bindings.wasm_modules && props.entry.format === "modules") {
|
|
76
|
+
throw new Error(
|
|
77
|
+
"You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (props.bindings.text_blobs && props.entry.format === "modules") {
|
|
82
|
+
throw new Error(
|
|
83
|
+
"You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (props.bindings.data_blobs && props.entry.format === "modules") {
|
|
88
|
+
throw new Error(
|
|
89
|
+
"You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const bundle = useEsbuild({
|
|
94
|
+
entry: props.entry,
|
|
95
|
+
destination: directory,
|
|
96
|
+
staticRoot: props.public,
|
|
97
|
+
jsxFactory: props.jsxFactory,
|
|
98
|
+
rules: props.rules,
|
|
99
|
+
jsxFragment: props.jsxFragment,
|
|
100
|
+
serveAssetsFromWorker: !!props.public,
|
|
101
|
+
tsconfig: props.tsconfig,
|
|
102
|
+
minify: props.minify,
|
|
103
|
+
nodeCompat: props.nodeCompat,
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
// only load the UI if we're running in a supported environment
|
|
107
|
+
const { isRawModeSupported } = useStdin();
|
|
108
|
+
return isRawModeSupported ? (
|
|
109
|
+
<InteractiveDevSession {...props} bundle={bundle} apiToken={apiToken} />
|
|
110
|
+
) : (
|
|
111
|
+
<DevSession
|
|
112
|
+
{...props}
|
|
113
|
+
bundle={bundle}
|
|
114
|
+
apiToken={apiToken}
|
|
115
|
+
local={props.initialMode === "local"}
|
|
116
|
+
/>
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
type InteractiveDevSessionProps = DevProps & {
|
|
121
|
+
apiToken: string | undefined;
|
|
122
|
+
bundle: EsbuildBundle | undefined;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
function InteractiveDevSession(props: InteractiveDevSessionProps) {
|
|
126
|
+
const toggles = useHotkeys(
|
|
127
|
+
{
|
|
128
|
+
local: props.initialMode === "local",
|
|
129
|
+
tunnel: false,
|
|
130
|
+
},
|
|
131
|
+
props.port,
|
|
132
|
+
props.ip,
|
|
133
|
+
props.inspectorPort,
|
|
134
|
+
props.localProtocol
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
useTunnel(toggles.tunnel);
|
|
138
|
+
|
|
139
|
+
return (
|
|
140
|
+
<>
|
|
141
|
+
<DevSession {...props} local={toggles.local} />
|
|
142
|
+
<Box borderStyle="round" paddingLeft={1} paddingRight={1}>
|
|
143
|
+
<Text bold={true}>[b]</Text>
|
|
144
|
+
<Text> open a browser, </Text>
|
|
145
|
+
<Text bold={true}>[d]</Text>
|
|
146
|
+
<Text> open Devtools, </Text>
|
|
147
|
+
<Text bold={true}>[l]</Text>
|
|
148
|
+
<Text> {toggles.local ? "turn off" : "turn on"} local mode, </Text>
|
|
149
|
+
<Text bold={true}>[c]</Text>
|
|
150
|
+
<Text> clear console, </Text>
|
|
151
|
+
<Text bold={true}>[x]</Text>
|
|
152
|
+
<Text> to exit</Text>
|
|
153
|
+
</Box>
|
|
154
|
+
</>
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
type DevSessionProps = InteractiveDevSessionProps & { local: boolean };
|
|
159
|
+
|
|
160
|
+
function DevSession(props: DevSessionProps) {
|
|
161
|
+
return props.local ? (
|
|
162
|
+
<Local
|
|
163
|
+
name={props.name}
|
|
164
|
+
bundle={props.bundle}
|
|
165
|
+
format={props.entry.format}
|
|
166
|
+
compatibilityDate={props.compatibilityDate}
|
|
167
|
+
compatibilityFlags={props.compatibilityFlags}
|
|
168
|
+
bindings={props.bindings}
|
|
169
|
+
assetPaths={props.assetPaths}
|
|
170
|
+
public={props.public}
|
|
171
|
+
port={props.port}
|
|
172
|
+
ip={props.ip}
|
|
173
|
+
rules={props.rules}
|
|
174
|
+
inspectorPort={props.inspectorPort}
|
|
175
|
+
enableLocalPersistence={props.enableLocalPersistence}
|
|
176
|
+
crons={props.crons}
|
|
177
|
+
/>
|
|
178
|
+
) : (
|
|
179
|
+
<Remote
|
|
180
|
+
name={props.name}
|
|
181
|
+
bundle={props.bundle}
|
|
182
|
+
format={props.entry.format}
|
|
183
|
+
accountId={props.accountId}
|
|
184
|
+
apiToken={props.apiToken}
|
|
185
|
+
bindings={props.bindings}
|
|
186
|
+
assetPaths={props.assetPaths}
|
|
187
|
+
public={props.public}
|
|
188
|
+
port={props.port}
|
|
189
|
+
ip={props.ip}
|
|
190
|
+
localProtocol={props.localProtocol}
|
|
191
|
+
inspectorPort={props.inspectorPort}
|
|
192
|
+
compatibilityDate={props.compatibilityDate}
|
|
193
|
+
compatibilityFlags={props.compatibilityFlags}
|
|
194
|
+
usageModel={props.usageModel}
|
|
195
|
+
env={props.env}
|
|
196
|
+
legacyEnv={props.legacyEnv}
|
|
197
|
+
zone={props.zone}
|
|
198
|
+
/>
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export interface DirectorySyncResult {
|
|
203
|
+
name: string;
|
|
204
|
+
removeCallback: () => void;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function useTmpDir(): string | undefined {
|
|
208
|
+
const [directory, setDirectory] = useState<DirectorySyncResult>();
|
|
209
|
+
const handleError = useErrorHandler();
|
|
210
|
+
useEffect(() => {
|
|
211
|
+
let dir: DirectorySyncResult | undefined;
|
|
212
|
+
try {
|
|
213
|
+
dir = tmp.dirSync({ unsafeCleanup: true });
|
|
214
|
+
setDirectory(dir);
|
|
215
|
+
return;
|
|
216
|
+
} catch (err) {
|
|
217
|
+
logger.error(
|
|
218
|
+
"Failed to create temporary directory to store built files."
|
|
219
|
+
);
|
|
220
|
+
handleError(err);
|
|
221
|
+
}
|
|
222
|
+
return () => {
|
|
223
|
+
dir?.removeCallback();
|
|
224
|
+
};
|
|
225
|
+
}, [handleError]);
|
|
226
|
+
return directory?.name;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function useCustomBuild(
|
|
230
|
+
expectedEntry: Entry,
|
|
231
|
+
build: {
|
|
232
|
+
command?: string | undefined;
|
|
233
|
+
cwd?: string | undefined;
|
|
234
|
+
watch_dir?: string | undefined;
|
|
235
|
+
}
|
|
236
|
+
): void {
|
|
237
|
+
useEffect(() => {
|
|
238
|
+
if (!build.command) return;
|
|
239
|
+
let watcher: ReturnType<typeof watch> | undefined;
|
|
240
|
+
if (build.watch_dir) {
|
|
241
|
+
watcher = watch(build.watch_dir, {
|
|
242
|
+
persistent: true,
|
|
243
|
+
ignoreInitial: true,
|
|
244
|
+
}).on("all", (_event, filePath) => {
|
|
245
|
+
//TODO: we should buffer requests to the proxy until this completes
|
|
246
|
+
logger.log(`The file ${filePath} changed, restarting build...`);
|
|
247
|
+
runCustomBuild(expectedEntry.file, build).catch((err) => {
|
|
248
|
+
logger.error("Custom build failed:", err);
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return () => {
|
|
254
|
+
watcher?.close();
|
|
255
|
+
};
|
|
256
|
+
}, [build, expectedEntry.file]);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function sleep(period: number) {
|
|
260
|
+
return new Promise((resolve) => setTimeout(resolve, period));
|
|
261
|
+
}
|
|
262
|
+
const SLEEP_DURATION = 2000;
|
|
263
|
+
// really need a first class api for this
|
|
264
|
+
const hostNameRegex = /userHostname="(.*)"/g;
|
|
265
|
+
async function findTunnelHostname() {
|
|
266
|
+
let hostName: string | undefined;
|
|
267
|
+
while (!hostName) {
|
|
268
|
+
try {
|
|
269
|
+
const resp = await fetch("http://localhost:8789/metrics");
|
|
270
|
+
const data = await resp.text();
|
|
271
|
+
const matches = Array.from(data.matchAll(hostNameRegex));
|
|
272
|
+
hostName = matches[0][1];
|
|
273
|
+
} catch (err) {
|
|
274
|
+
await sleep(SLEEP_DURATION);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return hostName;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Create a tunnel to the remote worker.
|
|
282
|
+
* We've disabled this for now until we figure out a better user experience.
|
|
283
|
+
*/
|
|
284
|
+
function useTunnel(toggle: boolean) {
|
|
285
|
+
const tunnel = useRef<ReturnType<typeof spawn>>();
|
|
286
|
+
const removeSignalExitListener = useRef<() => void>();
|
|
287
|
+
// TODO: test if cloudflared is available, if not
|
|
288
|
+
// point them to a url where they can get docs to install it
|
|
289
|
+
useEffect(() => {
|
|
290
|
+
async function startTunnel() {
|
|
291
|
+
if (toggle) {
|
|
292
|
+
try {
|
|
293
|
+
await commandExists("cloudflared");
|
|
294
|
+
} catch (e) {
|
|
295
|
+
logger.warn(
|
|
296
|
+
"To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
|
|
297
|
+
);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
logger.log("⎔ Starting a tunnel...");
|
|
301
|
+
tunnel.current = spawn("cloudflared", [
|
|
302
|
+
"tunnel",
|
|
303
|
+
"--url",
|
|
304
|
+
"http://localhost:8787",
|
|
305
|
+
"--metrics",
|
|
306
|
+
"localhost:8789",
|
|
307
|
+
]);
|
|
308
|
+
|
|
309
|
+
tunnel.current.on("close", (code) => {
|
|
310
|
+
if (code) {
|
|
311
|
+
logger.log(`Tunnel process exited with code ${code}`);
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
removeSignalExitListener.current = onExit((_code, _signal) => {
|
|
316
|
+
logger.log("⎔ Shutting down local tunnel.");
|
|
317
|
+
tunnel.current?.kill();
|
|
318
|
+
tunnel.current = undefined;
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
const hostName = await findTunnelHostname();
|
|
322
|
+
await clipboardy.write(hostName);
|
|
323
|
+
logger.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
startTunnel().catch(async (err) => {
|
|
328
|
+
logger.error("tunnel:", err);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
return () => {
|
|
332
|
+
if (tunnel.current) {
|
|
333
|
+
logger.log("⎔ Shutting down tunnel.");
|
|
334
|
+
tunnel.current?.kill();
|
|
335
|
+
tunnel.current = undefined;
|
|
336
|
+
removeSignalExitListener.current && removeSignalExitListener.current();
|
|
337
|
+
removeSignalExitListener.current = undefined;
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}, [toggle]);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
type useHotkeysInitialState = {
|
|
344
|
+
local: boolean;
|
|
345
|
+
tunnel: boolean;
|
|
346
|
+
};
|
|
347
|
+
function useHotkeys(
|
|
348
|
+
initial: useHotkeysInitialState,
|
|
349
|
+
port: number,
|
|
350
|
+
ip: string,
|
|
351
|
+
inspectorPort: number,
|
|
352
|
+
localProtocol: "http" | "https"
|
|
353
|
+
) {
|
|
354
|
+
// UGH, we should put port in context instead
|
|
355
|
+
const [toggles, setToggles] = useState(initial);
|
|
356
|
+
const { exit } = useApp();
|
|
357
|
+
useInput(
|
|
358
|
+
async (
|
|
359
|
+
input,
|
|
360
|
+
// eslint-disable-next-line unused-imports/no-unused-vars
|
|
361
|
+
key
|
|
362
|
+
) => {
|
|
363
|
+
switch (input.toLowerCase()) {
|
|
364
|
+
// clear console
|
|
365
|
+
case "c":
|
|
366
|
+
console.clear();
|
|
367
|
+
// This console.log causes Ink to re-render the `DevSession` component.
|
|
368
|
+
// Couldn't find a better way to tell it to do so...
|
|
369
|
+
console.log();
|
|
370
|
+
break;
|
|
371
|
+
// open browser
|
|
372
|
+
case "b": {
|
|
373
|
+
await openInBrowser(`${localProtocol}://${ip}:${port}`);
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
// toggle inspector
|
|
377
|
+
case "d": {
|
|
378
|
+
await openInBrowser(
|
|
379
|
+
`https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`,
|
|
380
|
+
{ forceChromium: true }
|
|
381
|
+
);
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
// toggle local
|
|
385
|
+
case "l":
|
|
386
|
+
setToggles((previousToggles) => ({
|
|
387
|
+
...previousToggles,
|
|
388
|
+
local: !previousToggles.local,
|
|
389
|
+
}));
|
|
390
|
+
break;
|
|
391
|
+
// shut down
|
|
392
|
+
case "q":
|
|
393
|
+
case "x":
|
|
394
|
+
exit();
|
|
395
|
+
break;
|
|
396
|
+
default:
|
|
397
|
+
// nothing?
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
);
|
|
402
|
+
return toggles;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function ErrorFallback(props: { error: Error }) {
|
|
406
|
+
const { exit } = useApp();
|
|
407
|
+
useEffect(() => exit(props.error));
|
|
408
|
+
return (
|
|
409
|
+
<>
|
|
410
|
+
<Text>Something went wrong:</Text>
|
|
411
|
+
<Text>{props.error.stack}</Text>
|
|
412
|
+
</>
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
export default withErrorBoundary(DevImplementation, {
|
|
417
|
+
FallbackComponent: ErrorFallback,
|
|
418
|
+
});
|