wrangler 0.0.0-e61fba8 → 0.0.0-e640ed9d

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 (152) hide show
  1. package/README.md +29 -11
  2. package/bin/wrangler.js +86 -67
  3. package/config-schema.json +2947 -0
  4. package/package.json +114 -79
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +30 -0
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +0 -4
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-pretty-error.ts +40 -0
  20. package/templates/middleware/middleware-scheduled.ts +15 -0
  21. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  22. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  23. package/templates/modules-watch-stub.js +4 -0
  24. package/templates/new-worker-scheduled.js +3 -3
  25. package/templates/new-worker-scheduled.ts +16 -16
  26. package/templates/new-worker.js +3 -3
  27. package/templates/new-worker.ts +19 -16
  28. package/templates/no-op-worker.js +10 -0
  29. package/templates/pages-dev-pipeline.ts +32 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +9 -0
  32. package/templates/pages-template-plugin.ts +190 -0
  33. package/templates/pages-template-worker.ts +198 -0
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +105 -0
  38. package/templates/tsconfig.json +6 -103
  39. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  40. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  41. package/wrangler-dist/ProxyWorker.js +240 -0
  42. package/wrangler-dist/ProxyWorker.js.map +6 -0
  43. package/wrangler-dist/cli.d.ts +24215 -0
  44. package/wrangler-dist/cli.js +191630 -110162
  45. package/wrangler-dist/wasm-sync.wasm +0 -0
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -4886
  52. package/pages/functions/buildPlugin.ts +0 -105
  53. package/pages/functions/buildWorker.ts +0 -151
  54. package/pages/functions/filepath-routing.test.ts +0 -234
  55. package/pages/functions/filepath-routing.ts +0 -189
  56. package/pages/functions/identifiers.ts +0 -78
  57. package/pages/functions/routes.ts +0 -156
  58. package/pages/functions/template-plugin.ts +0 -147
  59. package/pages/functions/template-worker.ts +0 -143
  60. package/src/__tests__/config-cache.test.ts +0 -36
  61. package/src/__tests__/configuration.test.ts +0 -3487
  62. package/src/__tests__/dev.test.tsx +0 -1010
  63. package/src/__tests__/guess-worker-format.test.ts +0 -85
  64. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  65. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  66. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  67. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  68. package/src/__tests__/helpers/mock-bin.ts +0 -36
  69. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  70. package/src/__tests__/helpers/mock-console.ts +0 -87
  71. package/src/__tests__/helpers/mock-dialogs.ts +0 -130
  72. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  73. package/src/__tests__/helpers/mock-istty.ts +0 -27
  74. package/src/__tests__/helpers/mock-kv.ts +0 -33
  75. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  76. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  77. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  78. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  79. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  80. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  81. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  82. package/src/__tests__/https-options.test.ts +0 -130
  83. package/src/__tests__/index.test.ts +0 -257
  84. package/src/__tests__/init.test.ts +0 -1637
  85. package/src/__tests__/jest.setup.ts +0 -77
  86. package/src/__tests__/kv.test.ts +0 -1502
  87. package/src/__tests__/logger.test.ts +0 -115
  88. package/src/__tests__/package-manager.test.ts +0 -353
  89. package/src/__tests__/pages.test.ts +0 -754
  90. package/src/__tests__/parse.test.ts +0 -330
  91. package/src/__tests__/publish.test.ts +0 -5820
  92. package/src/__tests__/r2.test.ts +0 -233
  93. package/src/__tests__/route.test.ts +0 -45
  94. package/src/__tests__/secret.test.ts +0 -481
  95. package/src/__tests__/tail.test.ts +0 -690
  96. package/src/__tests__/user.test.ts +0 -131
  97. package/src/__tests__/whoami.test.tsx +0 -139
  98. package/src/abort.d.ts +0 -3
  99. package/src/bundle.ts +0 -204
  100. package/src/cfetch/index.ts +0 -121
  101. package/src/cfetch/internal.ts +0 -142
  102. package/src/cli.ts +0 -13
  103. package/src/config/README.md +0 -107
  104. package/src/config/config.ts +0 -234
  105. package/src/config/diagnostics.ts +0 -80
  106. package/src/config/environment.ts +0 -420
  107. package/src/config/index.ts +0 -225
  108. package/src/config/validation-helpers.ts +0 -584
  109. package/src/config/validation.ts +0 -1548
  110. package/src/config-cache.ts +0 -45
  111. package/src/create-worker-preview.ts +0 -185
  112. package/src/create-worker-upload-form.ts +0 -254
  113. package/src/dev/dev-vars.ts +0 -36
  114. package/src/dev/dev.tsx +0 -395
  115. package/src/dev/local.tsx +0 -321
  116. package/src/dev/remote.tsx +0 -240
  117. package/src/dev/use-esbuild.ts +0 -115
  118. package/src/dialogs.tsx +0 -135
  119. package/src/durable.ts +0 -102
  120. package/src/entry.ts +0 -322
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/https-options.ts +0 -123
  124. package/src/index.tsx +0 -2859
  125. package/src/inspect.ts +0 -662
  126. package/src/intl-polyfill.d.ts +0 -139
  127. package/src/kv.ts +0 -408
  128. package/src/logger.ts +0 -66
  129. package/src/miniflare-cli/README.md +0 -30
  130. package/src/miniflare-cli/enum-keys.ts +0 -17
  131. package/src/miniflare-cli/index.ts +0 -41
  132. package/src/miniflare-cli/request-context.ts +0 -40
  133. package/src/module-collection.ts +0 -258
  134. package/src/open-in-browser.ts +0 -19
  135. package/src/package-manager.ts +0 -174
  136. package/src/pages.tsx +0 -2093
  137. package/src/parse.ts +0 -222
  138. package/src/paths.ts +0 -26
  139. package/src/proxy.ts +0 -478
  140. package/src/publish.ts +0 -721
  141. package/src/r2.ts +0 -50
  142. package/src/selfsigned.d.ts +0 -29
  143. package/src/sites.tsx +0 -326
  144. package/src/tail/filters.ts +0 -279
  145. package/src/tail/index.ts +0 -299
  146. package/src/tail/printing.ts +0 -67
  147. package/src/update-check.ts +0 -19
  148. package/src/user.tsx +0 -1214
  149. package/src/whoami.tsx +0 -71
  150. package/src/worker.ts +0 -181
  151. package/src/zones.ts +0 -73
  152. package/templates/static-asset-facade.js +0 -43
@@ -1,240 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import { useState, useEffect, useRef } from "react";
4
- import { createWorkerPreview } from "../create-worker-preview";
5
- import useInspector from "../inspect";
6
- import { logger } from "../logger";
7
- import { usePreviewServer } from "../proxy";
8
- import { syncAssets } from "../sites";
9
- import { requireApiToken, requireAuth } from "../user";
10
- import type { CfPreviewToken } from "../create-worker-preview";
11
- import type { AssetPaths } from "../sites";
12
- import type { CfModule, CfWorkerInit, CfScriptFormat } from "../worker";
13
- import type { EsbuildBundle } from "./use-esbuild";
14
-
15
- export function Remote(props: {
16
- name: string | undefined;
17
- bundle: EsbuildBundle | undefined;
18
- format: CfScriptFormat | undefined;
19
- public: string | undefined;
20
- assetPaths: AssetPaths | undefined;
21
- port: number;
22
- ip: string;
23
- localProtocol: "https" | "http";
24
- inspectorPort: number;
25
- accountId: string | undefined;
26
- bindings: CfWorkerInit["bindings"];
27
- compatibilityDate: string;
28
- compatibilityFlags: string[] | undefined;
29
- usageModel: "bundled" | "unbound" | undefined;
30
- env: string | undefined;
31
- legacyEnv: boolean | undefined;
32
- zone: string | undefined;
33
- host: string | undefined;
34
- }) {
35
- const previewToken = useWorker({
36
- name: props.name,
37
- bundle: props.bundle,
38
- format: props.format,
39
- modules: props.bundle ? props.bundle.modules : [],
40
- accountId: props.accountId,
41
- bindings: props.bindings,
42
- assetPaths: props.assetPaths,
43
- public: props.public,
44
- port: props.port,
45
- compatibilityDate: props.compatibilityDate,
46
- compatibilityFlags: props.compatibilityFlags,
47
- usageModel: props.usageModel,
48
- env: props.env,
49
- legacyEnv: props.legacyEnv,
50
- zone: props.zone,
51
- host: props.host,
52
- });
53
-
54
- usePreviewServer({
55
- previewToken,
56
- publicRoot: props.public,
57
- localProtocol: props.localProtocol,
58
- localPort: props.port,
59
- ip: props.ip,
60
- });
61
-
62
- useInspector({
63
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
64
- port: props.inspectorPort,
65
- logToTerminal: true,
66
- });
67
- return null;
68
- }
69
-
70
- export function useWorker(props: {
71
- name: string | undefined;
72
- bundle: EsbuildBundle | undefined;
73
- format: CfScriptFormat | undefined;
74
- modules: CfModule[];
75
- accountId: string | undefined;
76
- bindings: CfWorkerInit["bindings"];
77
- assetPaths: AssetPaths | undefined;
78
- public: string | undefined;
79
- port: number;
80
- compatibilityDate: string | undefined;
81
- compatibilityFlags: string[] | undefined;
82
- usageModel: "bundled" | "unbound" | undefined;
83
- env: string | undefined;
84
- legacyEnv: boolean | undefined;
85
- zone: string | undefined;
86
- host: string | undefined;
87
- }): CfPreviewToken | undefined {
88
- const {
89
- name,
90
- bundle,
91
- format,
92
- modules,
93
- accountId,
94
- bindings,
95
- assetPaths,
96
- compatibilityDate,
97
- compatibilityFlags,
98
- usageModel,
99
- port,
100
- } = props;
101
- const [token, setToken] = useState<CfPreviewToken | undefined>();
102
-
103
- // This is the most reliable way to detect whether
104
- // something's "happened" in our system; We make a ref and
105
- // mark it once we log our initial message. Refs are vars!
106
- const startedRef = useRef(false);
107
- // This ref holds the actual accountId being used, the `accountId` prop could be undefined
108
- // as it is only what is retrieved from the wrangler.toml config.
109
- const accountIdRef = useRef(accountId);
110
-
111
- useEffect(() => {
112
- const abortController = new AbortController();
113
- async function start() {
114
- setToken(undefined); // reset token in case we're re-running
115
-
116
- if (!bundle || !format) return;
117
-
118
- if (!startedRef.current) {
119
- startedRef.current = true;
120
- } else {
121
- logger.log("⎔ Detected changes, restarted server.");
122
- }
123
-
124
- // Ensure we have an account id, even if it means logging in here.
125
- accountIdRef.current = await requireAuth({
126
- account_id: accountIdRef.current,
127
- });
128
-
129
- const assets = await syncAssets(
130
- accountIdRef.current,
131
- // When we're using the newer service environments, we wouldn't
132
- // have added the env name on to the script name. However, we must
133
- // include it in the kv namespace name regardless (since there's no
134
- // concept of service environments for kv namespaces yet).
135
- name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
136
- props.public ? undefined : assetPaths,
137
- true,
138
- false
139
- ); // TODO: cancellable?
140
-
141
- const content = await readFile(bundle.path, "utf-8");
142
-
143
- const init: CfWorkerInit = {
144
- name,
145
- main: {
146
- name: path.basename(bundle.path),
147
- type: format === "modules" ? "esm" : "commonjs",
148
- content,
149
- },
150
- modules: modules.concat(
151
- assets.manifest
152
- ? {
153
- name: "__STATIC_CONTENT_MANIFEST",
154
- content: JSON.stringify(assets.manifest),
155
- type: "text",
156
- }
157
- : []
158
- ),
159
- bindings: {
160
- ...bindings,
161
- kv_namespaces: (bindings.kv_namespaces || []).concat(
162
- assets.namespace
163
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
164
- : []
165
- ),
166
- text_blobs: {
167
- ...bindings.text_blobs,
168
- ...(assets.manifest &&
169
- format === "service-worker" && {
170
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
171
- }),
172
- },
173
- },
174
- migrations: undefined, // no migrations in dev
175
- compatibility_date: compatibilityDate,
176
- compatibility_flags: compatibilityFlags,
177
- usage_model: usageModel,
178
- };
179
- setToken(
180
- await createWorkerPreview(
181
- init,
182
- {
183
- accountId: accountIdRef.current,
184
- apiToken: requireApiToken(),
185
- },
186
- {
187
- env: props.env,
188
- legacyEnv: props.legacyEnv,
189
- zone: props.zone,
190
- host: props.host,
191
- },
192
- abortController.signal
193
- )
194
- );
195
- }
196
- start().catch((err) => {
197
- // we want to log the error, but not end the process
198
- // since it could recover after the developer fixes whatever's wrong
199
- if ((err as { code: string }).code !== "ABORT_ERR") {
200
- // instead of logging the raw API error to the user,
201
- // give them friendly instructions
202
- // for error 10063 (workers.dev subdomain required)
203
- if (err.code === 10063) {
204
- const errorMessage =
205
- "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
206
- const solutionMessage =
207
- "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
208
- const onboardingLink = `https://dash.cloudflare.com/${accountIdRef.current}/workers/onboarding`;
209
- logger.error(
210
- `${errorMessage}\n${solutionMessage}\n${onboardingLink}`
211
- );
212
- } else {
213
- logger.error("Error on remote worker:", err);
214
- }
215
- }
216
- });
217
-
218
- return () => {
219
- abortController.abort();
220
- };
221
- }, [
222
- name,
223
- bundle,
224
- format,
225
- accountId,
226
- port,
227
- assetPaths,
228
- props.public,
229
- compatibilityDate,
230
- compatibilityFlags,
231
- usageModel,
232
- bindings,
233
- modules,
234
- props.env,
235
- props.legacyEnv,
236
- props.zone,
237
- props.host,
238
- ]);
239
- return token;
240
- }
@@ -1,115 +0,0 @@
1
- import assert from "node:assert";
2
- import { useApp } from "ink";
3
- import { useState, useEffect } from "react";
4
- import { bundleWorker } from "../bundle";
5
- import { logger } from "../logger";
6
- import type { Config } from "../config";
7
- import type { Entry } from "../entry";
8
- import type { CfModule } from "../worker";
9
- import type { WatchMode } from "esbuild";
10
-
11
- export type EsbuildBundle = {
12
- id: number;
13
- path: string;
14
- entry: Entry;
15
- type: "esm" | "commonjs";
16
- modules: CfModule[];
17
- };
18
-
19
- export function useEsbuild({
20
- entry,
21
- destination,
22
- staticRoot,
23
- jsxFactory,
24
- jsxFragment,
25
- rules,
26
- serveAssetsFromWorker,
27
- tsconfig,
28
- minify,
29
- nodeCompat,
30
- }: {
31
- entry: Entry;
32
- destination: string | undefined;
33
- staticRoot: string | undefined;
34
- jsxFactory: string | undefined;
35
- jsxFragment: string | undefined;
36
- rules: Config["rules"];
37
- serveAssetsFromWorker: boolean;
38
- tsconfig: string | undefined;
39
- minify: boolean | undefined;
40
- nodeCompat: boolean | undefined;
41
- }): EsbuildBundle | undefined {
42
- const [bundle, setBundle] = useState<EsbuildBundle>();
43
- const { exit } = useApp();
44
- useEffect(() => {
45
- let stopWatching: (() => void) | undefined = undefined;
46
-
47
- const watchMode: WatchMode = {
48
- async onRebuild(error) {
49
- if (error) logger.error("Watch build failed:", error);
50
- else {
51
- // nothing really changes here, so let's increment the id
52
- // to change the return object's identity
53
- setBundle((previousBundle) => {
54
- assert(
55
- previousBundle,
56
- "Rebuild triggered with no previous build available"
57
- );
58
- return { ...previousBundle, id: previousBundle.id + 1 };
59
- });
60
- }
61
- },
62
- };
63
-
64
- async function build() {
65
- if (!destination) return;
66
-
67
- const { resolvedEntryPointPath, bundleType, modules, stop } =
68
- await bundleWorker(entry, destination, {
69
- serveAssetsFromWorker,
70
- jsxFactory,
71
- jsxFragment,
72
- rules,
73
- watch: watchMode,
74
- tsconfig,
75
- minify,
76
- nodeCompat,
77
- });
78
-
79
- // Capture the `stop()` method to use as the `useEffect()` destructor.
80
- stopWatching = stop;
81
-
82
- setBundle({
83
- id: 0,
84
- entry,
85
- path: resolvedEntryPointPath,
86
- type: bundleType,
87
- modules,
88
- });
89
- }
90
-
91
- build().catch((err) => {
92
- // If esbuild fails on first run, we want to quit the process
93
- // since we can't recover from here
94
- // related: https://github.com/evanw/esbuild/issues/1037
95
- exit(err);
96
- });
97
-
98
- return () => {
99
- stopWatching?.();
100
- };
101
- }, [
102
- entry,
103
- destination,
104
- staticRoot,
105
- jsxFactory,
106
- jsxFragment,
107
- serveAssetsFromWorker,
108
- rules,
109
- tsconfig,
110
- exit,
111
- minify,
112
- nodeCompat,
113
- ]);
114
- return bundle;
115
- }
package/src/dialogs.tsx DELETED
@@ -1,135 +0,0 @@
1
- import chalk from "chalk";
2
- import { Box, Text, useInput, render } from "ink";
3
- import SelectInput from "ink-select-input";
4
- import TextInput from "ink-text-input";
5
- import * as React from "react";
6
- import { useState } from "react";
7
- import { logger } from "./logger";
8
- type ConfirmProps = {
9
- text: string;
10
- onConfirm: (answer: boolean) => void;
11
- };
12
- function Confirm(props: ConfirmProps) {
13
- useInput((input: string, key) => {
14
- if (input === "y" || key.return === true) {
15
- props.onConfirm(true);
16
- } else if (input === "n") {
17
- props.onConfirm(false);
18
- } else {
19
- logger.warn("Unrecognised input:", input);
20
- }
21
- });
22
- return (
23
- <Box>
24
- <Text>
25
- {props.text} ({chalk.bold("y")}/n)
26
- </Text>
27
- </Box>
28
- );
29
- }
30
-
31
- export function confirm(text: string): Promise<boolean> {
32
- return new Promise((resolve) => {
33
- const { unmount } = render(
34
- <Confirm
35
- text={text}
36
- onConfirm={(answer: boolean) => {
37
- unmount();
38
- resolve(answer);
39
- }}
40
- />
41
- );
42
- });
43
- }
44
-
45
- type PromptProps = {
46
- text: string;
47
- defaultValue?: string;
48
- type?: "text" | "password";
49
- onSubmit: (text: string) => void;
50
- };
51
-
52
- function Prompt(props: PromptProps) {
53
- const [value, setValue] = useState(props.defaultValue || "");
54
-
55
- return (
56
- <Box>
57
- <Text>{props.text} </Text>
58
- <Box>
59
- <TextInput
60
- mask={props.type === "password" ? "*" : undefined}
61
- value={value}
62
- onChange={setValue}
63
- onSubmit={props.onSubmit}
64
- />
65
- </Box>
66
- </Box>
67
- );
68
- }
69
-
70
- export async function prompt(
71
- text: string,
72
- type: "text" | "password" = "text",
73
- defaultValue?: string
74
- ): Promise<string> {
75
- return new Promise((resolve) => {
76
- const { unmount } = render(
77
- <Prompt
78
- text={text}
79
- defaultValue={defaultValue}
80
- type={type}
81
- onSubmit={(inputText) => {
82
- unmount();
83
- resolve(inputText);
84
- }}
85
- />
86
- );
87
- });
88
- }
89
-
90
- type SelectOption = {
91
- value: string;
92
- label: string;
93
- };
94
-
95
- type SelectProps = {
96
- text: string;
97
- options: SelectOption[];
98
- initialIndex: number;
99
- onSelect: (value: string) => void;
100
- };
101
-
102
- function Select(props: SelectProps) {
103
- return (
104
- <Box flexDirection="column">
105
- <Text>{props.text}</Text>
106
- <SelectInput
107
- initialIndex={props.initialIndex}
108
- items={props.options}
109
- onSelect={async (selected) => {
110
- props.onSelect(selected.value);
111
- }}
112
- />
113
- </Box>
114
- );
115
- }
116
-
117
- export function select(
118
- text: string,
119
- options: SelectOption[],
120
- initialIndex: number
121
- ): Promise<string> {
122
- return new Promise((resolve) => {
123
- const { unmount } = render(
124
- <Select
125
- text={text}
126
- options={options}
127
- initialIndex={initialIndex}
128
- onSelect={(option: string) => {
129
- unmount();
130
- resolve(option);
131
- }}
132
- />
133
- );
134
- });
135
- }
package/src/durable.ts DELETED
@@ -1,102 +0,0 @@
1
- import assert from "node:assert";
2
- import { fetchResult } from "./cfetch";
3
- import { logger } from "./logger";
4
- import type { Config } from "./config";
5
- import type { CfWorkerInit } from "./worker";
6
-
7
- /**
8
- * For a given Worker + migrations config, figure out which migrations
9
- * to upload based on the current migration tag of the deployed Worker.
10
- */
11
- export async function getMigrationsToUpload(
12
- scriptName: string,
13
- props: {
14
- accountId: string | undefined;
15
- config: Config;
16
- legacyEnv: boolean | undefined;
17
- env: string | undefined;
18
- }
19
- ): Promise<CfWorkerInit["migrations"]> {
20
- const { config, accountId } = props;
21
-
22
- assert(accountId, "Missing accountId");
23
- // if config.migrations
24
- let migrations;
25
- if (config.migrations.length > 0) {
26
- // get current migration tag
27
- type ScriptData = { id: string; migration_tag?: string };
28
- let script: ScriptData | undefined;
29
- if (!props.legacyEnv) {
30
- try {
31
- if (props.env) {
32
- const scriptData = await fetchResult<{
33
- script: ScriptData;
34
- }>(
35
- `/accounts/${accountId}/workers/services/${scriptName}/environments/${props.env}`
36
- );
37
- script = scriptData.script;
38
- } else {
39
- const scriptData = await fetchResult<{
40
- default_environment: {
41
- script: ScriptData;
42
- };
43
- }>(`/accounts/${accountId}/workers/services/${scriptName}`);
44
- script = scriptData.default_environment.script;
45
- }
46
- } catch (err) {
47
- if (
48
- ![
49
- 10090, // corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
50
- 10092, // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
51
- ].includes((err as { code: number }).code)
52
- ) {
53
- throw err;
54
- }
55
- // else it's a 404, no script found, and we can proceed
56
- }
57
- } else {
58
- const scripts = await fetchResult<ScriptData[]>(
59
- `/accounts/${accountId}/workers/scripts`
60
- );
61
- script = scripts.find(({ id }) => id === scriptName);
62
- }
63
-
64
- if (script?.migration_tag) {
65
- // was already published once
66
- const scriptMigrationTag = script.migration_tag;
67
- const foundIndex = config.migrations.findIndex(
68
- (migration) => migration.tag === scriptMigrationTag
69
- );
70
- if (foundIndex === -1) {
71
- logger.warn(
72
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
73
- );
74
- migrations = {
75
- old_tag: script.migration_tag,
76
- new_tag: config.migrations[config.migrations.length - 1].tag,
77
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
78
- };
79
- } else {
80
- if (foundIndex !== config.migrations.length - 1) {
81
- // there are new migrations to send up
82
- migrations = {
83
- old_tag: script.migration_tag,
84
- new_tag: config.migrations[config.migrations.length - 1].tag,
85
- steps: config.migrations
86
- .slice(foundIndex + 1)
87
- .map(({ tag: _tag, ...rest }) => rest),
88
- };
89
- }
90
- // else, we're up to date, no migrations to send
91
- }
92
- } else {
93
- // first time publishing durable objects to this script,
94
- // so we send all the migrations
95
- migrations = {
96
- new_tag: config.migrations[config.migrations.length - 1].tag,
97
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
98
- };
99
- }
100
- }
101
- return migrations;
102
- }