wrangler 0.0.0-e151223 → 0.0.0-e1e2ee5c

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 (209) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +160 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5354 -0
  6. package/package.json +166 -127
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +3950 -0
  10. package/src/__tests__/dev.test.tsx +1199 -67
  11. package/src/__tests__/guess-worker-format.test.ts +85 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +36 -18
  14. package/src/__tests__/helpers/mock-bin.ts +36 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +118 -80
  16. package/src/__tests__/helpers/mock-console.ts +70 -29
  17. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  18. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  19. package/src/__tests__/helpers/mock-istty.ts +74 -0
  20. package/src/__tests__/helpers/mock-kv.ts +28 -35
  21. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  22. package/src/__tests__/helpers/mock-process.ts +39 -0
  23. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  24. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  25. package/src/__tests__/helpers/run-in-tmp.ts +29 -20
  26. package/src/__tests__/helpers/run-wrangler.ts +8 -6
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  29. package/src/__tests__/https-options.test.ts +163 -0
  30. package/src/__tests__/index.test.ts +255 -399
  31. package/src/__tests__/init.test.ts +1992 -0
  32. package/src/__tests__/jest.setup.ts +102 -16
  33. package/src/__tests__/kv.test.ts +1400 -878
  34. package/src/__tests__/logger.test.ts +141 -0
  35. package/src/__tests__/metrics.test.ts +445 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1261 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6633 -1184
  40. package/src/__tests__/pubsub.test.ts +367 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +484 -202
  44. package/src/__tests__/tail.test.ts +698 -0
  45. package/src/__tests__/test-old-node-version.js +31 -0
  46. package/src/__tests__/user.test.ts +143 -0
  47. package/src/__tests__/version.test.ts +35 -0
  48. package/src/__tests__/whoami.test.tsx +219 -75
  49. package/src/__tests__/worker-namespace.test.ts +327 -0
  50. package/src/abort.d.ts +3 -0
  51. package/src/api/dev.ts +86 -0
  52. package/src/api/index.ts +1 -0
  53. package/src/bundle-reporter.tsx +29 -0
  54. package/src/bundle.ts +236 -0
  55. package/src/cfetch/index.ts +86 -76
  56. package/src/cfetch/internal.ts +122 -45
  57. package/src/cli.ts +24 -6
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +251 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +453 -0
  62. package/src/config/index.ts +238 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1754 -0
  65. package/src/config-cache.ts +84 -0
  66. package/src/create-worker-preview.ts +255 -0
  67. package/src/create-worker-upload-form.ts +263 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +452 -0
  70. package/src/dev/local.tsx +373 -0
  71. package/src/dev/remote.tsx +386 -0
  72. package/src/dev/use-esbuild.ts +150 -0
  73. package/src/dev.tsx +579 -820
  74. package/src/dialogs.tsx +115 -57
  75. package/src/durable.ts +102 -0
  76. package/src/entry.ts +328 -0
  77. package/src/environment-variables.ts +35 -0
  78. package/src/errors.ts +11 -0
  79. package/src/faye-websocket.d.ts +6 -0
  80. package/src/generate.ts +33 -0
  81. package/src/git-client.ts +42 -0
  82. package/src/global-wrangler-config-path.ts +26 -0
  83. package/src/https-options.ts +127 -0
  84. package/src/index.tsx +1969 -2024
  85. package/src/init.ts +549 -0
  86. package/src/inspect.ts +603 -537
  87. package/src/intl-polyfill.d.ts +139 -0
  88. package/src/is-interactive.ts +12 -0
  89. package/src/kv.ts +430 -0
  90. package/src/logger.ts +73 -0
  91. package/src/metrics/index.ts +4 -0
  92. package/src/metrics/is-ci.ts +14 -0
  93. package/src/metrics/metrics-config.ts +239 -0
  94. package/src/metrics/metrics-dispatcher.ts +95 -0
  95. package/src/metrics/send-event.ts +92 -0
  96. package/src/miniflare-cli/README.md +30 -0
  97. package/src/miniflare-cli/assets.ts +543 -0
  98. package/src/miniflare-cli/enum-keys.ts +17 -0
  99. package/src/miniflare-cli/index.ts +85 -0
  100. package/src/miniflare-cli/request-context.ts +40 -0
  101. package/src/module-collection.ts +244 -49
  102. package/src/open-in-browser.ts +17 -0
  103. package/src/package-manager.ts +219 -0
  104. package/src/pages/build.tsx +204 -0
  105. package/src/pages/constants.ts +7 -0
  106. package/src/pages/deployments.tsx +106 -0
  107. package/src/pages/dev.tsx +401 -0
  108. package/src/pages/functions/buildPlugin.ts +105 -0
  109. package/src/pages/functions/buildWorker.ts +151 -0
  110. package/src/pages/functions/filepath-routing.test.ts +234 -0
  111. package/src/pages/functions/filepath-routing.ts +189 -0
  112. package/src/pages/functions/identifiers.ts +78 -0
  113. package/src/pages/functions/routes.ts +151 -0
  114. package/src/pages/index.tsx +84 -0
  115. package/src/pages/projects.tsx +163 -0
  116. package/src/pages/publish.tsx +338 -0
  117. package/src/pages/types.ts +40 -0
  118. package/src/pages/upload.tsx +396 -0
  119. package/src/pages/utils.ts +12 -0
  120. package/src/parse.ts +286 -0
  121. package/src/paths.ts +6 -6
  122. package/src/preview.ts +31 -0
  123. package/src/proxy.ts +417 -311
  124. package/src/publish.ts +774 -391
  125. package/src/pubsub/index.ts +286 -0
  126. package/src/pubsub/pubsub-commands.tsx +623 -0
  127. package/src/r2.ts +50 -0
  128. package/src/selfsigned.d.ts +29 -0
  129. package/src/sites.tsx +291 -159
  130. package/src/tail/filters.ts +279 -0
  131. package/src/tail/index.ts +299 -0
  132. package/src/tail/printing.ts +67 -0
  133. package/src/update-check.ts +19 -0
  134. package/src/user/choose-account.tsx +69 -0
  135. package/src/user/env-vars.ts +46 -0
  136. package/src/user/generate-auth-url.ts +33 -0
  137. package/src/user/generate-random-state.ts +16 -0
  138. package/src/user/index.ts +3 -0
  139. package/src/user/user.tsx +1171 -0
  140. package/src/whoami.tsx +63 -41
  141. package/src/worker-namespace.ts +206 -0
  142. package/src/worker.ts +191 -0
  143. package/src/zones.ts +76 -0
  144. package/templates/checked-fetch.js +17 -0
  145. package/templates/gitignore +171 -0
  146. package/templates/new-worker-scheduled.js +17 -0
  147. package/templates/new-worker-scheduled.ts +32 -0
  148. package/templates/new-worker.js +15 -0
  149. package/templates/new-worker.ts +30 -0
  150. package/templates/no-op-worker.js +10 -0
  151. package/templates/pages-shim.ts +9 -0
  152. package/templates/pages-template-plugin.ts +155 -0
  153. package/templates/pages-template-worker.ts +161 -0
  154. package/templates/static-asset-facade.js +49 -0
  155. package/templates/tsconfig.json +105 -0
  156. package/wrangler-dist/cli.d.ts +327 -0
  157. package/wrangler-dist/cli.js +78107 -79324
  158. package/pages/functions/buildWorker.ts +0 -62
  159. package/pages/functions/filepath-routing.test.ts +0 -47
  160. package/pages/functions/filepath-routing.ts +0 -231
  161. package/pages/functions/identifiers.ts +0 -78
  162. package/pages/functions/routes.ts +0 -160
  163. package/pages/functions/template-worker.ts +0 -136
  164. package/src/__tests__/helpers/mock-user.ts +0 -27
  165. package/src/__tests__/logout.test.ts +0 -50
  166. package/src/api/form_data.ts +0 -134
  167. package/src/api/preview.ts +0 -128
  168. package/src/api/worker.ts +0 -155
  169. package/src/config.ts +0 -641
  170. package/src/kv.tsx +0 -276
  171. package/src/npm-installer.ts +0 -20
  172. package/src/pages.tsx +0 -1045
  173. package/src/tail.tsx +0 -73
  174. package/src/user.tsx +0 -1019
  175. package/static-asset-facade.js +0 -47
  176. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  177. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  178. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  179. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  180. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  181. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  182. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  183. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  184. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  185. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  186. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  187. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  188. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  189. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  190. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  191. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  192. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  193. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  194. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  195. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  196. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  197. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  198. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  199. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  200. package/vendor/wrangler-mime/LICENSE +0 -21
  201. package/vendor/wrangler-mime/Mime.js +0 -97
  202. package/vendor/wrangler-mime/README.md +0 -187
  203. package/vendor/wrangler-mime/cli.js +0 -46
  204. package/vendor/wrangler-mime/index.js +0 -4
  205. package/vendor/wrangler-mime/lite.js +0 -4
  206. package/vendor/wrangler-mime/package.json +0 -52
  207. package/vendor/wrangler-mime/types/other.js +0 -1
  208. package/vendor/wrangler-mime/types/standard.js +0 -1
  209. package/wrangler-dist/cli.js.map +0 -7
@@ -1,136 +0,0 @@
1
- import { match } from "path-to-regexp";
2
- import type { HTTPMethod } from "./routes";
3
-
4
- /* TODO: Grab these from @cloudflare/workers-types instead */
5
- type Params<P extends string = string> = Record<P, string | string[]>;
6
-
7
- type EventContext<Env, P extends string, Data> = {
8
- request: Request;
9
- waitUntil: (promise: Promise<unknown>) => void;
10
- next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
11
- env: Env & { ASSETS: { fetch: typeof fetch } };
12
- params: Params<P>;
13
- data: Data;
14
- };
15
-
16
- declare type PagesFunction<
17
- Env = unknown,
18
- P extends string = string,
19
- Data extends Record<string, unknown> = Record<string, unknown>
20
- > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
21
- /* end @cloudflare/workers-types */
22
-
23
- type RouteHandler = {
24
- routePath: string;
25
- methods: HTTPMethod[];
26
- modules: PagesFunction[];
27
- middlewares: PagesFunction[];
28
- };
29
-
30
- // inject `routes` via ESBuild
31
- declare const routes: RouteHandler[];
32
- // define `__FALLBACK_SERVICE__` via ESBuild
33
- declare const __FALLBACK_SERVICE__: string;
34
-
35
- // expect an ASSETS fetcher binding pointing to the asset-server stage
36
- type FetchEnv = {
37
- [name: string]: { fetch: typeof fetch };
38
- ASSETS: { fetch: typeof fetch };
39
- };
40
-
41
- type WorkerContext = {
42
- waitUntil: (promise: Promise<unknown>) => void;
43
- };
44
-
45
- function* executeRequest(request: Request, _env: FetchEnv) {
46
- const requestPath = new URL(request.url).pathname;
47
-
48
- // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
49
- for (const route of [...routes].reverse()) {
50
- if (
51
- route.methods.length &&
52
- !route.methods.includes(request.method as HTTPMethod)
53
- ) {
54
- continue;
55
- }
56
-
57
- const routeMatcher = match(route.routePath, { end: false });
58
- const matchResult = routeMatcher(requestPath);
59
- if (matchResult) {
60
- for (const handler of route.middlewares.flat()) {
61
- yield {
62
- handler,
63
- params: matchResult.params as Params,
64
- };
65
- }
66
- }
67
- }
68
-
69
- // Then look for the first exact route match and execute its "modules"
70
- for (const route of routes) {
71
- if (
72
- route.methods.length &&
73
- !route.methods.includes(request.method as HTTPMethod)
74
- ) {
75
- continue;
76
- }
77
-
78
- const routeMatcher = match(route.routePath, { end: true });
79
- const matchResult = routeMatcher(requestPath);
80
- if (matchResult && route.modules.length) {
81
- for (const handler of route.modules.flat()) {
82
- yield {
83
- handler,
84
- params: matchResult.params as Params,
85
- };
86
- }
87
- break;
88
- }
89
- }
90
- }
91
-
92
- export default {
93
- async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
94
- const handlerIterator = executeRequest(request, env);
95
- const data = {}; // arbitrary data the user can set between functions
96
- const next = async (input?: RequestInfo, init?: RequestInit) => {
97
- if (input !== undefined) {
98
- request = new Request(input, init);
99
- }
100
-
101
- const result = handlerIterator.next();
102
- // Note we can't use `!result.done` because this doesn't narrow to the correct type
103
- if (result.done == false) {
104
- const { handler, params } = result.value;
105
- const context = {
106
- request: new Request(request.clone()),
107
- next,
108
- params,
109
- data,
110
- env,
111
- waitUntil: workerContext.waitUntil.bind(workerContext),
112
- };
113
-
114
- const response = await handler(context);
115
-
116
- // https://fetch.spec.whatwg.org/#null-body-status
117
- return new Response(
118
- [101, 204, 205, 304].includes(response.status) ? null : response.body,
119
- response
120
- );
121
- } else if (__FALLBACK_SERVICE__) {
122
- // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
123
- return env[__FALLBACK_SERVICE__].fetch(request);
124
- } else {
125
- // There was not fallback service so actually make the request to the origin.
126
- return fetch(request);
127
- }
128
- };
129
-
130
- try {
131
- return next();
132
- } catch (err) {
133
- return new Response("Internal Error", { status: 500 });
134
- }
135
- },
136
- };
@@ -1,27 +0,0 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
-
5
- export function writeUserConfig(
6
- oauth_token?: string,
7
- refresh_token?: string,
8
- expiration_time?: string
9
- ) {
10
- const lines: string[] = [];
11
- if (oauth_token) {
12
- lines.push(`oauth_token = "${oauth_token}"`);
13
- }
14
- if (refresh_token) {
15
- lines.push(`refresh_token = "${refresh_token}"`);
16
- }
17
- if (expiration_time) {
18
- lines.push(`expiration_time = "${expiration_time}"`);
19
- }
20
- const configPath = path.join(os.homedir(), ".wrangler/config");
21
- mkdirSync(configPath, { recursive: true });
22
- writeFileSync(
23
- path.join(configPath, "default.toml"),
24
- lines.join("\n"),
25
- "utf-8"
26
- );
27
- }
@@ -1,50 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import fetchMock from "jest-fetch-mock";
5
- import { initialise } from "../user";
6
- import { mockConsoleMethods } from "./helpers/mock-console";
7
- import { writeUserConfig } from "./helpers/mock-user";
8
- import { runInTempDir } from "./helpers/run-in-tmp";
9
- import { runWrangler } from "./helpers/run-wrangler";
10
-
11
- describe("wrangler", () => {
12
- runInTempDir({ homedir: "./home" });
13
- const std = mockConsoleMethods();
14
-
15
- describe("logout", () => {
16
- it("should exit with a message stating the user is not logged in", async () => {
17
- await initialise();
18
- await runWrangler("logout");
19
- expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
20
- });
21
-
22
- it("should logout user that has been properly logged in", async () => {
23
- writeUserConfig("some-oauth-tok", "some-refresh-tok");
24
-
25
- // Mock out the response for a request to revoke the auth tokens,
26
- // checking the form of the request is as expected.
27
- fetchMock.mockResponseOnce(async (req) => {
28
- expect(req.url).toEqual("https://dash.cloudflare.com/oauth2/revoke");
29
- expect(req.method).toEqual("POST");
30
- return "";
31
- });
32
-
33
- await initialise();
34
- await runWrangler("logout");
35
-
36
- expect(std.out).toMatchInlineSnapshot(`
37
- "💁 Wrangler is configured with an OAuth token. The token has been successfully revoked
38
- Removing ./home/.wrangler/config/default.toml.. success!"
39
- `);
40
-
41
- // Make sure that we made the request to logout.
42
- expect(fetchMock).toHaveBeenCalledTimes(1);
43
-
44
- // Make sure that logout removed the config file containing the auth tokens.
45
- expect(
46
- existsSync(path.join(os.homedir(), ".wrangler/config/default.toml"))
47
- ).toBe(false);
48
- });
49
- });
50
- });
@@ -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
- }