wrangler 2.1.4 → 2.1.6

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 (46) hide show
  1. package/miniflare-dist/index.mjs +4 -1
  2. package/package.json +1 -1
  3. package/src/__tests__/api-dev.test.ts +3 -3
  4. package/src/__tests__/api-devregistry.test.js +56 -0
  5. package/src/__tests__/configuration.test.ts +3 -0
  6. package/src/__tests__/dev.test.tsx +39 -1
  7. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  8. package/src/__tests__/helpers/{hello-world-worker.js → worker-scripts/hello-world-worker.js} +0 -0
  9. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  10. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  11. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  12. package/src/__tests__/init.test.ts +72 -0
  13. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  14. package/src/__tests__/middleware.test.ts +703 -745
  15. package/src/__tests__/pages.test.ts +35 -40
  16. package/src/__tests__/publish.test.ts +57 -1
  17. package/src/api/dev.ts +2 -0
  18. package/src/bundle.ts +14 -16
  19. package/src/config/config.ts +12 -0
  20. package/src/config/validation.ts +9 -0
  21. package/src/create-worker-upload-form.ts +3 -2
  22. package/src/dev/dev.tsx +12 -21
  23. package/src/dev/local.tsx +1 -0
  24. package/src/dev/remote.tsx +38 -50
  25. package/src/dev/start-server.ts +43 -8
  26. package/src/dev/use-esbuild.ts +4 -0
  27. package/src/dev-registry.tsx +30 -0
  28. package/src/dev.tsx +21 -3
  29. package/src/index.tsx +8 -1
  30. package/src/init.ts +3 -1
  31. package/src/inspect.ts +26 -26
  32. package/src/miniflare-cli/assets.ts +8 -1
  33. package/src/pages/constants.ts +2 -1
  34. package/src/pages/dev.tsx +133 -10
  35. package/src/pages/errors.ts +48 -4
  36. package/src/pages/functions/routes-transformation.ts +1 -14
  37. package/src/pages/functions/routes-validation.test.ts +403 -0
  38. package/src/pages/functions/routes-validation.ts +202 -0
  39. package/src/pages/functions.tsx +4 -18
  40. package/src/pages/publish.tsx +6 -22
  41. package/src/publish.ts +3 -1
  42. package/src/worker.ts +1 -1
  43. package/templates/middleware/middleware-scheduled.ts +2 -1
  44. package/templates/pages-dev-pipeline.ts +35 -0
  45. package/wrangler-dist/cli.d.ts +2 -0
  46. package/wrangler-dist/cli.js +611 -353
@@ -1,7 +1,7 @@
1
1
  import { mkdirSync, writeFileSync } from "node:fs";
2
2
  import { chdir } from "node:process";
3
3
  import { ROUTES_SPEC_VERSION } from "../pages/constants";
4
- import { isRoutesJSONSpec } from "../pages/functions/routes-transformation";
4
+ import { isRoutesJSONSpec } from "../pages/functions/routes-validation";
5
5
  import { version } from "./../../package.json";
6
6
  import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
7
7
  import {
@@ -1113,10 +1113,11 @@ describe("pages", () => {
1113
1113
  // generated and that the file size is greater than zero
1114
1114
  expect(generatedWorkerJS).not.toBeNull();
1115
1115
  expect(generatedWorkerJS.size).toBeGreaterThan(0);
1116
+
1116
1117
  const maybeRoutesJSONSpec = JSON.parse(generatedRoutesJSON);
1117
1118
  expect(isRoutesJSONSpec(maybeRoutesJSONSpec)).toBe(true);
1118
1119
  expect(maybeRoutesJSONSpec).toMatchObject({
1119
- version: 1,
1120
+ version: ROUTES_SPEC_VERSION,
1120
1121
  description: `Generated by wrangler@${version}`,
1121
1122
  include: ["/hello"],
1122
1123
  exclude: [],
@@ -1371,16 +1372,13 @@ describe("pages", () => {
1371
1372
  expect(generatedWorkerJS).not.toBeNull();
1372
1373
  expect(generatedWorkerJS.size).toBeGreaterThan(0);
1373
1374
 
1374
- expect(customRoutesJSON).toMatchInlineSnapshot(`
1375
- "
1376
- {
1377
- \\"version\\": 1,
1378
- \\"description\\": \\"Custom _routes.json file\\",
1379
- \\"include\\": [\\"/hello\\"],
1380
- \\"exclude\\": []
1381
- }
1382
- "
1383
- `);
1375
+ const customRoutes = JSON.parse(customRoutesJSON);
1376
+ expect(customRoutes).toMatchObject({
1377
+ version: ROUTES_SPEC_VERSION,
1378
+ description: "Custom _routes.json file",
1379
+ include: ["/hello"],
1380
+ exclude: [],
1381
+ });
1384
1382
  });
1385
1383
 
1386
1384
  return {
@@ -1476,15 +1474,15 @@ describe("pages", () => {
1476
1474
  });
1477
1475
 
1478
1476
  await expect(runWrangler("pages publish public --project-name=foo"))
1479
- .rejects.toThrowErrorMatchingInlineSnapshot(`
1480
- "Invalid _routes.json file found at: public/_routes.json. Please make sure the JSON object has the following format:
1481
- {
1482
- version: ${ROUTES_SPEC_VERSION};
1483
- include: string[];
1484
- exclude: string[];
1485
- }
1486
- and that at least one include rule is provided.
1487
- "
1477
+ .rejects
1478
+ .toThrow(`Invalid _routes.json file found at: public/_routes.json
1479
+ Please make sure the JSON object has the following format:
1480
+ {
1481
+ version: ${ROUTES_SPEC_VERSION};
1482
+ include: string[];
1483
+ exclude: string[];
1484
+ }
1485
+ and that at least one include rule is provided.
1488
1486
  `);
1489
1487
  });
1490
1488
 
@@ -1612,16 +1610,13 @@ describe("pages", () => {
1612
1610
  "
1613
1611
  `);
1614
1612
 
1615
- expect(customRoutesJSON).toMatchInlineSnapshot(`
1616
- "
1617
- {
1618
- \\"version\\": 1,
1619
- \\"description\\": \\"Custom _routes.json file\\",
1620
- \\"include\\": [\\"/api/*\\"],
1621
- \\"exclude\\": []
1622
- }
1623
- "
1624
- `);
1613
+ const customRoutes = JSON.parse(customRoutesJSON);
1614
+ expect(customRoutes).toMatchObject({
1615
+ version: ROUTES_SPEC_VERSION,
1616
+ description: "Custom _routes.json file",
1617
+ include: ["/api/*"],
1618
+ exclude: [],
1619
+ });
1625
1620
  });
1626
1621
 
1627
1622
  return {
@@ -1716,15 +1711,15 @@ describe("pages", () => {
1716
1711
  });
1717
1712
 
1718
1713
  await expect(runWrangler("pages publish public --project-name=foo"))
1719
- .rejects.toThrowErrorMatchingInlineSnapshot(`
1720
- "Invalid _routes.json file found at: public/_routes.json. Please make sure the JSON object has the following format:
1721
- {
1722
- version: ${ROUTES_SPEC_VERSION};
1723
- include: string[];
1724
- exclude: string[];
1725
- }
1726
- and that at least one include rule is provided.
1727
- "
1714
+ .rejects
1715
+ .toThrow(`Invalid _routes.json file found at: public/_routes.json
1716
+ Please make sure the JSON object has the following format:
1717
+ {
1718
+ version: ${ROUTES_SPEC_VERSION};
1719
+ include: string[];
1720
+ exclude: string[];
1721
+ }
1722
+ and that at least one include rule is provided.
1728
1723
  `);
1729
1724
  });
1730
1725
  });
@@ -6540,6 +6540,56 @@ addEventListener('fetch', event => {});`
6540
6540
  `A request to the Cloudflare API (/accounts/some-account-id/workers/services/test-name) failed`
6541
6541
  );
6542
6542
  });
6543
+
6544
+ describe("--keep-vars", () => {
6545
+ it("should send keepVars when keep-vars is passed in", async () => {
6546
+ process.env = {
6547
+ CLOUDFLARE_API_TOKEN: "hunter2",
6548
+ CLOUDFLARE_ACCOUNT_ID: "some-account-id",
6549
+ };
6550
+ setIsTTY(false);
6551
+ writeWranglerToml();
6552
+ writeWorkerSource();
6553
+ mockSubDomainRequest();
6554
+ mockUploadWorkerRequest({ keepVars: true });
6555
+ mockOAuthServerCallback();
6556
+ mockGetMemberships([]);
6557
+
6558
+ await runWrangler("publish index.js --keep-vars");
6559
+
6560
+ expect(std.out).toMatchInlineSnapshot(`
6561
+ "Total Upload: xx KiB / gzip: xx KiB
6562
+ Uploaded test-name (TIMINGS)
6563
+ Published test-name (TIMINGS)
6564
+ https://test-name.test-sub-domain.workers.dev"
6565
+ `);
6566
+ expect(std.err).toMatchInlineSnapshot(`""`);
6567
+ });
6568
+
6569
+ it("should not send keepVars by default", async () => {
6570
+ process.env = {
6571
+ CLOUDFLARE_API_TOKEN: "hunter2",
6572
+ CLOUDFLARE_ACCOUNT_ID: "some-account-id",
6573
+ };
6574
+ setIsTTY(false);
6575
+ writeWranglerToml();
6576
+ writeWorkerSource();
6577
+ mockSubDomainRequest();
6578
+ mockUploadWorkerRequest();
6579
+ mockOAuthServerCallback();
6580
+ mockGetMemberships([]);
6581
+
6582
+ await runWrangler("publish index.js");
6583
+
6584
+ expect(std.out).toMatchInlineSnapshot(`
6585
+ "Total Upload: xx KiB / gzip: xx KiB
6586
+ Uploaded test-name (TIMINGS)
6587
+ Published test-name (TIMINGS)
6588
+ https://test-name.test-sub-domain.workers.dev"
6589
+ `);
6590
+ expect(std.err).toMatchInlineSnapshot(`""`);
6591
+ });
6592
+ });
6543
6593
  });
6544
6594
 
6545
6595
  /** Write mock assets to the file system so they can be uploaded. */
@@ -6571,6 +6621,7 @@ function mockUploadWorkerRequest(
6571
6621
  env?: string;
6572
6622
  legacyEnv?: boolean;
6573
6623
  sendScriptIds?: boolean;
6624
+ keepVars?: boolean;
6574
6625
  } = {}
6575
6626
  ) {
6576
6627
  const {
@@ -6586,6 +6637,7 @@ function mockUploadWorkerRequest(
6586
6637
  legacyEnv = false,
6587
6638
  expectedMigrations,
6588
6639
  sendScriptIds,
6640
+ keepVars,
6589
6641
  } = options;
6590
6642
  setMockResponse(
6591
6643
  env && !legacyEnv
@@ -6617,7 +6669,11 @@ function mockUploadWorkerRequest(
6617
6669
  expect(metadata.body_part).toEqual("index.js");
6618
6670
  }
6619
6671
 
6620
- expect(metadata.keep_bindings).toEqual(["plain_text", "json"]);
6672
+ if (keepVars) {
6673
+ expect(metadata.keep_bindings).toEqual(["plain_text", "json"]);
6674
+ } else {
6675
+ expect(metadata.keep_bindings).toBeFalsy();
6676
+ }
6621
6677
 
6622
6678
  if ("expectedBindings" in options) {
6623
6679
  expect(metadata.bindings).toEqual(expectedBindings);
package/src/api/dev.ts CHANGED
@@ -10,6 +10,7 @@ interface DevOptions {
10
10
  env?: string;
11
11
  ip?: string;
12
12
  port?: number;
13
+ noBundle?: boolean;
13
14
  inspectorPort?: number;
14
15
  localProtocol?: "http" | "https";
15
16
  assets?: string;
@@ -50,6 +51,7 @@ interface DevOptions {
50
51
  enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
51
52
  _?: (string | number)[]; //yargs wants this
52
53
  $0?: string; //yargs wants this
54
+ testScheduled?: boolean;
53
55
  }
54
56
 
55
57
  interface DevApiOptions {
package/src/bundle.ts CHANGED
@@ -7,7 +7,7 @@ import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
7
7
  import * as esbuild from "esbuild";
8
8
  import tmp from "tmp-promise";
9
9
  import createModuleCollector from "./module-collection";
10
- import { getBasePath } from "./paths";
10
+ import { getBasePath, toUrlPath } from "./paths";
11
11
  import type { Config } from "./config";
12
12
  import type { WorkerRegistry } from "./dev-registry";
13
13
  import type { Entry } from "./entry";
@@ -76,6 +76,7 @@ export async function bundleWorker(
76
76
  workerDefinitions: WorkerRegistry | undefined;
77
77
  firstPartyWorkerDevFacade: boolean | undefined;
78
78
  targetConsumer: "dev" | "publish";
79
+ testScheduled?: boolean | undefined;
79
80
  }
80
81
  ): Promise<BundleResult> {
81
82
  const {
@@ -93,6 +94,7 @@ export async function bundleWorker(
93
94
  services,
94
95
  firstPartyWorkerDevFacade,
95
96
  targetConsumer,
97
+ testScheduled,
96
98
  } = options;
97
99
 
98
100
  // We create a temporary directory for any oneoff files we
@@ -144,16 +146,13 @@ export async function bundleWorker(
144
146
 
145
147
  // We also have middleware that uses a more "traditional" middleware stack,
146
148
  // which is all loaded as one in a stack.
147
- const middlewareToLoad: MiddlewareLoader[] = [
148
- // {
149
- // path: "templates/middleware/middleware-pretty-error.ts",
150
- // publish: true,
151
- // dev: false,
152
- // },
153
- // {
154
- // path: "../templates/middleware/middleware-scheduled.ts",
155
- // },
156
- ];
149
+ const middlewareToLoad: MiddlewareLoader[] = [];
150
+
151
+ if (testScheduled) {
152
+ middlewareToLoad.push({
153
+ path: "templates/middleware/middleware-scheduled.ts",
154
+ });
155
+ }
157
156
 
158
157
  type MiddlewareFn = (arg0: Entry) => Promise<Entry>;
159
158
  const middleware: (false | undefined | MiddlewareFn)[] = [
@@ -309,7 +308,7 @@ export async function bundleWorker(
309
308
  /**
310
309
  * A simple plugin to alias modules and mark them as external
311
310
  */
312
- function esbuildAliasExternalPlugin(
311
+ export function esbuildAliasExternalPlugin(
313
312
  aliases: Record<string, string>
314
313
  ): esbuild.Plugin {
315
314
  return {
@@ -445,7 +444,7 @@ async function applyMiddlewareLoaderFacade(
445
444
  ...Object.fromEntries(
446
445
  middleware.map((val, index) => [
447
446
  middlewareIdentifiers[index],
448
- path.resolve(getBasePath(), val.path),
447
+ toUrlPath(path.resolve(getBasePath(), val.path)),
449
448
  ])
450
449
  ),
451
450
  }),
@@ -471,9 +470,8 @@ async function applyMiddlewareLoaderFacade(
471
470
  const imports = middlewareIdentifiers
472
471
  .map(
473
472
  (m, i) =>
474
- `import ${m} from "${path.resolve(
475
- getBasePath(),
476
- middleware[i].path
473
+ `import ${m} from "${toUrlPath(
474
+ path.resolve(getBasePath(), middleware[i].path)
477
475
  )}";`
478
476
  )
479
477
  .join("\n");
@@ -168,6 +168,18 @@ export interface ConfigFields<Dev extends RawDevConfig> {
168
168
  [key: string]: string;
169
169
  }
170
170
  | undefined;
171
+
172
+ /**
173
+ * By default, wrangler.toml is the source of truth for your environment configuration, like a terraform file.
174
+ *
175
+ * If you change your vars in the dashboard, wrangler *will* override/delete them on its next publish.
176
+ *
177
+ * If you want to keep your dashboard vars when wrangler deploys, set this field to true.
178
+ *
179
+ * @default false
180
+ * @nonInheritable
181
+ */
182
+ keep_vars?: boolean;
171
183
  }
172
184
 
173
185
  export interface DevConfig {
@@ -102,6 +102,14 @@ export function normalizeAndValidateConfig(
102
102
  "boolean"
103
103
  );
104
104
 
105
+ validateOptionalProperty(
106
+ diagnostics,
107
+ "",
108
+ "keep_vars",
109
+ rawConfig.keep_vars,
110
+ "boolean"
111
+ );
112
+
105
113
  // TODO: set the default to false to turn on service environments as the default
106
114
  const isLegacyEnv =
107
115
  (args as { "legacy-env": boolean | undefined })["legacy-env"] ??
@@ -182,6 +190,7 @@ export function normalizeAndValidateConfig(
182
190
  configPath,
183
191
  legacy_env: isLegacyEnv,
184
192
  send_metrics: rawConfig.send_metrics,
193
+ keep_vars: rawConfig.keep_vars,
185
194
  ...activeEnv,
186
195
  dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
187
196
  migrations: normalizeAndValidateMigrations(
@@ -59,7 +59,7 @@ export interface WorkerMetadata {
59
59
  migrations?: CfDurableObjectMigrations;
60
60
  capnp_schema?: string;
61
61
  bindings: WorkerMetadataBinding[];
62
- keep_bindings: WorkerMetadataBinding["type"][];
62
+ keep_bindings?: WorkerMetadataBinding["type"][];
63
63
  }
64
64
 
65
65
  /**
@@ -74,6 +74,7 @@ export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
74
74
  usage_model,
75
75
  compatibility_date,
76
76
  compatibility_flags,
77
+ keepVars,
77
78
  } = worker;
78
79
 
79
80
  let { modules } = worker;
@@ -257,7 +258,7 @@ export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
257
258
  ...(usage_model && { usage_model }),
258
259
  ...(migrations && { migrations }),
259
260
  capnp_schema: bindings.logfwdr?.schema,
260
- keep_bindings: ["plain_text", "json"],
261
+ ...(keepVars && { keep_bindings: ["plain_text", "json"] }),
261
262
  };
262
263
 
263
264
  formData.set("metadata", JSON.stringify(metadata));
package/src/dev/dev.tsx CHANGED
@@ -11,7 +11,7 @@ import onExit from "signal-exit";
11
11
  import tmp from "tmp-promise";
12
12
  import { fetch } from "undici";
13
13
  import {
14
- getRegisteredWorkers,
14
+ getBoundRegisteredWorkers,
15
15
  startWorkerRegistry,
16
16
  stopWorkerRegistry,
17
17
  unregisterWorker,
@@ -53,32 +53,21 @@ function useDevRegistry(
53
53
  logger.error("failed to start worker registry", err);
54
54
  });
55
55
 
56
- const serviceNames = (services || []).map(
57
- (serviceBinding) => serviceBinding.service
58
- );
59
- const durableObjectServices = (
60
- durableObjects || { bindings: [] }
61
- ).bindings.map((durableObjectBinding) => durableObjectBinding.script_name);
62
-
63
56
  const interval =
64
57
  // TODO: enable this for remote mode as well
65
58
  // https://github.com/cloudflare/wrangler2/issues/1182
66
59
  mode === "local"
67
60
  ? setInterval(() => {
68
- getRegisteredWorkers().then(
69
- (workerDefinitions: WorkerRegistry | undefined) => {
70
- // We only want the workers that we're bound to
71
- // so let's filter out the others
72
- const filteredWorkers = Object.fromEntries(
73
- Object.entries(workerDefinitions || {}).filter(
74
- ([key, _value]) =>
75
- serviceNames.includes(key) ||
76
- durableObjectServices.includes(key)
77
- )
78
- );
61
+ getBoundRegisteredWorkers({
62
+ services,
63
+ durableObjects,
64
+ }).then(
65
+ (boundRegisteredWorkers: WorkerRegistry | undefined) => {
79
66
  setWorkers((prevWorkers) => {
80
- if (!util.isDeepStrictEqual(filteredWorkers, prevWorkers)) {
81
- return filteredWorkers;
67
+ if (
68
+ !util.isDeepStrictEqual(boundRegisteredWorkers, prevWorkers)
69
+ ) {
70
+ return boundRegisteredWorkers || {};
82
71
  }
83
72
  return prevWorkers;
84
73
  });
@@ -164,6 +153,7 @@ export type DevProps = {
164
153
  enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
165
154
  firstPartyWorker: boolean | undefined;
166
155
  sendMetrics: boolean | undefined;
156
+ testScheduled: boolean | undefined;
167
157
  };
168
158
 
169
159
  export function DevImplementation(props: DevProps): JSX.Element {
@@ -259,6 +249,7 @@ function DevSession(props: DevSessionProps) {
259
249
  firstPartyWorkerDevFacade: props.firstPartyWorker,
260
250
  // Enable the bundling to know whether we are using dev or publish
261
251
  targetConsumer: "dev",
252
+ testScheduled: props.testScheduled ?? false,
262
253
  });
263
254
 
264
255
  return props.local ? (
package/src/dev/local.tsx CHANGED
@@ -52,6 +52,7 @@ export interface LocalProps {
52
52
  logLevel: "none" | "error" | "log" | "warn" | "debug" | undefined;
53
53
  logPrefix?: string;
54
54
  enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
55
+ testScheduled?: boolean;
55
56
  }
56
57
 
57
58
  export function Local(props: LocalProps) {
@@ -169,19 +169,6 @@ export function useWorker(props: {
169
169
  sendMetrics: boolean | undefined;
170
170
  port: number;
171
171
  }): CfPreviewToken | undefined {
172
- const {
173
- name,
174
- bundle,
175
- format,
176
- modules,
177
- accountId,
178
- bindings,
179
- assetPaths,
180
- compatibilityDate,
181
- compatibilityFlags,
182
- usageModel,
183
- onReady,
184
- } = props;
185
172
  const [session, setSession] = useState<CfPreviewSession | undefined>();
186
173
  const [token, setToken] = useState<CfPreviewToken | undefined>();
187
174
  const [restartCounter, setRestartCounter] = useState<number>(0);
@@ -189,17 +176,18 @@ export function useWorker(props: {
189
176
  // something's "happened" in our system; We make a ref and
190
177
  // mark it once we log our initial message. Refs are vars!
191
178
  const startedRef = useRef(false);
192
-
179
+ // functions must be destructured before use inside a useEffect, otherwise the entire props object has to be added to the dependency array
180
+ const { onReady } = props;
193
181
  // This effect sets up the preview session
194
182
  useEffect(() => {
195
183
  const abortController = new AbortController();
196
184
  async function start() {
197
- if (accountId === undefined) {
185
+ if (props.accountId === undefined) {
198
186
  return;
199
187
  }
200
188
 
201
189
  const workerAccount: CfAccount = {
202
- accountId,
190
+ accountId: props.accountId,
203
191
  apiToken: requireApiToken(),
204
192
  };
205
193
 
@@ -232,7 +220,7 @@ export function useWorker(props: {
232
220
  abortController.abort();
233
221
  };
234
222
  }, [
235
- accountId,
223
+ props.accountId,
236
224
  props.env,
237
225
  props.host,
238
226
  props.legacyEnv,
@@ -246,7 +234,7 @@ export function useWorker(props: {
246
234
  useEffect(() => {
247
235
  const abortController = new AbortController();
248
236
  async function start() {
249
- if (accountId === undefined) {
237
+ if (props.accountId === undefined) {
250
238
  return;
251
239
  }
252
240
  if (session === undefined) {
@@ -254,7 +242,7 @@ export function useWorker(props: {
254
242
  }
255
243
  setToken(undefined); // reset token in case we're re-running
256
244
 
257
- if (!bundle || !format) return;
245
+ if (!props.bundle || !props.format) return;
258
246
 
259
247
  if (!startedRef.current) {
260
248
  startedRef.current = true;
@@ -262,34 +250,34 @@ export function useWorker(props: {
262
250
  logger.log("⎔ Detected changes, restarted server.");
263
251
  }
264
252
 
265
- const content = await readFile(bundle.path, "utf-8");
253
+ const content = await readFile(props.bundle.path, "utf-8");
266
254
 
267
255
  // TODO: For Dev we could show the reporter message in the interactive box.
268
256
  void printBundleSize(
269
- { name: path.basename(bundle.path), content: content },
270
- modules
257
+ { name: path.basename(props.bundle.path), content: content },
258
+ props.modules
271
259
  );
272
260
 
273
261
  const assets = await syncAssets(
274
- accountId,
262
+ props.accountId,
275
263
  // When we're using the newer service environments, we wouldn't
276
264
  // have added the env name on to the script name. However, we must
277
265
  // include it in the kv namespace name regardless (since there's no
278
266
  // concept of service environments for kv namespaces yet).
279
- name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
280
- props.isWorkersSite ? assetPaths : undefined,
267
+ props.name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
268
+ props.isWorkersSite ? props.assetPaths : undefined,
281
269
  true,
282
270
  false
283
271
  ); // TODO: cancellable?
284
272
 
285
273
  const init: CfWorkerInit = {
286
- name,
274
+ name: props.name,
287
275
  main: {
288
- name: path.basename(bundle.path),
289
- type: format === "modules" ? "esm" : "commonjs",
276
+ name: path.basename(props.bundle.path),
277
+ type: props.format === "modules" ? "esm" : "commonjs",
290
278
  content,
291
279
  },
292
- modules: modules.concat(
280
+ modules: props.modules.concat(
293
281
  assets.manifest
294
282
  ? {
295
283
  name: "__STATIC_CONTENT_MANIFEST",
@@ -299,29 +287,29 @@ export function useWorker(props: {
299
287
  : []
300
288
  ),
301
289
  bindings: {
302
- ...bindings,
303
- kv_namespaces: (bindings.kv_namespaces || []).concat(
290
+ ...props.bindings,
291
+ kv_namespaces: (props.bindings.kv_namespaces || []).concat(
304
292
  assets.namespace
305
293
  ? { binding: "__STATIC_CONTENT", id: assets.namespace }
306
294
  : []
307
295
  ),
308
296
  text_blobs: {
309
- ...bindings.text_blobs,
297
+ ...props.bindings.text_blobs,
310
298
  ...(assets.manifest &&
311
- format === "service-worker" && {
299
+ props.format === "service-worker" && {
312
300
  __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
313
301
  }),
314
302
  },
315
303
  },
316
304
  migrations: undefined, // no migrations in dev
317
- compatibility_date: compatibilityDate,
318
- compatibility_flags: compatibilityFlags,
319
- usage_model: usageModel,
320
- keep_bindings: true,
305
+ compatibility_date: props.compatibilityDate,
306
+ compatibility_flags: props.compatibilityFlags,
307
+ usage_model: props.usageModel,
308
+ keepVars: true,
321
309
  };
322
310
 
323
311
  const workerAccount: CfAccount = {
324
- accountId,
312
+ accountId: props.accountId,
325
313
  apiToken: requireApiToken(),
326
314
  };
327
315
 
@@ -364,7 +352,6 @@ export function useWorker(props: {
364
352
  });
365
353
  }
366
354
  */
367
-
368
355
  onReady?.(props.host || "localhost", props.port);
369
356
  }
370
357
  start().catch((err) => {
@@ -379,7 +366,7 @@ export function useWorker(props: {
379
366
  "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
380
367
  const solutionMessage =
381
368
  "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
382
- const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
369
+ const onboardingLink = `https://dash.cloudflare.com/${props.accountId}/workers/onboarding`;
383
370
  logger.error(
384
371
  `${errorMessage}\n${solutionMessage}\n${onboardingLink}`
385
372
  );
@@ -400,17 +387,17 @@ export function useWorker(props: {
400
387
  abortController.abort();
401
388
  };
402
389
  }, [
403
- name,
404
- bundle,
405
- format,
406
- accountId,
407
- assetPaths,
390
+ props.name,
391
+ props.bundle,
392
+ props.format,
393
+ props.accountId,
394
+ props.assetPaths,
408
395
  props.isWorkersSite,
409
- compatibilityDate,
410
- compatibilityFlags,
411
- usageModel,
412
- bindings,
413
- modules,
396
+ props.compatibilityDate,
397
+ props.compatibilityFlags,
398
+ props.usageModel,
399
+ props.bindings,
400
+ props.modules,
414
401
  props.env,
415
402
  props.legacyEnv,
416
403
  props.zone,
@@ -421,5 +408,6 @@ export function useWorker(props: {
421
408
  props.sendMetrics,
422
409
  props.port,
423
410
  ]);
411
+
424
412
  return token;
425
413
  }