wrangler 0.0.0-e2a26a0 → 0.0.0-e2a6fa40

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