wrangler 0.0.0-e0d2f35 → 0.0.0-e11e1691

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 (130) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +122 -31
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +176 -80
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +167 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-ensure-req-body-drained.ts +19 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/modules-watch-stub.js +4 -0
  28. package/templates/new-worker-scheduled.js +17 -0
  29. package/templates/new-worker-scheduled.ts +32 -0
  30. package/templates/new-worker.js +15 -0
  31. package/templates/new-worker.ts +33 -0
  32. package/templates/no-op-worker.js +10 -0
  33. package/templates/pages-dev-pipeline.ts +32 -0
  34. package/templates/pages-dev-util.ts +55 -0
  35. package/templates/pages-shim.ts +9 -0
  36. package/templates/pages-template-plugin.ts +190 -0
  37. package/templates/pages-template-worker.ts +198 -0
  38. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  39. package/templates/startDevWorker/ProxyWorker.ts +326 -0
  40. package/templates/tsconfig-sanity.ts +11 -0
  41. package/templates/tsconfig.init.json +105 -0
  42. package/templates/tsconfig.json +8 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +237 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +23937 -0
  48. package/wrangler-dist/cli.js +164283 -116933
  49. package/wrangler-dist/wasm-sync.wasm +0 -0
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/pages/functions/buildWorker.ts +0 -62
  55. package/pages/functions/filepath-routing.test.ts +0 -39
  56. package/pages/functions/filepath-routing.ts +0 -228
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -158
  59. package/pages/functions/template-worker.ts +0 -136
  60. package/src/__tests__/clipboardy-mock.js +0 -4
  61. package/src/__tests__/dev.test.tsx +0 -71
  62. package/src/__tests__/index.test.ts +0 -424
  63. package/src/__tests__/jest.setup.ts +0 -29
  64. package/src/__tests__/kv.test.ts +0 -1224
  65. package/src/__tests__/logout.test.ts +0 -64
  66. package/src/__tests__/mock-cfetch.ts +0 -173
  67. package/src/__tests__/mock-console.ts +0 -34
  68. package/src/__tests__/mock-dialogs.ts +0 -65
  69. package/src/__tests__/mock-kv.ts +0 -40
  70. package/src/__tests__/mock-user.ts +0 -27
  71. package/src/__tests__/publish.test.ts +0 -1206
  72. package/src/__tests__/run-in-tmp.ts +0 -29
  73. package/src/__tests__/run-wrangler.ts +0 -8
  74. package/src/__tests__/secret.test.ts +0 -206
  75. package/src/__tests__/whoami.test.tsx +0 -101
  76. package/src/api/form_data.ts +0 -135
  77. package/src/api/preview.ts +0 -128
  78. package/src/api/worker.ts +0 -155
  79. package/src/cfetch/index.ts +0 -111
  80. package/src/cfetch/internal.ts +0 -71
  81. package/src/cli.ts +0 -9
  82. package/src/config.ts +0 -641
  83. package/src/dev.tsx +0 -830
  84. package/src/dialogs.tsx +0 -77
  85. package/src/index.tsx +0 -2078
  86. package/src/inspect.ts +0 -595
  87. package/src/kv.tsx +0 -276
  88. package/src/module-collection.ts +0 -63
  89. package/src/pages.tsx +0 -1043
  90. package/src/proxy.ts +0 -370
  91. package/src/publish.ts +0 -410
  92. package/src/sites.tsx +0 -240
  93. package/src/tail.tsx +0 -73
  94. package/src/user.tsx +0 -1019
  95. package/src/whoami.tsx +0 -69
  96. package/static-asset-facade.js +0 -47
  97. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  98. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  99. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  100. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  101. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  102. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  103. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  104. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  105. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  106. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  107. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  108. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  109. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  110. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  111. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  112. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  113. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  114. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  115. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  116. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  117. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  118. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  119. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  120. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  121. package/vendor/wrangler-mime/LICENSE +0 -21
  122. package/vendor/wrangler-mime/Mime.js +0 -97
  123. package/vendor/wrangler-mime/README.md +0 -187
  124. package/vendor/wrangler-mime/cli.js +0 -46
  125. package/vendor/wrangler-mime/index.js +0 -4
  126. package/vendor/wrangler-mime/lite.js +0 -4
  127. package/vendor/wrangler-mime/package.json +0 -52
  128. package/vendor/wrangler-mime/types/other.js +0 -1
  129. package/vendor/wrangler-mime/types/standard.js +0 -1
  130. package/wrangler-dist/cli.js.map +0 -7
@@ -1,29 +0,0 @@
1
- import os from "node:os";
2
- import * as path from "node:path";
3
- import * as fs from "fs";
4
-
5
- const originalCwd = process.cwd();
6
-
7
- export function runInTempDir({ homedir }: { homedir?: string } = {}) {
8
- let tmpDir: string;
9
-
10
- beforeEach(() => {
11
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrangler-tests"));
12
- process.chdir(tmpDir);
13
- if (homedir !== undefined) {
14
- // Override where the home directory is so that we can write our own user config,
15
- // without destroying the real thing.
16
- fs.mkdirSync(homedir);
17
- // Note it is very important that we use the "default" value from "node:os" (e.g. `import os from "node:os";`)
18
- // rather than an alias to the module (e.g. `import * as os from "node:os";`).
19
- // This is because the module gets transpiled so that the "method" `homedir()` gets converted to a
20
- // getter that is not configurable (and so cannot be spied upon).
21
- jest.spyOn(os, "homedir").mockReturnValue(homedir);
22
- }
23
- });
24
-
25
- afterEach(() => {
26
- process.chdir(originalCwd);
27
- fs.rmSync(tmpDir, { recursive: true });
28
- });
29
- }
@@ -1,8 +0,0 @@
1
- import { main } from "../index";
2
-
3
- /**
4
- * A helper to 'run' wrangler commands for tests.
5
- */
6
- export async function runWrangler(cmd?: string) {
7
- await main(cmd?.split(" ") ?? []);
8
- }
@@ -1,206 +0,0 @@
1
- import { setMockResponse, unsetAllMocks } from "./mock-cfetch";
2
- import { runWrangler } from "./run-wrangler";
3
- import { runInTempDir } from "./run-in-tmp";
4
- import { mockConfirm, mockPrompt } from "./mock-dialogs";
5
- import { mockConsoleMethods } from "./mock-console";
6
-
7
- describe("wrangler secret", () => {
8
- const std = mockConsoleMethods();
9
- runInTempDir();
10
- afterEach(() => {
11
- unsetAllMocks();
12
- });
13
-
14
- describe("put", () => {
15
- function mockPutRequest(input: { name: string; text: string }) {
16
- setMockResponse(
17
- "/accounts/:accountId/workers/scripts/:scriptName/secrets",
18
- "PUT",
19
- ([_url, accountId], { body }) => {
20
- expect(accountId).toEqual("some-account-id");
21
- const { name, text, type } = JSON.parse(body as string);
22
- expect(type).toEqual("secret_text");
23
- expect(name).toEqual(input.name);
24
- expect(text).toEqual(input.text);
25
-
26
- return { name, type };
27
- }
28
- );
29
- }
30
-
31
- it("should create a secret", async () => {
32
- mockPrompt({
33
- text: "Enter a secret value:",
34
- type: "password",
35
- result: "the-secret",
36
- });
37
-
38
- mockPutRequest({ name: "the-secret-name", text: "the-secret" });
39
- await runWrangler("secret put the-key --name script-name");
40
-
41
- expect(std.out).toMatchInlineSnapshot(`
42
- "🌀 Creating the secret for script script-name
43
- ✨ Success! Uploaded secret the-key"
44
- `);
45
- expect(std.err).toMatchInlineSnapshot(`""`);
46
- });
47
-
48
- it("should error without a script name", async () => {
49
- let error: Error | undefined;
50
- try {
51
- await runWrangler("secret put the-key");
52
- } catch (e) {
53
- error = e;
54
- }
55
- expect(std.out).toMatchInlineSnapshot(`""`);
56
- expect(std.err).toMatchInlineSnapshot(`
57
- "Missing script name
58
-
59
- %s
60
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
61
- `);
62
- expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
63
- });
64
-
65
- it("warns about being a no-op in local mode", async () => {
66
- mockPrompt({
67
- text: "Enter a secret value:",
68
- type: "password",
69
- result: "the-secret",
70
- });
71
-
72
- mockPutRequest({ name: "the-secret-name", text: "the-secret" });
73
- await runWrangler("secret put the-key --name script-name --local");
74
- expect(std.out).toMatchInlineSnapshot(`""`);
75
- expect(std.err).toMatchInlineSnapshot(`""`);
76
- expect(std.warn).toMatchInlineSnapshot(
77
- `"\`wrangler secret put\` is a no-op in --local mode"`
78
- );
79
- });
80
- });
81
-
82
- describe("delete", () => {
83
- function mockDeleteRequest(input: {
84
- scriptName: string;
85
- secretName: string;
86
- }) {
87
- setMockResponse(
88
- "/accounts/:accountId/workers/scripts/:scriptName/secrets/:secretName",
89
- "DELETE",
90
- ([_url, accountId, scriptName, secretName]) => {
91
- expect(accountId).toEqual("some-account-id");
92
- expect(scriptName).toEqual(input.scriptName);
93
- expect(secretName).toEqual(input.secretName);
94
-
95
- return null;
96
- }
97
- );
98
- }
99
- it("should delete a secret", async () => {
100
- mockDeleteRequest({ scriptName: "script-name", secretName: "the-key" });
101
- mockConfirm({
102
- text: "Are you sure you want to permanently delete the variable the-key on the script script-name?",
103
- result: true,
104
- });
105
- await runWrangler("secret delete the-key --name script-name");
106
- expect(std.out).toMatchInlineSnapshot(`
107
- "🌀 Deleting the secret the-key on script script-name.
108
- ✨ Success! Deleted secret the-key"
109
- `);
110
- expect(std.err).toMatchInlineSnapshot(`""`);
111
- });
112
-
113
- it("should error without a script name", async () => {
114
- let error: Error | undefined;
115
-
116
- try {
117
- await runWrangler("secret delete the-key");
118
- } catch (e) {
119
- error = e;
120
- }
121
- expect(std.out).toMatchInlineSnapshot(`""`);
122
- expect(std.err).toMatchInlineSnapshot(`
123
- "Missing script name
124
-
125
- %s
126
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
127
- `);
128
- expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
129
- });
130
-
131
- it("warns about being a no-op in local mode", async () => {
132
- mockConfirm({
133
- text: "Are you sure you want to permanently delete the variable the-key on the script script-name?",
134
- result: true,
135
- });
136
- await runWrangler("secret delete the-key --name script-name --local");
137
- expect(std.out).toMatchInlineSnapshot(
138
- `"🌀 Deleting the secret the-key on script script-name."`
139
- );
140
- expect(std.err).toMatchInlineSnapshot(`""`);
141
- expect(std.warn).toMatchInlineSnapshot(
142
- `"\`wrangler secret delete\` is a no-op in --local mode"`
143
- );
144
- });
145
- });
146
-
147
- describe("list", () => {
148
- function mockListRequest(input: { scriptName: string }) {
149
- setMockResponse(
150
- "/accounts/:accountId/workers/scripts/:scriptName/secrets",
151
- "GET",
152
- ([_url, accountId, scriptName]) => {
153
- expect(accountId).toEqual("some-account-id");
154
- expect(scriptName).toEqual(input.scriptName);
155
-
156
- return [
157
- {
158
- name: "the-secret-name",
159
- type: "secret_text",
160
- },
161
- ];
162
- }
163
- );
164
- }
165
-
166
- it("should list secrets", async () => {
167
- mockListRequest({ scriptName: "script-name" });
168
- await runWrangler("secret list --name script-name");
169
- expect(std.out).toMatchInlineSnapshot(`
170
- "[
171
- {
172
- \\"name\\": \\"the-secret-name\\",
173
- \\"type\\": \\"secret_text\\"
174
- }
175
- ]"
176
- `);
177
- expect(std.err).toMatchInlineSnapshot(`""`);
178
- });
179
-
180
- it("should error without a script name", async () => {
181
- let error: Error | undefined;
182
- try {
183
- await runWrangler("secret list");
184
- } catch (e) {
185
- error = e;
186
- }
187
- expect(std.out).toMatchInlineSnapshot(`""`);
188
- expect(std.err).toMatchInlineSnapshot(`
189
- "Missing script name
190
-
191
- %s
192
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
193
- `);
194
- expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
195
- });
196
-
197
- it("warns about being a no-op in local mode", async () => {
198
- await runWrangler("secret list --name script-name --local");
199
- expect(std.out).toMatchInlineSnapshot(`""`);
200
- expect(std.err).toMatchInlineSnapshot(`""`);
201
- expect(std.warn).toMatchInlineSnapshot(
202
- `"\`wrangler secret list\` is a no-op in --local mode"`
203
- );
204
- });
205
- });
206
- });
@@ -1,101 +0,0 @@
1
- import React from "react";
2
- import { render } from "ink-testing-library";
3
- import type { UserInfo } from "../whoami";
4
- import { getUserInfo, WhoAmI } from "../whoami";
5
- import { runInTempDir } from "./run-in-tmp";
6
- import { setMockResponse } from "./mock-cfetch";
7
- import { initialise } from "../user";
8
- import { writeUserConfig } from "./mock-user";
9
-
10
- const ORIGINAL_CF_API_TOKEN = process.env.CF_API_TOKEN;
11
- const ORIGINAL_CF_ACCOUNT_ID = process.env.CF_ACCOUNT_ID;
12
-
13
- describe("getUserInfo()", () => {
14
- runInTempDir({ homedir: "./home" });
15
-
16
- beforeEach(() => {
17
- // Clear the environment variables, so we can control them in the tests
18
- delete process.env.CF_API_TOKEN;
19
- delete process.env.CF_ACCOUNT_ID;
20
- });
21
-
22
- afterEach(() => {
23
- // Reset any changes to the environment variables
24
- process.env.CF_API_TOKEN = ORIGINAL_CF_API_TOKEN;
25
- process.env.CF_ACCOUNT_ID = ORIGINAL_CF_ACCOUNT_ID;
26
- });
27
-
28
- it("should return undefined if there is no config file", async () => {
29
- await initialise();
30
- const userInfo = await getUserInfo();
31
- expect(userInfo).toBeUndefined();
32
- });
33
-
34
- it("should return undefined if there is an empty config file", async () => {
35
- writeUserConfig();
36
- await initialise();
37
- const userInfo = await getUserInfo();
38
- expect(userInfo).toBeUndefined();
39
- });
40
-
41
- it("should return the user's email and accounts if authenticated via config token", async () => {
42
- writeUserConfig("some-oauth-token");
43
- setMockResponse("/user", () => {
44
- return { email: "user@example.com" };
45
- });
46
- setMockResponse("/accounts", () => {
47
- return [
48
- { name: "Account One", id: "account-1" },
49
- { name: "Account Two", id: "account-2" },
50
- { name: "Account Three", id: "account-3" },
51
- ];
52
- });
53
-
54
- await initialise();
55
- const userInfo = await getUserInfo();
56
-
57
- expect(userInfo).toEqual({
58
- authType: "OAuth",
59
- apiToken: "some-oauth-token",
60
- email: "user@example.com",
61
- accounts: [
62
- { name: "Account One", id: "account-1" },
63
- { name: "Account Two", id: "account-2" },
64
- { name: "Account Three", id: "account-3" },
65
- ],
66
- });
67
- });
68
- });
69
-
70
- describe("WhoAmI component", () => {
71
- it("should return undefined if there is no user", async () => {
72
- const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
73
-
74
- expect(lastFrame()).toMatchInlineSnapshot(
75
- `"You are not authenticated. Please run \`wrangler login\`."`
76
- );
77
- });
78
-
79
- it("should display the user's email and accounts", async () => {
80
- const user: UserInfo = {
81
- authType: "OAuth",
82
- apiToken: "some-oauth-token",
83
- email: "user@example.com",
84
- accounts: [
85
- { name: "Account One", id: "account-1" },
86
- { name: "Account Two", id: "account-2" },
87
- { name: "Account Three", id: "account-3" },
88
- ],
89
- };
90
-
91
- const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
92
-
93
- expect(lastFrame()).toContain(
94
- "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
95
- );
96
- expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
97
- expect(lastFrame()).toMatch(/Account One .+ account-1/);
98
- expect(lastFrame()).toMatch(/Account Two .+ account-2/);
99
- expect(lastFrame()).toMatch(/Account Three .+ account-3/);
100
- });
101
- });
@@ -1,135 +0,0 @@
1
- import type {
2
- CfWorkerInit,
3
- CfModuleType,
4
- CfModule,
5
- CfDurableObjectMigrations,
6
- } from "./worker.js";
7
- import { FormData, Blob } from "formdata-node";
8
-
9
- export function toMimeType(type: CfModuleType): string {
10
- switch (type) {
11
- case "esm":
12
- return "application/javascript+module";
13
- case "commonjs":
14
- return "application/javascript";
15
- case "compiled-wasm":
16
- return "application/wasm";
17
- case "buffer":
18
- return "application/octet-stream";
19
- case "text":
20
- return "text/plain";
21
- default:
22
- throw new TypeError("Unsupported module: " + type);
23
- }
24
- }
25
-
26
- function toModule(module: CfModule, entryType: CfModuleType): Blob {
27
- const { type: moduleType, content } = module;
28
- const type = toMimeType(moduleType ?? entryType);
29
-
30
- return new Blob([content], { type });
31
- }
32
-
33
- export interface WorkerMetadata {
34
- /** The name of the entry point module. Only exists when the worker is in the ES module format */
35
- main_module?: string;
36
- /** The name of the entry point module. Only exists when the worker is in the Service Worker format */
37
- body_part?: string;
38
- compatibility_date?: string;
39
- compatibility_flags?: string[];
40
- usage_model?: "bundled" | "unbound";
41
- migrations?: CfDurableObjectMigrations;
42
- bindings: (
43
- | { type: "kv_namespace"; name: string; namespace_id: string }
44
- | { type: "plain_text"; name: string; text: string }
45
- | {
46
- type: "durable_object_namespace";
47
- name: string;
48
- class_name: string;
49
- script_name?: string;
50
- }
51
- | {
52
- type: "service";
53
- name: string;
54
- service: string;
55
- environment: string;
56
- }
57
- )[];
58
- }
59
-
60
- /**
61
- * Creates a `FormData` upload from a `CfWorkerInit`.
62
- */
63
- export function toFormData(worker: CfWorkerInit): FormData {
64
- const formData = new FormData();
65
- const {
66
- main,
67
- modules,
68
- bindings,
69
- migrations,
70
- usage_model,
71
- compatibility_date,
72
- compatibility_flags,
73
- } = worker;
74
-
75
- const metadataBindings: WorkerMetadata["bindings"] = [];
76
-
77
- bindings.kv_namespaces?.forEach(({ id, binding }) => {
78
- metadataBindings.push({
79
- name: binding,
80
- type: "kv_namespace",
81
- namespace_id: id,
82
- });
83
- });
84
-
85
- bindings.durable_objects?.bindings.forEach(
86
- ({ name, class_name, script_name }) => {
87
- metadataBindings.push({
88
- name,
89
- type: "durable_object_namespace",
90
- class_name: class_name,
91
- ...(script_name && { script_name }),
92
- });
93
- }
94
- );
95
-
96
- Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
97
- metadataBindings.push({ name: key, type: "plain_text", text: value });
98
- });
99
-
100
- bindings.services?.forEach(({ name, service, environment }) => {
101
- metadataBindings.push({
102
- name,
103
- type: "service",
104
- service,
105
- environment,
106
- });
107
- });
108
-
109
- const metadata: WorkerMetadata = {
110
- ...(main.type !== "commonjs"
111
- ? { main_module: main.name }
112
- : { body_part: main.name }),
113
- bindings: metadataBindings,
114
- ...(compatibility_date && { compatibility_date }),
115
- ...(compatibility_flags && { compatibility_flags }),
116
- ...(usage_model && { usage_model }),
117
- ...(migrations && { migrations }),
118
- };
119
-
120
- formData.set("metadata", JSON.stringify(metadata));
121
-
122
- if (main.type === "commonjs" && modules && modules.length > 0) {
123
- throw new TypeError(
124
- "More than one module can only be specified when type = 'esm'"
125
- );
126
- }
127
-
128
- for (const module of [main].concat(modules || [])) {
129
- const { name } = module;
130
- const blob = toModule(module, main.type ?? "esm");
131
- formData.set(name, blob, name);
132
- }
133
-
134
- return formData;
135
- }
@@ -1,128 +0,0 @@
1
- import fetch from "node-fetch";
2
- import { fetchResult } from "../cfetch";
3
- import { toFormData } from "./form_data";
4
- import type { CfAccount, CfWorkerInit } from "./worker";
5
-
6
- /**
7
- * A preview mode.
8
- *
9
- * * If true, then using a `workers.dev` subdomain.
10
- * * Otherwise, a list of routes under a single zone.
11
- */
12
- type CfPreviewMode = { workers_dev: boolean } | { routes: string[] };
13
-
14
- /**
15
- * A preview token.
16
- */
17
- export interface CfPreviewToken {
18
- /**
19
- * The header value required to trigger a preview.
20
- *
21
- * @example
22
- * const headers = { 'cf-workers-preview-token': value }
23
- * const response = await fetch('https://' + host, { headers })
24
- */
25
- value: string;
26
- /**
27
- * The host where the preview is available.
28
- */
29
- host: string;
30
- /**
31
- * A websocket url to a DevTools inspector.
32
- *
33
- * Workers does not have a fully-featured implementation
34
- * of the Chrome DevTools protocol, but supports the following:
35
- * * `console.log()` output.
36
- * * `Error` stack traces.
37
- * * `fetch()` events.
38
- *
39
- * There is no support for breakpoints, but we want to implement
40
- * this eventually.
41
- *
42
- * @link https://chromedevtools.github.io/devtools-protocol/
43
- */
44
- inspectorUrl: URL;
45
- /**
46
- * A url to prewarm the preview session.
47
- *
48
- * @example
49
- * fetch(prewarmUrl, { method: 'POST' })
50
- */
51
- prewarmUrl: URL;
52
- }
53
-
54
- /**
55
- * Generates a preview session token.
56
- */
57
- async function sessionToken(account: CfAccount): Promise<CfPreviewToken> {
58
- const { accountId, zoneId } = account;
59
- const initUrl = zoneId
60
- ? `/zones/${zoneId}/workers/edge-preview`
61
- : `/accounts/${accountId}/workers/subdomain/edge-preview`;
62
-
63
- const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
64
- const { inspector_websocket, token } = (await (
65
- await fetch(exchange_url)
66
- ).json()) as { inspector_websocket: string; token: string };
67
- const { host } = new URL(inspector_websocket);
68
- const query = `cf_workers_preview_token=${token}`;
69
-
70
- return {
71
- value: token,
72
- host,
73
- inspectorUrl: new URL(`${inspector_websocket}?${query}`),
74
- prewarmUrl: new URL(
75
- `https://${host}/cdn-cgi/workers/preview/prewarm?${query}`
76
- ),
77
- };
78
- }
79
-
80
- // Credit: https://stackoverflow.com/a/2117523
81
- function randomId(): string {
82
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
83
- const r = (Math.random() * 16) | 0,
84
- v = c == "x" ? r : (r & 0x3) | 0x8;
85
- return v.toString(16);
86
- });
87
- }
88
-
89
- /**
90
- * Creates a preview token.
91
- */
92
- export async function previewToken(
93
- account: CfAccount,
94
- worker: CfWorkerInit
95
- ): Promise<CfPreviewToken> {
96
- const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(account);
97
-
98
- const { accountId, zoneId } = account;
99
- const scriptId = zoneId ? randomId() : worker.name || host.split(".")[0];
100
- const url = `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
101
-
102
- const mode: CfPreviewMode = zoneId
103
- ? { routes: ["*/*"] }
104
- : { workers_dev: true };
105
-
106
- const formData = toFormData(worker);
107
- formData.set("wrangler-session-config", JSON.stringify(mode));
108
-
109
- const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
110
- method: "POST",
111
- // @ts-expect-error TODO: fix this
112
- body: formData,
113
- headers: {
114
- "cf-preview-upload-config-token": value,
115
- },
116
- });
117
-
118
- return {
119
- value: preview_token,
120
- // TODO: verify this works with zoned workers
121
- host:
122
- worker.name && !zoneId
123
- ? `${worker.name}.${host.split(".").slice(1).join(".")}`
124
- : host,
125
- inspectorUrl,
126
- prewarmUrl,
127
- };
128
- }