1 | type Cloudflare = { |
2 | token: string; |
3 | email: string; |
4 | key: string; |
5 | }; |
6 | |
7 | * Put script content |
8 | * Put script content without touching config or metadata |
9 | */ |
10 | export async function main( |
11 | auth: Cloudflare, |
12 | account_identifier: string, |
13 | script_name: string, |
14 | CF_WORKER_BODY_PART: string, |
15 | CF_WORKER_MAIN_MODULE_PART: string, |
16 | body: { |
17 | "<any part name>"?: string[]; |
18 | metadata?: { |
19 | body_part?: string; |
20 | main_module?: string; |
21 | [k: string]: unknown; |
22 | }; |
23 | [k: string]: unknown; |
24 | } |
25 | ) { |
26 | const url = new URL( |
27 | `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/workers/scripts/${script_name}/content` |
28 | ); |
29 |
|
30 | const formData = new FormData(); |
31 | for (const [k, v] of Object.entries(body)) { |
32 | if (v !== undefined && v !== "") { |
33 | formData.append(k, String(v)); |
34 | } |
35 | } |
36 | const response = await fetch(url, { |
37 | method: "PUT", |
38 | headers: { |
39 | "CF-WORKER-BODY-PART": CF_WORKER_BODY_PART, |
40 | "CF-WORKER-MAIN-MODULE-PART": CF_WORKER_MAIN_MODULE_PART, |
41 | "X-AUTH-EMAIL": auth.email, |
42 | "X-AUTH-KEY": auth.key, |
43 | Authorization: "Bearer " + auth.token, |
44 | }, |
45 | body: formData, |
46 | }); |
47 | if (!response.ok) { |
48 | const text = await response.text(); |
49 | throw new Error(`${response.status} ${text}`); |
50 | } |
51 | return await response.json(); |
52 | } |
53 |
|