wrangler 0.0.0-e1c615f → 0.0.0-e3cab74

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 (85) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +28 -13
  3. package/pages/functions/buildWorker.ts +6 -1
  4. package/pages/functions/filepath-routing.test.ts +112 -28
  5. package/pages/functions/filepath-routing.ts +88 -131
  6. package/pages/functions/routes.ts +11 -18
  7. package/pages/functions/template-worker.ts +21 -28
  8. package/src/__tests__/configuration.test.ts +2185 -0
  9. package/src/__tests__/dev.test.tsx +56 -9
  10. package/src/__tests__/guess-worker-format.test.ts +66 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +53 -17
  17. package/src/__tests__/helpers/mock-console.ts +62 -0
  18. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  19. package/src/__tests__/helpers/mock-kv.ts +40 -0
  20. package/src/__tests__/helpers/mock-user.ts +27 -0
  21. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  22. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  23. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  24. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  25. package/src/__tests__/index.test.ts +655 -76
  26. package/src/__tests__/jest.setup.ts +37 -2
  27. package/src/__tests__/kv.test.ts +441 -398
  28. package/src/__tests__/logout.test.ts +50 -0
  29. package/src/__tests__/package-manager.test.ts +206 -0
  30. package/src/__tests__/parse.test.ts +322 -0
  31. package/src/__tests__/publish.test.ts +2406 -0
  32. package/src/__tests__/r2.test.ts +198 -0
  33. package/src/__tests__/secret.test.ts +326 -0
  34. package/src/__tests__/sentry.test.ts +146 -0
  35. package/src/__tests__/tail.test.ts +564 -0
  36. package/src/__tests__/whoami.test.tsx +86 -0
  37. package/src/api/form_data.ts +112 -26
  38. package/src/api/preview.ts +34 -15
  39. package/src/api/worker.ts +58 -27
  40. package/src/bundle.ts +133 -0
  41. package/src/cfetch/index.ts +21 -19
  42. package/src/cfetch/internal.ts +85 -21
  43. package/src/cli.ts +10 -0
  44. package/src/config/README.md +107 -0
  45. package/src/config/config.ts +265 -0
  46. package/src/config/diagnostics.ts +80 -0
  47. package/src/config/environment.ts +305 -0
  48. package/src/config/index.ts +52 -0
  49. package/src/config/validation-helpers.ts +370 -0
  50. package/src/config/validation.ts +1017 -0
  51. package/src/dev.tsx +455 -368
  52. package/src/dialogs.tsx +2 -2
  53. package/src/entry.ts +57 -0
  54. package/src/environment-variables.ts +33 -0
  55. package/src/guess-worker-format.ts +68 -0
  56. package/src/index.tsx +1044 -646
  57. package/src/inspect.ts +609 -0
  58. package/src/kv.tsx +47 -39
  59. package/src/module-collection.ts +142 -36
  60. package/src/open-in-browser.ts +13 -0
  61. package/src/package-manager.ts +126 -0
  62. package/src/pages.tsx +139 -62
  63. package/src/parse.ts +183 -0
  64. package/src/paths.ts +26 -0
  65. package/src/proxy.ts +350 -77
  66. package/src/publish.ts +307 -289
  67. package/src/r2.ts +50 -0
  68. package/src/reporting.ts +115 -0
  69. package/src/sites.tsx +183 -56
  70. package/src/tail/filters.ts +279 -0
  71. package/src/tail/index.ts +299 -0
  72. package/src/tail/printing.ts +62 -0
  73. package/src/user.tsx +137 -110
  74. package/src/whoami.tsx +69 -0
  75. package/templates/new-worker.js +15 -0
  76. package/templates/new-worker.ts +15 -0
  77. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  78. package/templates/tsconfig.json +105 -0
  79. package/wrangler-dist/cli.js +127861 -111486
  80. package/wrangler-dist/cli.js.map +3 -3
  81. package/src/__tests__/run-in-tmp.ts +0 -19
  82. package/src/__tests__/run-wrangler.ts +0 -32
  83. package/src/api/inspect.ts +0 -430
  84. package/src/config.ts +0 -131
  85. package/src/tail.tsx +0 -73
@@ -1,10 +1,10 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { FormData, File } from "undici";
1
3
  import type {
2
4
  CfWorkerInit,
3
5
  CfModuleType,
4
- CfModule,
5
6
  CfDurableObjectMigrations,
6
7
  } from "./worker.js";
7
- import { FormData, Blob } from "formdata-node";
8
8
 
9
9
  export function toMimeType(type: CfModuleType): string {
10
10
  switch (type) {
@@ -23,14 +23,11 @@ export function toMimeType(type: CfModuleType): string {
23
23
  }
24
24
  }
25
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
- interface WorkerMetadata {
26
+ export interface WorkerMetadata {
27
+ /** The name of the entry point module. Only exists when the worker is in the ES module format */
28
+ main_module?: string;
29
+ /** The name of the entry point module. Only exists when the worker is in the Service Worker format */
30
+ body_part?: string;
34
31
  compatibility_date?: string;
35
32
  compatibility_flags?: string[];
36
33
  usage_model?: "bundled" | "unbound";
@@ -38,18 +35,16 @@ interface WorkerMetadata {
38
35
  bindings: (
39
36
  | { type: "kv_namespace"; name: string; namespace_id: string }
40
37
  | { type: "plain_text"; name: string; text: string }
38
+ | { type: "json"; name: string; json: unknown }
39
+ | { type: "wasm_module"; name: string; part: string }
40
+ | { type: "text_blob"; name: string; part: string }
41
41
  | {
42
42
  type: "durable_object_namespace";
43
43
  name: string;
44
44
  class_name: string;
45
45
  script_name?: string;
46
46
  }
47
- | {
48
- type: "service";
49
- name: string;
50
- service: string;
51
- environment: string;
52
- }
47
+ | { type: "r2_bucket"; name: string; bucket_name: string }
53
48
  )[];
54
49
  }
55
50
 
@@ -60,7 +55,6 @@ export function toFormData(worker: CfWorkerInit): FormData {
60
55
  const formData = new FormData();
61
56
  const {
62
57
  main,
63
- modules,
64
58
  bindings,
65
59
  migrations,
66
60
  usage_model,
@@ -68,6 +62,8 @@ export function toFormData(worker: CfWorkerInit): FormData {
68
62
  compatibility_flags,
69
63
  } = worker;
70
64
 
65
+ let { modules } = worker;
66
+
71
67
  const metadataBindings: WorkerMetadata["bindings"] = [];
72
68
 
73
69
  bindings.kv_namespaces?.forEach(({ id, binding }) => {
@@ -89,18 +85,105 @@ export function toFormData(worker: CfWorkerInit): FormData {
89
85
  }
90
86
  );
91
87
 
88
+ bindings.r2_buckets?.forEach(({ binding, bucket_name }) => {
89
+ metadataBindings.push({
90
+ name: binding,
91
+ type: "r2_bucket",
92
+ bucket_name,
93
+ });
94
+ });
95
+
92
96
  Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
93
- metadataBindings.push({ name: key, type: "plain_text", text: value });
97
+ if (typeof value === "string") {
98
+ metadataBindings.push({ name: key, type: "plain_text", text: value });
99
+ } else {
100
+ metadataBindings.push({ name: key, type: "json", json: value });
101
+ }
94
102
  });
95
103
 
96
- bindings.services?.forEach(({ name, service, environment }) => {
104
+ for (const [name, filePath] of Object.entries(bindings.wasm_modules || {})) {
97
105
  metadataBindings.push({
98
106
  name,
99
- type: "service",
100
- service,
101
- environment,
107
+ type: "wasm_module",
108
+ part: name,
102
109
  });
103
- });
110
+
111
+ formData.set(
112
+ name,
113
+ new File([readFileSync(filePath)], filePath, {
114
+ type: "application/wasm",
115
+ })
116
+ );
117
+ }
118
+
119
+ for (const [name, filePath] of Object.entries(bindings.text_blobs || {})) {
120
+ metadataBindings.push({
121
+ name,
122
+ type: "text_blob",
123
+ part: name,
124
+ });
125
+
126
+ if (name !== "__STATIC_CONTENT_MANIFEST") {
127
+ formData.set(
128
+ name,
129
+ new File([readFileSync(filePath)], filePath, {
130
+ type: "text/plain",
131
+ })
132
+ );
133
+ }
134
+ }
135
+
136
+ if (main.type === "commonjs") {
137
+ // This is a service-worker format worker.
138
+ for (const module of Object.values([...(modules || [])])) {
139
+ if (module.name === "__STATIC_CONTENT_MANIFEST") {
140
+ // Add the manifest to the form data.
141
+ formData.set(
142
+ module.name,
143
+ new File([module.content], module.name, {
144
+ type: "text/plain",
145
+ })
146
+ );
147
+ // And then remove it from the modules collection
148
+ modules = modules?.filter((m) => m !== module);
149
+ } else if (module.type === "compiled-wasm" || module.type === "text") {
150
+ // Convert all wasm/text modules into `wasm_module`/`text_blob` bindings.
151
+ // The "name" of the module is a file path. We use it
152
+ // to instead be a "part" of the body, and a reference
153
+ // that we can use inside our source. This identifier has to be a valid
154
+ // JS identifier, so we replace all non alphanumeric characters
155
+ // with an underscore.
156
+ const name = module.name.replace(/[^a-zA-Z0-9_$]/g, "_");
157
+ metadataBindings.push({
158
+ name,
159
+ type: module.type === "compiled-wasm" ? "wasm_module" : "text_blob",
160
+ part: name,
161
+ });
162
+
163
+ // Add the module to the form data.
164
+ formData.set(
165
+ name,
166
+ new File([module.content], module.name, {
167
+ type:
168
+ module.type === "compiled-wasm"
169
+ ? "application/wasm"
170
+ : "text/plain",
171
+ })
172
+ );
173
+ // And then remove it from the modules collection
174
+ modules = modules?.filter((m) => m !== module);
175
+ } else if (module.type === "buffer") {
176
+ throw new Error(
177
+ 'The "buffer" module type is not yet supported in service worker format workers'
178
+ );
179
+ }
180
+ }
181
+ }
182
+
183
+ if (bindings.unsafe) {
184
+ // @ts-expect-error unsafe bindings don't need to match a specific type here
185
+ metadataBindings.push(...bindings.unsafe);
186
+ }
104
187
 
105
188
  const metadata: WorkerMetadata = {
106
189
  ...(main.type !== "commonjs"
@@ -122,9 +205,12 @@ export function toFormData(worker: CfWorkerInit): FormData {
122
205
  }
123
206
 
124
207
  for (const module of [main].concat(modules || [])) {
125
- const { name } = module;
126
- const blob = toModule(module, main.type ?? "esm");
127
- formData.set(name, blob, name);
208
+ formData.set(
209
+ module.name,
210
+ new File([module.content], module.name, {
211
+ type: toMimeType(module.type ?? main.type ?? "esm"),
212
+ })
213
+ );
128
214
  }
129
215
 
130
216
  return formData;
@@ -1,7 +1,8 @@
1
- import fetch from "node-fetch";
1
+ import { URL } from "node:url";
2
+ import { fetch } from "undici";
2
3
  import { fetchResult } from "../cfetch";
3
4
  import { toFormData } from "./form_data";
4
- import type { CfAccount, CfWorkerInit } from "./worker";
5
+ import type { CfAccount, CfWorkerContext, CfWorkerInit } from "./worker";
5
6
 
6
7
  /**
7
8
  * A preview mode.
@@ -54,10 +55,13 @@ export interface CfPreviewToken {
54
55
  /**
55
56
  * Generates a preview session token.
56
57
  */
57
- async function sessionToken(account: CfAccount): Promise<CfPreviewToken> {
58
- const { accountId, zoneId } = account;
59
- const initUrl = zoneId
60
- ? `/zones/${zoneId}/workers/edge-preview`
58
+ async function sessionToken(
59
+ account: CfAccount,
60
+ ctx: CfWorkerContext
61
+ ): Promise<CfPreviewToken> {
62
+ const { accountId } = account;
63
+ const initUrl = ctx.zone
64
+ ? `/zones/${ctx.zone}/workers/edge-preview`
61
65
  : `/accounts/${accountId}/workers/subdomain/edge-preview`;
62
66
 
63
67
  const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
@@ -91,15 +95,22 @@ function randomId(): string {
91
95
  */
92
96
  export async function previewToken(
93
97
  account: CfAccount,
94
- worker: CfWorkerInit
98
+ worker: CfWorkerInit,
99
+ ctx: CfWorkerContext
95
100
  ): Promise<CfPreviewToken> {
96
- const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(account);
101
+ const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(
102
+ account,
103
+ ctx
104
+ );
97
105
 
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`;
106
+ const { accountId } = account;
107
+ const scriptId = ctx.zone ? randomId() : worker.name || host.split(".")[0];
108
+ const url =
109
+ ctx.env && !ctx.legacyEnv
110
+ ? `/accounts/${accountId}/workers/services/${scriptId}/environments/${ctx.env}/edge-preview`
111
+ : `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
101
112
 
102
- const mode: CfPreviewMode = zoneId
113
+ const mode: CfPreviewMode = ctx.zone
103
114
  ? { routes: ["*/*"] }
104
115
  : { workers_dev: true };
105
116
 
@@ -108,7 +119,6 @@ export async function previewToken(
108
119
 
109
120
  const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
110
121
  method: "POST",
111
- // @ts-expect-error TODO: fix this
112
122
  body: formData,
113
123
  headers: {
114
124
  "cf-preview-upload-config-token": value,
@@ -119,8 +129,17 @@ export async function previewToken(
119
129
  value: preview_token,
120
130
  // TODO: verify this works with zoned workers
121
131
  host:
122
- worker.name && !zoneId
123
- ? `${worker.name}.${host.split(".").slice(1).join(".")}`
132
+ worker.name && !ctx.zone
133
+ ? // hrmm this might need change as well
134
+ `${
135
+ worker.name
136
+ // TODO: this should also probably have the env prefix
137
+ // but it doesn't appear to work yet, instead giving us the
138
+ // "There is nothing here yet" screen
139
+ // ctx.env && !ctx.legacyEnv
140
+ // ? `${ctx.env}.${worker.name}`
141
+ // : worker.name
142
+ }.${host.split(".").slice(1).join(".")}`
124
143
  : host,
125
144
  inspectorUrl,
126
145
  prewarmUrl,
package/src/api/worker.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { CfPreviewToken } from "./preview";
1
+ import { fetch } from "undici";
2
2
  import { previewToken } from "./preview";
3
- import fetch from "node-fetch";
3
+ import type { CfPreviewToken } from "./preview";
4
4
 
5
5
  /**
6
6
  * A Cloudflare account.
@@ -16,12 +16,13 @@ export interface CfAccount {
16
16
  * An account ID.
17
17
  */
18
18
  accountId: string;
19
- /**
20
- * A zone ID, only required if not using `workers.dev`.
21
- */
22
- zoneId?: string;
23
19
  }
24
20
 
21
+ /**
22
+ * The type of Worker
23
+ */
24
+ export type CfScriptFormat = "modules" | "service-worker";
25
+
25
26
  /**
26
27
  * A module type.
27
28
  */
@@ -53,7 +54,7 @@ export interface CfModule {
53
54
  * }
54
55
  * }
55
56
  */
56
- content: string | BufferSource;
57
+ content: string | Buffer;
57
58
  /**
58
59
  * The module type.
59
60
  *
@@ -66,7 +67,7 @@ export interface CfModule {
66
67
  * A map of variable names to values.
67
68
  */
68
69
  interface CfVars {
69
- [key: string]: string;
70
+ [key: string]: unknown;
70
71
  }
71
72
 
72
73
  /**
@@ -77,6 +78,22 @@ interface CfKvNamespace {
77
78
  id: string;
78
79
  }
79
80
 
81
+ /**
82
+ * A binding to a wasm module (in service worker format)
83
+ */
84
+
85
+ interface CfWasmModuleBindings {
86
+ [key: string]: string;
87
+ }
88
+
89
+ /**
90
+ * A binding to a text blob (in service worker format)
91
+ */
92
+
93
+ interface CfTextBlobBindings {
94
+ [key: string]: string;
95
+ }
96
+
80
97
  /**
81
98
  * A Durable Object.
82
99
  */
@@ -86,13 +103,14 @@ interface CfDurableObject {
86
103
  script_name?: string;
87
104
  }
88
105
 
89
- /**
90
- * A Service.
91
- */
92
- interface CfService {
106
+ interface CfR2Bucket {
107
+ binding: string;
108
+ bucket_name: string;
109
+ }
110
+
111
+ interface CfUnsafeBinding {
93
112
  name: string;
94
- service: string;
95
- environment: string;
113
+ type: string;
96
114
  }
97
115
 
98
116
  export interface CfDurableObjectMigrations {
@@ -100,7 +118,10 @@ export interface CfDurableObjectMigrations {
100
118
  new_tag: string;
101
119
  steps: {
102
120
  new_classes?: string[];
103
- renamed_classes?: string[];
121
+ renamed_classes?: {
122
+ from: string;
123
+ to: string;
124
+ }[];
104
125
  deleted_classes?: string[];
105
126
  }[];
106
127
  }
@@ -112,7 +133,7 @@ export interface CfWorkerInit {
112
133
  /**
113
134
  * The name of the worker.
114
135
  */
115
- name: string | void;
136
+ name: string | undefined;
116
137
  /**
117
138
  * The entrypoint module.
118
139
  */
@@ -120,20 +141,29 @@ export interface CfWorkerInit {
120
141
  /**
121
142
  * The list of additional modules.
122
143
  */
123
- modules: void | CfModule[];
144
+ modules: undefined | CfModule[];
124
145
  /**
125
146
  * All the bindings
126
147
  */
127
148
  bindings: {
128
- kv_namespaces?: CfKvNamespace[];
129
- durable_objects?: { bindings: CfDurableObject[] };
130
- vars?: CfVars;
131
- services?: CfService[];
149
+ vars: CfVars | undefined;
150
+ kv_namespaces: CfKvNamespace[] | undefined;
151
+ wasm_modules: CfWasmModuleBindings | undefined;
152
+ text_blobs: CfTextBlobBindings | undefined;
153
+ durable_objects: { bindings: CfDurableObject[] } | undefined;
154
+ r2_buckets: CfR2Bucket[] | undefined;
155
+ unsafe: CfUnsafeBinding[] | undefined;
132
156
  };
133
- migrations: void | CfDurableObjectMigrations;
134
- compatibility_date: string | void;
135
- compatibility_flags: void | string[];
136
- usage_model: void | "bundled" | "unbound";
157
+ migrations: undefined | CfDurableObjectMigrations;
158
+ compatibility_date: string | undefined;
159
+ compatibility_flags: undefined | string[];
160
+ usage_model: undefined | "bundled" | "unbound";
161
+ }
162
+
163
+ export interface CfWorkerContext {
164
+ env: string | undefined;
165
+ legacyEnv: boolean | undefined;
166
+ zone: string | undefined;
137
167
  }
138
168
 
139
169
  /**
@@ -144,9 +174,10 @@ export interface CfWorkerInit {
144
174
  */
145
175
  export async function createWorker(
146
176
  init: CfWorkerInit,
147
- account: CfAccount
177
+ account: CfAccount,
178
+ ctx: CfWorkerContext
148
179
  ): Promise<CfPreviewToken> {
149
- const token = await previewToken(account, init);
180
+ const token = await previewToken(account, init, ctx);
150
181
  const response = await fetch(token.prewarmUrl.href, { method: "POST" });
151
182
  if (!response.ok) {
152
183
  // console.error("worker failed to prewarm: ", response.statusText);
package/src/bundle.ts ADDED
@@ -0,0 +1,133 @@
1
+ import assert from "node:assert";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import * as esbuild from "esbuild";
5
+ import makeModuleCollector from "./module-collection";
6
+ import type { CfModule, CfScriptFormat } from "./api/worker";
7
+ import type { Config } from "./config";
8
+ import type { Entry } from "./entry";
9
+
10
+ type BundleResult = {
11
+ modules: CfModule[];
12
+ resolvedEntryPointPath: string;
13
+ bundleType: "esm" | "commonjs";
14
+ stop: (() => void) | undefined;
15
+ };
16
+
17
+ /**
18
+ * Generate a bundle for the worker identified by the arguments passed in.
19
+ */
20
+ export async function bundleWorker(
21
+ entry: Entry,
22
+ destination: string,
23
+ options: {
24
+ serveAssetsFromWorker: boolean;
25
+ jsxFactory: string | undefined;
26
+ jsxFragment: string | undefined;
27
+ format: CfScriptFormat;
28
+ rules: Config["rules"];
29
+ watch?: esbuild.WatchMode;
30
+ }
31
+ ): Promise<BundleResult> {
32
+ const {
33
+ serveAssetsFromWorker,
34
+ jsxFactory,
35
+ jsxFragment,
36
+ format,
37
+ rules,
38
+ watch,
39
+ } = options;
40
+ const moduleCollector = makeModuleCollector({ format, rules });
41
+ const result = await esbuild.build({
42
+ ...getEntryPoint(entry.file, serveAssetsFromWorker),
43
+ bundle: true,
44
+ absWorkingDir: entry.directory,
45
+ outdir: destination,
46
+ external: ["__STATIC_CONTENT_MANIFEST"],
47
+ format: "esm",
48
+ sourcemap: true,
49
+ metafile: true,
50
+ conditions: ["worker", "browser"],
51
+ loader: {
52
+ ".js": "jsx",
53
+ ".mjs": "jsx",
54
+ ".cjs": "jsx",
55
+ },
56
+ plugins: [moduleCollector.plugin],
57
+ ...(jsxFactory && { jsxFactory }),
58
+ ...(jsxFragment && { jsxFragment }),
59
+ watch,
60
+ });
61
+
62
+ const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
63
+ ([_path, output]) => output.entryPoint !== undefined
64
+ );
65
+ assert(
66
+ entryPointOutputs.length > 0,
67
+ `Cannot find entry-point "${entry.file}" in generated bundle.` +
68
+ listEntryPoints(entryPointOutputs)
69
+ );
70
+ assert(
71
+ entryPointOutputs.length < 2,
72
+ "More than one entry-point found for generated bundle." +
73
+ listEntryPoints(entryPointOutputs)
74
+ );
75
+
76
+ const entryPointExports = entryPointOutputs[0][1].exports;
77
+ const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
78
+
79
+ return {
80
+ modules: moduleCollector.modules,
81
+ resolvedEntryPointPath: path.resolve(
82
+ entry.directory,
83
+ entryPointOutputs[0][0]
84
+ ),
85
+ bundleType,
86
+ stop: result.stop,
87
+ };
88
+ }
89
+
90
+ type EntryPoint =
91
+ | { stdin: esbuild.StdinOptions; nodePaths: string[] }
92
+ | { entryPoints: string[] };
93
+
94
+ /**
95
+ * Create an object that describes the entry point for esbuild.
96
+ *
97
+ * If we are using the experimental asset handling, then the entry point is
98
+ * actually a shim worker that will either return an asset from a KV store,
99
+ * or delegate to the actual worker.
100
+ */
101
+ function getEntryPoint(
102
+ entryFile: string,
103
+ serveAssetsFromWorker: boolean
104
+ ): EntryPoint {
105
+ if (serveAssetsFromWorker) {
106
+ return {
107
+ stdin: {
108
+ contents: fs
109
+ .readFileSync(
110
+ path.join(__dirname, "../templates/static-asset-facade.js"),
111
+ "utf8"
112
+ )
113
+ .replace("__ENTRY_POINT__", entryFile),
114
+ sourcefile: "static-asset-facade.js",
115
+ resolveDir: path.dirname(entryFile),
116
+ },
117
+ nodePaths: [path.join(__dirname, "../vendor")],
118
+ };
119
+ } else {
120
+ return { entryPoints: [entryFile] };
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Generate a string that describes the entry-points that were identified by esbuild.
126
+ */
127
+ function listEntryPoints(
128
+ outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
129
+ ): string {
130
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
131
+ }
132
+
133
+ type ValueOf<T> = T[keyof T];
@@ -1,10 +1,11 @@
1
- import type { RequestInit } from "node-fetch";
2
- import { URLSearchParams } from "url";
1
+ import { URLSearchParams } from "node:url";
2
+ import { ParseError } from "../parse";
3
3
  import { fetchInternal } from "./internal";
4
+ import type { RequestInit } from "undici";
4
5
 
5
6
  // Check out https://api.cloudflare.com/ for API docs.
6
7
 
7
- export { CF_API_BASE_URL } from "./internal";
8
+ export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
8
9
 
9
10
  export interface FetchError {
10
11
  code: number;
@@ -18,16 +19,7 @@ export interface FetchResult<ResponseType = unknown> {
18
19
  result_info?: unknown;
19
20
  }
20
21
 
21
- /**
22
- * Make a fetch request for a raw JSON value.
23
- */
24
- export async function fetchRaw<ResponseType>(
25
- resource: string,
26
- init: RequestInit = {},
27
- queryParams?: URLSearchParams
28
- ): Promise<ResponseType> {
29
- return fetchInternal<ResponseType>(resource, init, queryParams);
30
- }
22
+ export { fetchKVGetValue } from "./internal";
31
23
 
32
24
  /**
33
25
  * Make a fetch request, and extract the `result` from the JSON response.
@@ -90,13 +82,23 @@ function throwFetchError(
90
82
  resource: string,
91
83
  response: FetchResult<unknown>
92
84
  ): never {
93
- response.messages.forEach((message) => console.warn(message));
94
- const errors = response.errors
95
- .map((error) => `${error.code}: ${error.message}`)
96
- .join("\n");
97
- throw new Error(`Failed to fetch ${resource} - ${errors}`);
85
+ const error = new ParseError({
86
+ text: "Received a bad response from the API",
87
+ notes: response.errors.map((err) => ({
88
+ text: err.code ? `${err.message} [code: ${err.code}]` : err.message,
89
+ })),
90
+ });
91
+ // add the first error code directly to this error
92
+ // so consumers can use it for specific behaviour
93
+ const code = response.errors[0]?.code;
94
+ if (code) {
95
+ //@ts-expect-error non-standard property on Error
96
+ error.code = code;
97
+ }
98
+ throw error;
98
99
  }
99
100
 
100
101
  function hasCursor(result_info: unknown): result_info is { cursor: string } {
101
- return (result_info as { cursor } | undefined)?.cursor !== undefined;
102
+ const cursor = (result_info as { cursor: string } | undefined)?.cursor;
103
+ return cursor !== undefined && cursor !== null && cursor !== "";
102
104
  }