wrangler 0.0.0-dfa31a7 → 0.0.0-e14e589

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.
Files changed (41) hide show
  1. package/bin/wrangler.js +36 -2
  2. package/import_meta_url.js +3 -0
  3. package/package.json +50 -18
  4. package/src/__tests__/clipboardy-mock.js +4 -0
  5. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  6. package/src/__tests__/index.test.ts +153 -0
  7. package/src/__tests__/mock-cfetch.js +46 -0
  8. package/src/api/form_data.ts +125 -0
  9. package/src/api/inspect.ts +441 -0
  10. package/src/api/preview.ts +123 -0
  11. package/src/api/worker.ts +140 -0
  12. package/src/cfetch.ts +72 -0
  13. package/src/cli.ts +10 -0
  14. package/src/config.ts +96 -0
  15. package/src/dev.tsx +670 -0
  16. package/src/dialogs.tsx +85 -0
  17. package/src/index.tsx +1754 -0
  18. package/src/kv.tsx +211 -0
  19. package/src/pages.tsx +340 -0
  20. package/src/publish.ts +278 -0
  21. package/src/sites.tsx +115 -0
  22. package/src/tail.tsx +71 -0
  23. package/src/user.tsx +1029 -0
  24. package/src/util/fetch.ts +74 -0
  25. package/{facade.js → static-asset-facade.js} +2 -7
  26. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +262 -192
  27. package/vendor/@cloudflare/kv-asset-handler/package.json +1 -1
  28. package/vendor/{mime → wrangler-mime}/CHANGELOG.md +0 -0
  29. package/vendor/{mime → wrangler-mime}/LICENSE +0 -0
  30. package/vendor/{mime → wrangler-mime}/Mime.js +0 -0
  31. package/vendor/{mime → wrangler-mime}/README.md +0 -0
  32. package/vendor/{mime → wrangler-mime}/cli.js +0 -0
  33. package/vendor/{mime → wrangler-mime}/index.js +0 -0
  34. package/vendor/{mime → wrangler-mime}/lite.js +0 -0
  35. package/vendor/{mime → wrangler-mime}/package.json +1 -1
  36. package/vendor/{mime → wrangler-mime}/types/other.js +0 -0
  37. package/vendor/{mime → wrangler-mime}/types/standard.js +0 -0
  38. package/wrangler-dist/cli.js +841 -0
  39. package/wrangler-dist/cli.js.map +7 -0
  40. package/wrangler-dist/index_node.js +0 -95243
  41. package/wrangler-dist/index_node.js.map +0 -7
package/bin/wrangler.js CHANGED
@@ -1,2 +1,36 @@
1
- #!/usr/bin/env node --no-warnings
2
- require("../wrangler-dist/index_node.js");
1
+ #!/usr/bin/env node
2
+ const { spawn } = require("child_process");
3
+ const { join } = require("path");
4
+ const semiver = require("semiver");
5
+
6
+ const MIN_NODE_VERSION = "16.7.0";
7
+
8
+ async function main() {
9
+ if (semiver(process.versions.node, MIN_NODE_VERSION) < 0) {
10
+ // Note Volta and nvm are also recommended in the official docs:
11
+ // https://developers.cloudflare.com/workers/get-started/guide#2-install-the-workers-cli
12
+ console.error(
13
+ `Wrangler requires at least Node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}.
14
+ You should use the latest Node.js version if possible, as Cloudflare Workers use a very up-to-date version of V8.
15
+ Consider using a Node.js version manager such as https://volta.sh/ or https://github.com/nvm-sh/nvm.`
16
+ );
17
+ process.exitCode = 1;
18
+ return;
19
+ }
20
+
21
+ spawn(
22
+ process.execPath,
23
+ [
24
+ "--no-warnings",
25
+ "--experimental-vm-modules",
26
+ ...process.execArgv,
27
+ join(__dirname, "../wrangler-dist/cli.js"),
28
+ ...process.argv.slice(2),
29
+ ],
30
+ { stdio: "inherit" }
31
+ ).on("exit", (code) =>
32
+ process.exit(code === undefined || code === null ? 0 : code)
33
+ );
34
+ }
35
+
36
+ void main();
@@ -0,0 +1,3 @@
1
+ // as per https://github.com/evanw/esbuild/issues/1492
2
+ // to make some libs work
3
+ export const import_meta_url = require("url").pathToFileURL(__filename);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-dfa31a7",
3
+ "version": "0.0.0-e14e589",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
6
  "bin": "./bin/wrangler.js",
@@ -33,9 +33,11 @@
33
33
  "cli"
34
34
  ],
35
35
  "dependencies": {
36
- "esbuild": "^0.12.19",
37
- "miniflare": "^1.3.3",
38
- "yargs": "^17.1.1"
36
+ "@cloudflare/pages-functions-compiler": "0.3.4",
37
+ "esbuild": "0.13.12",
38
+ "miniflare": "2.0.0-rc.2",
39
+ "semiver": "^1.1.0",
40
+ "serve": "^13.0.2"
39
41
  },
40
42
  "optionalDependencies": {
41
43
  "fsevents": "~2.3.2"
@@ -43,38 +45,68 @@
43
45
  "devDependencies": {
44
46
  "@iarna/toml": "^2.2.5",
45
47
  "@types/cloudflare": "^2.7.6",
46
- "@types/react": "^17.0.19",
48
+ "@types/express": "^4.17.13",
49
+ "@types/react": "^17.0.34",
47
50
  "@types/signal-exit": "^3.0.1",
48
- "@types/ws": "^7.4.7",
49
- "@types/yargs": "^17.0.2",
50
- "clipboardy": "^2.3.0",
51
- "cloudflare": "^2.9.1",
52
- "find-up": "^6.0.0",
53
- "formdata-node": "^3.6.3",
51
+ "@types/ws": "^8.2.0",
52
+ "@types/yargs": "^17.0.5",
53
+ "clipboardy": "^3.0.0",
54
+ "command-exists": "^1.2.9",
55
+ "execa": "^5.1.1",
56
+ "express": "^4.17.1",
57
+ "finalhandler": "^1.1.2",
58
+ "find-up": "^6.2.0",
59
+ "formdata-node": "^4.3.1",
54
60
  "http-proxy": "^1.18.1",
61
+ "http-proxy-middleware": "^2.0.1",
55
62
  "ink": "^3.2.0",
63
+ "ink-select-input": "^4.2.0",
56
64
  "ink-table": "^3.0.0",
57
- "node-fetch": "github:tekwiz/node-fetch#fix/redirect-with-empty-chunked-transfer-encoding",
58
- "open": "^8.2.1",
65
+ "ink-text-input": "^4.0.1",
66
+ "node-fetch": "^3.1.0",
67
+ "open": "^8.4.0",
68
+ "path-to-regexp": "^6.2.0",
59
69
  "react": "^17.0.2",
70
+ "serve-static": "^1.14.1",
60
71
  "signal-exit": "^3.0.5",
61
- "tmp-promise": "^3.0.2",
62
- "ws": "^8.2.0"
72
+ "tmp-promise": "^3.0.3",
73
+ "ws": "^8.2.3",
74
+ "yargs": "^17.2.1"
63
75
  },
64
76
  "files": [
77
+ "src",
65
78
  "bin",
66
79
  "miniflare-config-stubs",
67
80
  "wrangler-dist",
68
- "facade.js",
69
- "vendor"
81
+ "static-asset-facade.js",
82
+ "vendor",
83
+ "import_meta_url.js"
70
84
  ],
71
85
  "scripts": {
72
86
  "clean": "rm -rf wrangler-dist",
73
87
  "bundle": "node -r esbuild-register scripts/bundle.ts",
74
88
  "build": "npm run clean && npm run bundle",
75
- "start": "npm run bundle && ./bin/wrangler.js"
89
+ "start": "npm run bundle && NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
90
+ "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true"
76
91
  },
77
92
  "engines": {
78
93
  "node": ">=16.0.0"
94
+ },
95
+ "jest": {
96
+ "testRegex": ".*.(test|spec)\\.[jt]sx?$",
97
+ "transformIgnorePatterns": [
98
+ "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill)"
99
+ ],
100
+ "moduleNameMapper": {
101
+ "clipboardy": "<rootDir>/src/__tests__/clipboardy-mock.js"
102
+ },
103
+ "transform": {
104
+ "^.+\\.c?(t|j)sx?$": [
105
+ "esbuild-jest",
106
+ {
107
+ "sourcemap": true
108
+ }
109
+ ]
110
+ }
79
111
  }
80
112
  }
@@ -0,0 +1,4 @@
1
+ // We use this mock during tests because we're having trouble
2
+ // properly compiling clipboardy for jest
3
+ // We can revisit this if and when we write tests that test
4
+ // the copying part of `dev`
File without changes
@@ -0,0 +1,153 @@
1
+ import * as fs from "node:fs";
2
+ import * as fsp from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ import * as TOML from "@iarna/toml";
5
+ import { main } from "../index";
6
+ // @ts-expect-error we're mocking cfetch, so of course setMock isn't a thing
7
+ import { setMock, unsetAllMocks } from "../cfetch";
8
+
9
+ jest.mock("../cfetch", () => {
10
+ return jest.requireActual("./mock-cfetch");
11
+ });
12
+
13
+ async function w(cmd: void | string, options?: { tap: boolean }) {
14
+ const tapped = options?.tap ? tap() : undefined;
15
+ await main([...(cmd ? cmd.split(" ") : [])]);
16
+ tapped?.off();
17
+ return { stdout: tapped?.out, stderr: tapped?.err };
18
+ }
19
+
20
+ function tap() {
21
+ const oldLog = console.log;
22
+ const oldError = console.error;
23
+
24
+ const toReturn = {
25
+ off: () => {
26
+ console.log = oldLog;
27
+ console.error = oldError;
28
+ },
29
+ out: "",
30
+ err: "",
31
+ };
32
+
33
+ console.log = (...args) => {
34
+ toReturn.out += args.join("");
35
+ oldLog.apply(console, args);
36
+ // console.trace(...args); // use this if you want to find the true source of your console.log
37
+ };
38
+ console.error = (...args) => {
39
+ toReturn.err += args.join("");
40
+ oldError.apply(console, args);
41
+ };
42
+
43
+ return toReturn;
44
+ }
45
+
46
+ describe("wrangler", () => {
47
+ it("should run", async () => {
48
+ const { stdout } = await w(undefined, { tap: true });
49
+
50
+ expect(stdout).toMatchInlineSnapshot(`
51
+ "wrangler
52
+
53
+ Commands:
54
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
55
+ wrangler dev <filename> 👂 Start a local server for developing your worker
56
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
57
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
58
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
59
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
60
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
61
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
62
+ wrangler pages ⚡️ Configure Cloudflare Pages
63
+
64
+ Flags:
65
+ --config Path to .toml configuration file [string]
66
+ --help Show help [boolean]
67
+ --version Show version number [boolean]
68
+
69
+ Options:
70
+ --local Run on my machine [boolean] [default: false]"
71
+ `);
72
+ });
73
+
74
+ describe("init", () => {
75
+ const ogcwd = process.cwd();
76
+
77
+ beforeEach(() => {
78
+ process.chdir(path.join(__dirname, "fixtures", "init"));
79
+ });
80
+
81
+ afterEach(async () => {
82
+ await fsp.rm("./wrangler.toml");
83
+ process.chdir(ogcwd);
84
+ });
85
+
86
+ it("should create a wrangler.toml", async () => {
87
+ await w("init");
88
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
89
+ expect(typeof parsed.compatibility_date).toBe("string");
90
+ });
91
+
92
+ it("should error when wrangler.toml already exists", async () => {
93
+ fs.closeSync(fs.openSync("./wrangler.toml", "w"));
94
+ const { stderr } = await w("init", { tap: true });
95
+ expect(stderr.endsWith("wrangler.toml already exists.")).toBe(true);
96
+ });
97
+ });
98
+
99
+ describe("kv:namespace", () => {
100
+ afterAll(() => {
101
+ unsetAllMocks();
102
+ });
103
+ let KVNamespaces: { title: string; id: string }[] = [];
104
+ it("can create a namespace", async () => {
105
+ setMock("/accounts/:accountId/storage/kv/namespaces", (uri, init) => {
106
+ expect(init.method === "POST");
107
+ const body = JSON.parse(init.body);
108
+ expect(body.title).toBe("worker-UnitTestNamespace");
109
+ KVNamespaces.push({ title: body.title, id: "some-namespace-id" });
110
+ return { id: "some-namespace-id" };
111
+ });
112
+
113
+ await w('kv:namespace create "UnitTestNamespace"');
114
+ expect(
115
+ KVNamespaces.find((ns) => ns.title === `worker-UnitTestNamespace`)
116
+ ).toBeTruthy();
117
+ });
118
+
119
+ let createdNamespace: { id: string; title: string };
120
+ it("can list namespaces", async () => {
121
+ setMock(
122
+ "/accounts/:accountId/storage/kv/namespaces\\?:qs",
123
+ (uri, init) => {
124
+ expect(init).toBe(undefined);
125
+ return KVNamespaces;
126
+ }
127
+ );
128
+ const { stdout } = await w("kv:namespace list", { tap: true });
129
+ const namespaces = JSON.parse(stdout);
130
+ createdNamespace = namespaces.find(
131
+ (ns) => ns.title === "worker-UnitTestNamespace"
132
+ );
133
+ expect(createdNamespace.title).toBe("worker-UnitTestNamespace");
134
+ });
135
+
136
+ it("can delete a namespace", async () => {
137
+ const namespaceIdToDelete = createdNamespace.id;
138
+ setMock(
139
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId",
140
+ (uri, init) => {
141
+ expect(init.method).toBe("DELETE");
142
+ KVNamespaces = KVNamespaces.filter(
143
+ (ns) => ns.id !== namespaceIdToDelete
144
+ );
145
+ }
146
+ );
147
+ await w(`kv:namespace delete --namespace-id ${namespaceIdToDelete}`);
148
+ expect(KVNamespaces.find((ns) => ns.id === namespaceIdToDelete)).toBe(
149
+ undefined
150
+ );
151
+ });
152
+ });
153
+ });
@@ -0,0 +1,46 @@
1
+ // This file mocks ../cfetch.ts
2
+ // so we can insert whatever responses we want from it
3
+
4
+ const pathToRegexp = require("path-to-regexp");
5
+ // TODO: add jsdoc style types here
6
+
7
+ // type MockHandler = (resource: string, init?: RequestInit) => any; // TODO: use a generic here
8
+
9
+ let mocks = [];
10
+
11
+ function mockCfetch(resource, init) {
12
+ for (const { regexp, handler } of mocks) {
13
+ if (regexp.test(resource)) {
14
+ return handler(resource, init); // should we have some kind of fallthrough system? we'll see.
15
+ }
16
+ }
17
+ throw new Error(`no mocks found for ${resource}`);
18
+ }
19
+
20
+ function setMock(resource, handler) {
21
+ const mock = {
22
+ resource,
23
+ handler,
24
+ regexp: pathToRegexp(resource),
25
+ };
26
+ mocks.push(mock);
27
+ return () => {
28
+ mocks = mocks.filter((x) => x !== mock);
29
+ };
30
+ }
31
+
32
+ function unsetAllMocks() {
33
+ mocks = [];
34
+ }
35
+
36
+ const CF_API_BASE_URL =
37
+ process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
38
+
39
+ Object.assign(module.exports, {
40
+ __esModule: true,
41
+ default: mockCfetch,
42
+ mockCfetch,
43
+ setMock,
44
+ unsetAllMocks,
45
+ CF_API_BASE_URL,
46
+ });
@@ -0,0 +1,125 @@
1
+ import type {
2
+ CfWorkerInit,
3
+ CfModuleType,
4
+ CfVariable,
5
+ CfModule,
6
+ CfKvNamespace,
7
+ CfCryptoKey,
8
+ } from "./worker.js";
9
+ import { FormData, Blob } from "formdata-node";
10
+
11
+ // Credit: https://stackoverflow.com/a/9458996
12
+ function toBase64(source: BufferSource): string {
13
+ let result = "";
14
+ const buffer = source instanceof ArrayBuffer ? source : source.buffer;
15
+ const bytes = new Uint8Array(buffer);
16
+ for (let i = 0; i < bytes.byteLength; i++) {
17
+ result += String.fromCharCode(bytes[i]);
18
+ }
19
+ return btoa(result);
20
+ }
21
+
22
+ function toBinding(
23
+ name: string,
24
+ variable: CfVariable
25
+ ): Record<string, unknown> {
26
+ if (typeof variable === "string") {
27
+ return { name, type: "plain_text", text: variable };
28
+ }
29
+
30
+ const { namespaceId } = variable as CfKvNamespace;
31
+ if (namespaceId) {
32
+ return { name, type: "kv_namespace", namespace_id: namespaceId };
33
+ }
34
+
35
+ const { format, algorithm, usages, data } = variable as CfCryptoKey;
36
+ if (format) {
37
+ let key_base64;
38
+ let key_jwk;
39
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
40
+ key_base64 = toBase64(data);
41
+ } else {
42
+ key_jwk = data;
43
+ }
44
+ return {
45
+ name,
46
+ type: "secret_key",
47
+ format,
48
+ algorithm,
49
+ usages,
50
+ key_base64,
51
+ key_jwk,
52
+ };
53
+ }
54
+
55
+ throw new TypeError("Unsupported variable: " + variable);
56
+ }
57
+
58
+ export function toMimeType(type: CfModuleType): string {
59
+ switch (type) {
60
+ case "esm":
61
+ return "application/javascript+module";
62
+ case "commonjs":
63
+ return "application/javascript";
64
+ case "compiled-wasm":
65
+ return "application/wasm";
66
+ case "buffer":
67
+ return "application/octet-stream";
68
+ case "text":
69
+ return "text/plain";
70
+ default:
71
+ throw new TypeError("Unsupported module: " + type);
72
+ }
73
+ }
74
+
75
+ function toModule(module: CfModule, entryType?: CfModuleType): Blob {
76
+ const { type: moduleType, content } = module;
77
+ const type = toMimeType(moduleType ?? entryType);
78
+
79
+ return new Blob([content], { type });
80
+ }
81
+
82
+ /**
83
+ * Creates a `FormData` upload from a `CfWorkerInit`.
84
+ */
85
+ export function toFormData(worker: CfWorkerInit): FormData {
86
+ const formData = new FormData();
87
+ const { main, modules, variables, usage_model, compatibility_date } = worker;
88
+ const { name, type: mainType } = main;
89
+
90
+ const bindings = [];
91
+ for (const [name, variable] of Object.entries(variables ?? {})) {
92
+ const binding = toBinding(name, variable);
93
+ bindings.push(binding);
94
+ }
95
+
96
+ const singleton = mainType === "commonjs";
97
+ const metadata = {
98
+ main_module: singleton ? undefined : name,
99
+ body_part: singleton ? name : undefined,
100
+ bindings,
101
+ };
102
+ if (compatibility_date) {
103
+ // @ts-expect-error - we should type metadata
104
+ metadata.compatibility_date = compatibility_date;
105
+ }
106
+ if (usage_model) {
107
+ // @ts-expect-error - we should type metadata
108
+ metadata.usage_model = usage_model;
109
+ }
110
+ formData.set("metadata", JSON.stringify(metadata));
111
+
112
+ if (singleton && modules && modules.length > 0) {
113
+ throw new TypeError(
114
+ "More than one module can only be specified when type = 'esm'"
115
+ );
116
+ }
117
+
118
+ for (const module of [main].concat(modules || [])) {
119
+ const { name } = module;
120
+ const blob = toModule(module, mainType ?? "esm");
121
+ formData.set(name, blob, name);
122
+ }
123
+
124
+ return formData;
125
+ }