wrangler 0.0.0-e2f9bb2 → 0.0.0-e305903a
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.
- package/Cloudflare_CA.pem +18 -0
- package/README.md +30 -4
- package/bin/wrangler.js +154 -34
- package/kv-asset-handler.js +1 -0
- package/miniflare-dist/index.mjs +1437 -21
- package/package.json +185 -148
- package/src/__tests__/api-dev.test.ts +209 -0
- package/src/__tests__/api-devregistry.test.js +56 -0
- package/src/__tests__/api.test.ts +80 -0
- package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
- package/src/__tests__/config-cache.test.ts +30 -24
- package/src/__tests__/configuration.test.ts +4121 -3114
- package/src/__tests__/dev.test.tsx +1331 -738
- package/src/__tests__/dialogs.test.tsx +40 -0
- package/src/__tests__/generate.test.ts +91 -0
- package/src/__tests__/guess-worker-format.test.ts +68 -68
- package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
- package/src/__tests__/helpers/mock-account-id.ts +24 -24
- package/src/__tests__/helpers/mock-bin.ts +20 -20
- package/src/__tests__/helpers/mock-cfetch.ts +199 -94
- package/src/__tests__/helpers/mock-console.ts +58 -39
- package/src/__tests__/helpers/mock-dialogs.ts +115 -51
- package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
- package/src/__tests__/helpers/mock-http-server.ts +30 -30
- package/src/__tests__/helpers/mock-istty.ts +65 -18
- package/src/__tests__/helpers/mock-known-routes.ts +7 -0
- package/src/__tests__/helpers/mock-kv.ts +26 -26
- package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
- package/src/__tests__/helpers/mock-process.ts +39 -0
- package/src/__tests__/helpers/mock-stdin.ts +82 -77
- package/src/__tests__/helpers/mock-web-socket.ts +21 -21
- package/src/__tests__/helpers/msw/handlers/index.ts +13 -0
- package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
- package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
- package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
- package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
- package/src/__tests__/helpers/msw/index.ts +4 -0
- package/src/__tests__/helpers/run-in-tmp.ts +27 -28
- package/src/__tests__/helpers/run-wrangler.ts +8 -8
- package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
- package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
- package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
- package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
- package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
- package/src/__tests__/helpers/write-worker-source.ts +16 -16
- package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
- package/src/__tests__/https-options.test.ts +142 -109
- package/src/__tests__/index.test.ts +231 -231
- package/src/__tests__/init.test.ts +2689 -1014
- package/src/__tests__/jest.setup.ts +147 -30
- package/src/__tests__/kv.test.ts +1311 -1094
- package/src/__tests__/logger.test.ts +100 -74
- package/src/__tests__/metrics.test.ts +450 -0
- package/src/__tests__/middleware.scheduled.test.ts +135 -0
- package/src/__tests__/middleware.test.ts +726 -0
- package/src/__tests__/package-manager.test.ts +312 -165
- package/src/__tests__/pages.test.ts +1988 -322
- package/src/__tests__/parse.test.ts +253 -245
- package/src/__tests__/paths.test.ts +39 -0
- package/src/__tests__/publish.test.ts +6955 -4743
- package/src/__tests__/pubsub.test.ts +367 -0
- package/src/__tests__/r2.test.ts +363 -206
- package/src/__tests__/route.test.ts +18 -18
- package/src/__tests__/secret.test.ts +624 -426
- package/src/__tests__/tail.test.ts +650 -565
- package/src/__tests__/test-old-node-version.js +31 -0
- package/src/__tests__/user.test.ts +140 -116
- package/src/__tests__/validate-dev-props.test.ts +56 -0
- package/src/__tests__/version.test.ts +35 -0
- package/src/__tests__/whoami.test.tsx +259 -91
- package/src/__tests__/worker-namespace.test.ts +319 -0
- package/src/abort.d.ts +3 -0
- package/src/api/dev.ts +206 -0
- package/src/api/index.ts +2 -0
- package/src/bundle-reporter.tsx +29 -0
- package/src/bundle.ts +721 -134
- package/src/cfetch/index.ts +83 -66
- package/src/cfetch/internal.ts +267 -90
- package/src/cli.ts +23 -7
- package/src/config/config.ts +236 -195
- package/src/config/diagnostics.ts +61 -61
- package/src/config/environment.ts +450 -339
- package/src/config/index.ts +258 -38
- package/src/config/validation-helpers.ts +379 -357
- package/src/config/validation.ts +1769 -1263
- package/src/config-cache.ts +81 -41
- package/src/create-worker-preview.ts +232 -132
- package/src/create-worker-upload-form.ts +285 -224
- package/src/d1/backups.tsx +212 -0
- package/src/d1/create.tsx +54 -0
- package/src/d1/delete.tsx +56 -0
- package/src/d1/execute.tsx +294 -0
- package/src/d1/formatTimeAgo.ts +14 -0
- package/src/d1/index.ts +75 -0
- package/src/d1/list.tsx +48 -0
- package/src/d1/options.ts +12 -0
- package/src/d1/types.tsx +14 -0
- package/src/d1/utils.ts +39 -0
- package/src/dev/dev-vars.ts +13 -13
- package/src/dev/dev.tsx +500 -353
- package/src/dev/get-local-persistence-path.tsx +31 -0
- package/src/dev/local.tsx +628 -290
- package/src/dev/remote.tsx +397 -197
- package/src/dev/start-server.ts +443 -0
- package/src/dev/use-esbuild.ts +173 -94
- package/src/dev/validate-dev-props.ts +31 -0
- package/src/dev-registry.tsx +190 -0
- package/src/dev.tsx +869 -0
- package/src/dialogs.tsx +134 -63
- package/src/dispatch-namespace.ts +206 -0
- package/src/durable.ts +102 -0
- package/src/entry.ts +248 -186
- package/src/environment-variables.ts +38 -23
- package/src/errors.ts +6 -6
- package/src/faye-websocket.d.ts +6 -0
- package/src/generate.ts +131 -0
- package/src/git-client.ts +42 -0
- package/src/global-wrangler-config-path.ts +26 -0
- package/src/https-options.ts +84 -80
- package/src/index.tsx +2288 -2534
- package/src/init.ts +967 -0
- package/src/inspect.ts +686 -562
- package/src/intl-polyfill.d.ts +123 -123
- package/src/is-ci.ts +14 -0
- package/src/is-interactive.ts +12 -0
- package/src/kv.ts +353 -242
- package/src/logger.ts +53 -39
- package/src/metrics/index.ts +5 -0
- package/src/metrics/metrics-config.ts +239 -0
- package/src/metrics/metrics-dispatcher.ts +96 -0
- package/src/metrics/metrics-usage-headers.ts +24 -0
- package/src/metrics/send-event.ts +93 -0
- package/src/miniflare-cli/assets.ts +215 -0
- package/src/miniflare-cli/index.ts +200 -33
- package/src/miniflare-cli/request-context.ts +18 -18
- package/src/module-collection.ts +212 -212
- package/src/open-in-browser.ts +5 -14
- package/src/package-manager.ts +182 -90
- package/src/pages/build.tsx +238 -0
- package/src/pages/constants.ts +16 -0
- package/src/pages/deployments.tsx +106 -0
- package/src/pages/dev.tsx +684 -0
- package/src/pages/errors.ts +66 -0
- package/src/pages/functions/buildPlugin.ts +110 -0
- package/src/pages/functions/buildWorker.ts +156 -0
- package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
- package/src/pages/functions/filepath-routing.ts +189 -0
- package/src/pages/functions/identifiers.ts +78 -0
- package/src/pages/functions/routes-consolidation.test.ts +250 -0
- package/src/pages/functions/routes-consolidation.ts +73 -0
- package/src/pages/functions/routes-transformation.test.ts +282 -0
- package/src/pages/functions/routes-transformation.ts +115 -0
- package/src/pages/functions/routes-validation.test.ts +403 -0
- package/src/pages/functions/routes-validation.ts +202 -0
- package/src/pages/functions/routes.ts +151 -0
- package/src/pages/functions.tsx +82 -0
- package/src/pages/hash.tsx +13 -0
- package/src/pages/index.tsx +94 -0
- package/src/pages/projects.tsx +169 -0
- package/src/pages/publish.tsx +419 -0
- package/src/pages/types.ts +49 -0
- package/src/pages/upload.tsx +398 -0
- package/src/pages/utils.ts +12 -0
- package/src/parse.ts +223 -120
- package/src/paths.ts +53 -8
- package/src/preview.ts +31 -0
- package/src/proxy.ts +435 -383
- package/src/publish.ts +837 -441
- package/src/pubsub/index.ts +286 -0
- package/src/pubsub/pubsub-commands.tsx +623 -0
- package/src/r2.ts +100 -19
- package/src/selfsigned.d.ts +23 -23
- package/src/sites.tsx +279 -200
- package/src/tail/filters.ts +108 -110
- package/src/tail/index.ts +234 -218
- package/src/tail/printing.ts +86 -46
- package/src/update-check.ts +11 -11
- package/src/user/choose-account.tsx +69 -0
- package/src/user/env-vars.ts +46 -0
- package/src/user/generate-auth-url.ts +33 -0
- package/src/user/generate-random-state.ts +16 -0
- package/src/user/index.ts +3 -0
- package/src/user/user.tsx +1192 -0
- package/src/whoami.tsx +141 -42
- package/src/worker.ts +163 -101
- package/src/zones.ts +167 -0
- package/templates/checked-fetch.js +17 -0
- package/templates/d1-beta-facade.js +174 -0
- package/templates/experimental-local-cache-stubs.js +27 -0
- package/templates/first-party-worker-module-facade.ts +18 -0
- package/templates/format-dev-errors.ts +32 -0
- package/templates/init-tests/test-jest-new-worker.js +25 -0
- package/templates/init-tests/test-vitest-new-worker.js +26 -0
- package/templates/middleware/common.ts +62 -0
- package/templates/middleware/loader-modules.ts +84 -0
- package/templates/middleware/loader-sw.ts +213 -0
- package/templates/middleware/middleware-pretty-error.ts +40 -0
- package/templates/middleware/middleware-scheduled.ts +15 -0
- package/templates/new-worker-scheduled.js +17 -0
- package/templates/new-worker-scheduled.ts +32 -0
- package/templates/new-worker.js +3 -3
- package/templates/new-worker.ts +18 -3
- package/templates/no-op-worker.js +10 -0
- package/templates/pages-dev-pipeline.ts +35 -0
- package/templates/pages-shim.ts +9 -0
- package/templates/pages-template-plugin.ts +167 -0
- package/templates/pages-template-worker.ts +172 -0
- package/templates/serve-static-assets.ts +63 -0
- package/templates/service-bindings-module-facade.js +54 -0
- package/templates/service-bindings-sw-facade.js +42 -0
- package/templates/tsconfig.json +95 -95
- package/wrangler-dist/cli.d.ts +841 -0
- package/wrangler-dist/cli.js +120834 -70331
- package/pages/functions/buildPlugin.ts +0 -92
- package/pages/functions/buildWorker.ts +0 -138
- package/pages/functions/filepath-routing.ts +0 -189
- package/pages/functions/identifiers.ts +0 -78
- package/pages/functions/routes.ts +0 -156
- package/pages/functions/template-plugin.ts +0 -146
- package/pages/functions/template-worker.ts +0 -143
- package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
- package/src/miniflare-cli/enum-keys.ts +0 -17
- package/src/pages.tsx +0 -1866
- package/src/user.tsx +0 -1193
- package/templates/static-asset-facade.js +0 -47
- package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
- package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
- package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
- package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
- package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
- package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
- package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
- package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
- package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
- package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
- package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
- package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
- package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
- package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
- package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
- package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
- package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
- package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
- package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
- package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
- package/vendor/wrangler-mime/CHANGELOG.md +0 -289
- package/vendor/wrangler-mime/LICENSE +0 -21
- package/vendor/wrangler-mime/Mime.js +0 -97
- package/vendor/wrangler-mime/README.md +0 -187
- package/vendor/wrangler-mime/cli.js +0 -46
- package/vendor/wrangler-mime/index.js +0 -4
- package/vendor/wrangler-mime/lite.js +0 -4
- package/vendor/wrangler-mime/package.json +0 -52
- package/vendor/wrangler-mime/types/other.js +0 -1
- package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/cfetch/index.ts
CHANGED
|
@@ -8,15 +8,16 @@ import type { RequestInit } from "undici";
|
|
|
8
8
|
export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
|
|
9
9
|
|
|
10
10
|
export interface FetchError {
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
code: number;
|
|
12
|
+
message: string;
|
|
13
|
+
error_chain?: FetchError[];
|
|
13
14
|
}
|
|
14
15
|
export interface FetchResult<ResponseType = unknown> {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
16
|
+
success: boolean;
|
|
17
|
+
result: ResponseType;
|
|
18
|
+
errors: FetchError[];
|
|
19
|
+
messages: string[];
|
|
20
|
+
result_info?: unknown;
|
|
20
21
|
}
|
|
21
22
|
|
|
22
23
|
export { fetchKVGetValue } from "./internal";
|
|
@@ -25,20 +26,22 @@ export { fetchKVGetValue } from "./internal";
|
|
|
25
26
|
* Make a fetch request, and extract the `result` from the JSON response.
|
|
26
27
|
*/
|
|
27
28
|
export async function fetchResult<ResponseType>(
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
resource: string,
|
|
30
|
+
init: RequestInit = {},
|
|
31
|
+
queryParams?: URLSearchParams,
|
|
32
|
+
abortSignal?: AbortSignal
|
|
31
33
|
): Promise<ResponseType> {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
34
|
+
const json = await fetchInternal<FetchResult<ResponseType>>(
|
|
35
|
+
resource,
|
|
36
|
+
init,
|
|
37
|
+
queryParams,
|
|
38
|
+
abortSignal
|
|
39
|
+
);
|
|
40
|
+
if (json.success) {
|
|
41
|
+
return json.result;
|
|
42
|
+
} else {
|
|
43
|
+
throwFetchError(resource, json);
|
|
44
|
+
}
|
|
42
45
|
}
|
|
43
46
|
|
|
44
47
|
/**
|
|
@@ -47,58 +50,72 @@ export async function fetchResult<ResponseType>(
|
|
|
47
50
|
* and repeating the request if the results are paginated.
|
|
48
51
|
*/
|
|
49
52
|
export async function fetchListResult<ResponseType>(
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
+
resource: string,
|
|
54
|
+
init: RequestInit = {},
|
|
55
|
+
queryParams?: URLSearchParams
|
|
53
56
|
): Promise<ResponseType[]> {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
57
|
+
const results: ResponseType[] = [];
|
|
58
|
+
let getMoreResults = true;
|
|
59
|
+
let cursor: string | undefined;
|
|
60
|
+
while (getMoreResults) {
|
|
61
|
+
if (cursor) {
|
|
62
|
+
queryParams = new URLSearchParams(queryParams);
|
|
63
|
+
queryParams.set("cursor", cursor);
|
|
64
|
+
}
|
|
65
|
+
const json = await fetchInternal<FetchResult<ResponseType[]>>(
|
|
66
|
+
resource,
|
|
67
|
+
init,
|
|
68
|
+
queryParams
|
|
69
|
+
);
|
|
70
|
+
if (json.success) {
|
|
71
|
+
results.push(...json.result);
|
|
72
|
+
if (hasCursor(json.result_info)) {
|
|
73
|
+
cursor = json.result_info?.cursor;
|
|
74
|
+
} else {
|
|
75
|
+
getMoreResults = false;
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
throwFetchError(resource, json);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return results;
|
|
79
82
|
}
|
|
80
83
|
|
|
81
84
|
function throwFetchError(
|
|
82
|
-
|
|
83
|
-
|
|
85
|
+
resource: string,
|
|
86
|
+
response: FetchResult<unknown>
|
|
84
87
|
): never {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
88
|
+
const error = new ParseError({
|
|
89
|
+
text: `A request to the Cloudflare API (${resource}) failed.`,
|
|
90
|
+
notes: response.errors.map((err) => ({
|
|
91
|
+
text: renderError(err),
|
|
92
|
+
})),
|
|
93
|
+
});
|
|
94
|
+
// add the first error code directly to this error
|
|
95
|
+
// so consumers can use it for specific behaviour
|
|
96
|
+
const code = response.errors[0]?.code;
|
|
97
|
+
if (code) {
|
|
98
|
+
//@ts-expect-error non-standard property on Error
|
|
99
|
+
error.code = code;
|
|
100
|
+
}
|
|
101
|
+
throw error;
|
|
99
102
|
}
|
|
100
103
|
|
|
101
104
|
function hasCursor(result_info: unknown): result_info is { cursor: string } {
|
|
102
|
-
|
|
103
|
-
|
|
105
|
+
const cursor = (result_info as { cursor: string } | undefined)?.cursor;
|
|
106
|
+
return cursor !== undefined && cursor !== null && cursor !== "";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function renderError(err: FetchError, level = 0): string {
|
|
110
|
+
const chainedMessages =
|
|
111
|
+
err.error_chain
|
|
112
|
+
?.map(
|
|
113
|
+
(chainedError) =>
|
|
114
|
+
`\n${" ".repeat(level)}- ${renderError(chainedError, level + 1)}`
|
|
115
|
+
)
|
|
116
|
+
.join("\n") ?? "";
|
|
117
|
+
return (
|
|
118
|
+
(err.code ? `${err.message} [code: ${err.code}]` : err.message) +
|
|
119
|
+
chainedMessages
|
|
120
|
+
);
|
|
104
121
|
}
|
package/src/cfetch/internal.ts
CHANGED
|
@@ -1,19 +1,61 @@
|
|
|
1
|
-
import
|
|
1
|
+
import assert from "node:assert";
|
|
2
|
+
import Busboy from "busboy";
|
|
3
|
+
import { fetch, File, FormData, Headers } from "undici";
|
|
4
|
+
import { version as wranglerVersion } from "../../package.json";
|
|
2
5
|
import { getEnvironmentVariableFactory } from "../environment-variables";
|
|
6
|
+
import { logger } from "../logger";
|
|
3
7
|
import { ParseError, parseJSON } from "../parse";
|
|
4
|
-
import {
|
|
8
|
+
import { loginOrRefreshIfRequired, requireApiToken } from "../user";
|
|
9
|
+
import type { ApiCredentials } from "../user";
|
|
5
10
|
import type { URLSearchParams } from "node:url";
|
|
6
|
-
import type { RequestInit, HeadersInit } from "undici";
|
|
11
|
+
import type { RequestInit, HeadersInit, Response } from "undici";
|
|
7
12
|
|
|
8
13
|
/**
|
|
9
14
|
* Get the URL to use to access the Cloudflare API.
|
|
10
15
|
*/
|
|
11
16
|
export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
17
|
+
variableName: "CLOUDFLARE_API_BASE_URL",
|
|
18
|
+
deprecatedName: "CF_API_BASE_URL",
|
|
19
|
+
defaultValue: "https://api.cloudflare.com/client/v4",
|
|
15
20
|
});
|
|
16
21
|
|
|
22
|
+
/*
|
|
23
|
+
* performApiFetch does everything required to make a CF API request,
|
|
24
|
+
* but doesn't parse the response as JSON. For normal V4 API responses,
|
|
25
|
+
* use `fetchInternal`
|
|
26
|
+
* */
|
|
27
|
+
export async function performApiFetch(
|
|
28
|
+
resource: string,
|
|
29
|
+
init: RequestInit = {},
|
|
30
|
+
queryParams?: URLSearchParams,
|
|
31
|
+
abortSignal?: AbortSignal
|
|
32
|
+
) {
|
|
33
|
+
const method = init.method ?? "GET";
|
|
34
|
+
assert(
|
|
35
|
+
resource.startsWith("/"),
|
|
36
|
+
`CF API fetch - resource path must start with a "/" but got "${resource}"`
|
|
37
|
+
);
|
|
38
|
+
await requireLoggedIn();
|
|
39
|
+
const apiToken = requireApiToken();
|
|
40
|
+
const headers = cloneHeaders(init.headers);
|
|
41
|
+
addAuthorizationHeaderIfUnspecified(headers, apiToken);
|
|
42
|
+
addUserAgent(headers);
|
|
43
|
+
|
|
44
|
+
const queryString = queryParams ? `?${queryParams.toString()}` : "";
|
|
45
|
+
logger.debug(
|
|
46
|
+
`-- START CF API REQUEST: ${method} ${getCloudflareAPIBaseURL()}${resource}${queryString}`
|
|
47
|
+
);
|
|
48
|
+
logger.debug("HEADERS:", JSON.stringify(headers, null, 2));
|
|
49
|
+
logger.debug("INIT:", JSON.stringify(init, null, 2));
|
|
50
|
+
logger.debug("-- END CF API REQUEST");
|
|
51
|
+
return await fetch(`${getCloudflareAPIBaseURL()}${resource}${queryString}`, {
|
|
52
|
+
method,
|
|
53
|
+
...init,
|
|
54
|
+
headers,
|
|
55
|
+
signal: abortSignal,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
17
59
|
/**
|
|
18
60
|
* Make a fetch request to the Cloudflare API.
|
|
19
61
|
*
|
|
@@ -24,86 +66,86 @@ export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
|
|
|
24
66
|
* This function should not be used directly, instead use the functions in `cfetch/index.ts`.
|
|
25
67
|
*/
|
|
26
68
|
export async function fetchInternal<ResponseType>(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
69
|
+
resource: string,
|
|
70
|
+
init: RequestInit = {},
|
|
71
|
+
queryParams?: URLSearchParams,
|
|
72
|
+
abortSignal?: AbortSignal
|
|
30
73
|
): Promise<ResponseType> {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
74
|
+
const method = init.method ?? "GET";
|
|
75
|
+
const response = await performApiFetch(
|
|
76
|
+
resource,
|
|
77
|
+
init,
|
|
78
|
+
queryParams,
|
|
79
|
+
abortSignal
|
|
80
|
+
);
|
|
81
|
+
const jsonText = await response.text();
|
|
82
|
+
logger.debug(
|
|
83
|
+
"-- START CF API RESPONSE:",
|
|
84
|
+
response.statusText,
|
|
85
|
+
response.status
|
|
86
|
+
);
|
|
87
|
+
logger.debug("HEADERS:", JSON.stringify(response.headers, null, 2));
|
|
88
|
+
logger.debug("RESPONSE:", jsonText);
|
|
89
|
+
logger.debug("-- END CF API RESPONSE");
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
return parseJSON<ResponseType>(jsonText);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
throw new ParseError({
|
|
95
|
+
text: "Received a malformed response from the API",
|
|
96
|
+
notes: [
|
|
97
|
+
{
|
|
98
|
+
text: truncate(jsonText, 100),
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
|
|
102
|
+
},
|
|
103
|
+
],
|
|
104
|
+
});
|
|
105
|
+
}
|
|
62
106
|
}
|
|
63
107
|
|
|
64
108
|
function truncate(text: string, maxLength: number): string {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
109
|
+
const { length } = text;
|
|
110
|
+
if (length <= maxLength) {
|
|
111
|
+
return text;
|
|
112
|
+
}
|
|
113
|
+
return `${text.substring(0, maxLength)}... (length = ${length})`;
|
|
70
114
|
}
|
|
71
115
|
|
|
72
116
|
function cloneHeaders(
|
|
73
|
-
|
|
117
|
+
headers: HeadersInit | undefined
|
|
74
118
|
): Record<string, string> {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
119
|
+
return headers instanceof Headers
|
|
120
|
+
? Object.fromEntries(headers.entries())
|
|
121
|
+
: Array.isArray(headers)
|
|
122
|
+
? Object.fromEntries(headers)
|
|
123
|
+
: { ...headers };
|
|
80
124
|
}
|
|
81
125
|
|
|
82
126
|
async function requireLoggedIn(): Promise<void> {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
127
|
+
const loggedIn = await loginOrRefreshIfRequired();
|
|
128
|
+
if (!loggedIn) {
|
|
129
|
+
throw new Error("Not logged in.");
|
|
130
|
+
}
|
|
87
131
|
}
|
|
88
132
|
|
|
89
|
-
function
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
133
|
+
function addAuthorizationHeaderIfUnspecified(
|
|
134
|
+
headers: Record<string, string>,
|
|
135
|
+
auth: ApiCredentials
|
|
136
|
+
): void {
|
|
137
|
+
if (!("Authorization" in headers)) {
|
|
138
|
+
if ("apiToken" in auth) {
|
|
139
|
+
headers["Authorization"] = `Bearer ${auth.apiToken}`;
|
|
140
|
+
} else {
|
|
141
|
+
headers["X-Auth-Key"] = auth.authKey;
|
|
142
|
+
headers["X-Auth-Email"] = auth.authEmail;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
95
145
|
}
|
|
96
146
|
|
|
97
|
-
function
|
|
98
|
-
|
|
99
|
-
apiToken: string
|
|
100
|
-
): void {
|
|
101
|
-
if ("Authorization" in headers) {
|
|
102
|
-
throw new Error(
|
|
103
|
-
"The request already specifies an authorisation header - cannot add a new one."
|
|
104
|
-
);
|
|
105
|
-
}
|
|
106
|
-
headers["Authorization"] = `Bearer ${apiToken}`;
|
|
147
|
+
function addUserAgent(headers: Record<string, string>): void {
|
|
148
|
+
headers["User-Agent"] = `wrangler/${wranglerVersion}`;
|
|
107
149
|
}
|
|
108
150
|
|
|
109
151
|
/**
|
|
@@ -112,26 +154,161 @@ function addAuthorizationHeader(
|
|
|
112
154
|
* doesn't return json. We inline the implementation and try not to share
|
|
113
155
|
* any code with the other calls. We should push back on any new APIs that
|
|
114
156
|
* try to introduce non-"standard" response structures.
|
|
157
|
+
*
|
|
158
|
+
* Note: any calls to fetchKVGetValue must call encodeURIComponent on key
|
|
159
|
+
* before passing it
|
|
115
160
|
*/
|
|
116
|
-
|
|
117
161
|
export async function fetchKVGetValue(
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
162
|
+
accountId: string,
|
|
163
|
+
namespaceId: string,
|
|
164
|
+
key: string
|
|
165
|
+
): Promise<ArrayBuffer> {
|
|
166
|
+
await requireLoggedIn();
|
|
167
|
+
const auth = requireApiToken();
|
|
168
|
+
const headers: Record<string, string> = {};
|
|
169
|
+
addAuthorizationHeaderIfUnspecified(headers, auth);
|
|
170
|
+
const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
|
|
171
|
+
const response = await fetch(resource, {
|
|
172
|
+
method: "GET",
|
|
173
|
+
headers,
|
|
174
|
+
});
|
|
175
|
+
if (response.ok) {
|
|
176
|
+
return await response.arrayBuffer();
|
|
177
|
+
} else {
|
|
178
|
+
throw new Error(
|
|
179
|
+
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The implementation for fetching a R2 object from Cloudflare API.
|
|
186
|
+
* We have a special implementation to handle the non-standard API response
|
|
187
|
+
* that doesn't return JSON, likely due to the streaming nature.
|
|
188
|
+
*
|
|
189
|
+
* note: The implementation should be called from light wrappers for
|
|
190
|
+
* different methods (GET, PUT)
|
|
191
|
+
*/
|
|
192
|
+
type ResponseWithBody = Response & { body: NonNullable<Response["body"]> };
|
|
193
|
+
export async function fetchR2Objects(
|
|
194
|
+
resource: string,
|
|
195
|
+
bodyInit: RequestInit = {}
|
|
196
|
+
): Promise<ResponseWithBody> {
|
|
197
|
+
await requireLoggedIn();
|
|
198
|
+
const auth = requireApiToken();
|
|
199
|
+
const headers = cloneHeaders(bodyInit.headers);
|
|
200
|
+
addAuthorizationHeaderIfUnspecified(headers, auth);
|
|
201
|
+
addUserAgent(headers);
|
|
202
|
+
|
|
203
|
+
const response = await fetch(`${getCloudflareAPIBaseURL()}${resource}`, {
|
|
204
|
+
...bodyInit,
|
|
205
|
+
headers,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
if (response.ok && response.body) {
|
|
209
|
+
return response as ResponseWithBody;
|
|
210
|
+
} else {
|
|
211
|
+
throw new Error(
|
|
212
|
+
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* This is a wrapper STOPGAP for getting the script which returns a raw text response.
|
|
219
|
+
*/
|
|
220
|
+
export async function fetchDashboardScript(
|
|
221
|
+
resource: string,
|
|
222
|
+
bodyInit: RequestInit = {}
|
|
121
223
|
): Promise<string> {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
224
|
+
await requireLoggedIn();
|
|
225
|
+
const auth = requireApiToken();
|
|
226
|
+
const headers = cloneHeaders(bodyInit.headers);
|
|
227
|
+
addAuthorizationHeaderIfUnspecified(headers, auth);
|
|
228
|
+
addUserAgent(headers);
|
|
229
|
+
|
|
230
|
+
const response = await fetch(`${getCloudflareAPIBaseURL()}${resource}`, {
|
|
231
|
+
...bodyInit,
|
|
232
|
+
headers,
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
if (!response.ok || !response.body) {
|
|
236
|
+
throw new Error(
|
|
237
|
+
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const usesModules = response.headers
|
|
242
|
+
.get("content-type")
|
|
243
|
+
?.startsWith("multipart");
|
|
244
|
+
|
|
245
|
+
if (usesModules) {
|
|
246
|
+
// Response from edge contains generic "name = worker.js" for dashboard created scripts
|
|
247
|
+
const form = await formData(response);
|
|
248
|
+
const entries = Array.from(form.entries());
|
|
249
|
+
if (entries.length > 1)
|
|
250
|
+
throw new RangeError("Expected only one entry in multipart response");
|
|
251
|
+
const [_, file] = entries[0];
|
|
252
|
+
|
|
253
|
+
if (file instanceof File) {
|
|
254
|
+
return await file.text();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return file ?? "";
|
|
258
|
+
|
|
259
|
+
// Follow up on issue in Undici about multipart/form-data support & replace the workaround: https://github.com/nodejs/undici/issues/974
|
|
260
|
+
// This should be using a builtin formData() parser pattern.
|
|
261
|
+
} else {
|
|
262
|
+
return response.text();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function formData({ headers, body }: Response): Promise<FormData> {
|
|
267
|
+
// undici doesn't include a multipart/form-data parser yet, so we parse
|
|
268
|
+
// form data with busboy instead
|
|
269
|
+
const contentType = headers.get("Content-Type") ?? "";
|
|
270
|
+
if (!/multipart\/form-data/.test(contentType))
|
|
271
|
+
throw Error("Need Content-Type for multipart/form-data");
|
|
272
|
+
|
|
273
|
+
const responseFormData = new FormData();
|
|
274
|
+
|
|
275
|
+
let busboy: Busboy.Busboy;
|
|
276
|
+
|
|
277
|
+
const parsedHeaders = Object.fromEntries(
|
|
278
|
+
Array.from(headers).map(([header, value]) => [header.toLowerCase(), value])
|
|
279
|
+
);
|
|
280
|
+
try {
|
|
281
|
+
busboy = Busboy({ headers: parsedHeaders });
|
|
282
|
+
} catch (err) {
|
|
283
|
+
// Error due to headers:
|
|
284
|
+
throw Object.assign(new TypeError(), { cause: err });
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
busboy.on("field", (name, value) => {
|
|
288
|
+
responseFormData.append(name, value);
|
|
289
|
+
});
|
|
290
|
+
busboy.on("file", (name, value, info) => {
|
|
291
|
+
const { filename, encoding, mimeType } = info;
|
|
292
|
+
const base64 = encoding.toLowerCase() === "base64";
|
|
293
|
+
const chunks: Buffer[] = [];
|
|
294
|
+
value.on("data", (chunk) => {
|
|
295
|
+
if (base64) chunk = Buffer.from(chunk.toString(), "base64");
|
|
296
|
+
chunks.push(chunk);
|
|
297
|
+
});
|
|
298
|
+
value.on("end", () => {
|
|
299
|
+
const file = new File(chunks, filename, { type: mimeType });
|
|
300
|
+
responseFormData.append(name, file);
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
const busboyResolve = new Promise((resolve, reject) => {
|
|
305
|
+
busboy.on("finish", resolve);
|
|
306
|
+
busboy.on("error", (err) => reject(err));
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
if (body !== null) for await (const chunk of body) busboy.write(chunk);
|
|
310
|
+
busboy.end();
|
|
311
|
+
await busboyResolve;
|
|
312
|
+
|
|
313
|
+
return responseFormData;
|
|
137
314
|
}
|
package/src/cli.ts
CHANGED
|
@@ -1,13 +1,29 @@
|
|
|
1
1
|
import "dotenv/config"; // Grab locally specified env params from a `.env` file.
|
|
2
2
|
import process from "process";
|
|
3
3
|
import { hideBin } from "yargs/helpers";
|
|
4
|
+
import { unstable_dev } from "./api";
|
|
4
5
|
import { FatalError } from "./errors";
|
|
5
6
|
import { main } from ".";
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
8
|
+
import type { UnstableDevWorker } from "./api";
|
|
9
|
+
/**
|
|
10
|
+
* The main entrypoint for the CLI.
|
|
11
|
+
* main only gets called when the script is run directly, not when it's imported as a module.
|
|
12
|
+
*/
|
|
13
|
+
if (typeof jest === "undefined" && require.main) {
|
|
14
|
+
main(hideBin(process.argv)).catch((e) => {
|
|
15
|
+
// The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
|
|
16
|
+
// Here we just want to ensure that the process exits with a non-zero code.
|
|
17
|
+
// We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
|
|
18
|
+
const exitCode = (e instanceof FatalError && e.code) || 1;
|
|
19
|
+
process.exit(exitCode);
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* This is how we're exporting the API.
|
|
25
|
+
* It makes it possible to import wrangler from 'wrangler',
|
|
26
|
+
* and call wrangler.unstable_dev().
|
|
27
|
+
*/
|
|
28
|
+
export { unstable_dev };
|
|
29
|
+
export type { UnstableDevWorker };
|