forked from cloudflare/workers-sdk
-
Notifications
You must be signed in to change notification settings - Fork 2
/
deploy.test.ts
12877 lines (11991 loc) · 396 KB
/
deploy.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Buffer } from "node:buffer";
import { spawnSync } from "node:child_process";
import { randomFillSync } from "node:crypto";
import * as fs from "node:fs";
import * as path from "node:path";
import * as TOML from "@iarna/toml";
import { sync } from "command-exists";
import * as esbuild from "esbuild";
import { http, HttpResponse } from "msw";
import dedent from "ts-dedent";
import { File } from "undici";
import { vi } from "vitest";
import {
printBundleSize,
printOffendingDependencies,
} from "../deployment-bundle/bundle-reporter";
import { writeAuthConfigFile } from "../user";
import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
import { mockAuthDomain } from "./helpers/mock-auth-domain";
import { mockConsoleMethods } from "./helpers/mock-console";
import { clearDialogs, mockConfirm } from "./helpers/mock-dialogs";
import { mockGetZoneFromHostRequest } from "./helpers/mock-get-zone-from-host";
import { useMockIsTTY } from "./helpers/mock-istty";
import { mockCollectKnownRoutesRequest } from "./helpers/mock-known-routes";
import {
mockKeyListRequest,
mockListKVNamespacesRequest,
} from "./helpers/mock-kv";
import {
mockExchangeRefreshTokenForAccessToken,
mockGetMemberships,
mockOAuthFlow,
} from "./helpers/mock-oauth-flow";
import { mockUploadWorkerRequest } from "./helpers/mock-upload-worker";
import {
mockGetWorkerSubdomain,
mockSubDomainRequest,
mockUpdateWorkerSubdomain,
} from "./helpers/mock-workers-subdomain";
import {
createFetchResult,
msw,
mswSuccessDeployments,
mswSuccessDeploymentScriptAPI,
mswSuccessDeploymentScriptMetadata,
mswSuccessOauthHandlers,
mswSuccessUserHandlers,
} from "./helpers/msw";
import { mswListNewDeploymentsLatestFull } from "./helpers/msw/handlers/versions";
import { normalizeString } from "./helpers/normalize";
import { runInTempDir } from "./helpers/run-in-tmp";
import { runWrangler } from "./helpers/run-wrangler";
import { writeWorkerSource } from "./helpers/write-worker-source";
import { writeWranglerConfig } from "./helpers/write-wrangler-config";
import type { AssetManifest } from "../assets";
import type { Config } from "../config";
import type { CustomDomain, CustomDomainChangeset } from "../deploy/deploy";
import type {
PostQueueBody,
PostTypedConsumerBody,
QueueResponse,
} from "../queues/client";
import type { FormData } from "undici";
import type { Mock } from "vitest";
vi.mock("command-exists");
describe("deploy", () => {
mockAccountId();
mockApiToken();
runInTempDir();
const { setIsTTY } = useMockIsTTY();
const std = mockConsoleMethods();
const {
mockOAuthServerCallback,
mockGrantAccessToken,
mockDomainUsesAccess,
} = mockOAuthFlow();
beforeEach(() => {
vi.stubGlobal("setTimeout", (fn: () => void) => {
setImmediate(fn);
});
setIsTTY(true);
mockLastDeploymentRequest();
mockDeploymentsListRequest();
msw.use(...mswListNewDeploymentsLatestFull);
});
afterEach(() => {
vi.unstubAllGlobals();
clearDialogs();
});
it("should output log file with deployment details", async () => {
vi.stubEnv("WRANGLER_OUTPUT_FILE_DIRECTORY", "output");
vi.stubEnv("WRANGLER_OUTPUT_FILE_PATH", "");
writeWorkerSource();
writeWranglerConfig({
routes: ["example.com/some-route/*"],
workers_dev: true,
});
mockUploadWorkerRequest();
mockSubDomainRequest();
mockGetWorkerSubdomain({ enabled: true });
mockPublishRoutesRequest({ routes: ["example.com/some-route/*"] });
await runWrangler("deploy ./index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
example.com/some-route/*
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
const outputFilePaths = fs.readdirSync("output");
expect(outputFilePaths.length).toEqual(1);
expect(outputFilePaths[0]).toMatch(/wrangler-output-.+\.json/);
const outputFile = fs.readFileSync(
path.join("output", outputFilePaths[0]),
"utf8"
);
const entries = outputFile
.split("\n")
.filter(Boolean)
.map((e) => JSON.parse(e));
expect(entries.find((e) => e.type === "deploy")).toMatchObject({
targets: [
"https://test-name.test-sub-domain.workers.dev",
"example.com/some-route/*",
],
// Omitting timestamp for matching
// timestamp: ...
type: "deploy",
version: 1,
version_id: "Galaxy-Class",
worker_name: "test-name",
worker_tag: "tag:test-name",
});
});
it("should successfully deploy with CI tag match", async () => {
vi.stubEnv("WRANGLER_CI_MATCH_TAG", "abc123");
writeWorkerSource();
writeWranglerConfig({
routes: ["example.com/some-route/*"],
workers_dev: true,
});
mockServiceScriptData({
scriptName: "test-name",
script: { id: "test-name", tag: "abc123" },
});
mockUploadWorkerRequest();
mockSubDomainRequest();
mockGetWorkerSubdomain({ enabled: false });
mockUpdateWorkerSubdomain({ enabled: true });
mockPublishRoutesRequest({ routes: ["example.com/some-route/*"] });
await runWrangler("deploy ./index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
example.com/some-route/*
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
it("should resolve wrangler.toml relative to the entrypoint", async () => {
fs.mkdirSync("./some-path/worker", { recursive: true });
fs.writeFileSync(
"./some-path/wrangler.toml",
TOML.stringify({
name: "test-name",
compatibility_date: "2022-01-12",
vars: { xyz: 123 },
}),
"utf-8"
);
writeWorkerSource({ basePath: "./some-path/worker" });
mockUploadWorkerRequest({
expectedBindings: [
{
json: 123,
name: "xyz",
type: "json",
},
],
expectedCompatibilityDate: "2022-01-12",
});
mockSubDomainRequest();
await runWrangler("deploy ./some-path/worker/index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Your worker has access to the following bindings:
- Vars:
- xyz: 123
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
it("should support wrangler.json", async () => {
fs.mkdirSync("./my-worker", { recursive: true });
fs.writeFileSync(
"./wrangler.json",
JSON.stringify({
name: "test-worker",
compatibility_date: "2024-01-01",
vars: { xyz: 123 },
}),
"utf-8"
);
writeWorkerSource({ basePath: "./my-worker" });
mockUploadWorkerRequest({
expectedScriptName: "test-worker",
expectedBindings: [
{
json: 123,
name: "xyz",
type: "json",
},
],
expectedCompatibilityDate: "2024-01-01",
});
mockSubDomainRequest();
await runWrangler("deploy ./my-worker/index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Your worker has access to the following bindings:
- Vars:
- xyz: 123
Uploaded test-worker (TIMINGS)
Deployed test-worker triggers (TIMINGS)
https://test-worker.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
it("should include serialised FormData in debug logs", async () => {
fs.mkdirSync("./my-worker", { recursive: true });
fs.writeFileSync(
"./my-worker/wrangler.toml",
TOML.stringify({
name: "test-worker",
compatibility_date: "2022-01-12",
vars: { xyz: 123 },
}),
"utf-8"
);
writeWorkerSource({ basePath: "./my-worker" });
mockUploadWorkerRequest({
expectedScriptName: "test-worker",
expectedBindings: [
{
json: 123,
name: "xyz",
type: "json",
},
],
expectedCompatibilityDate: "2022-01-12",
});
mockSubDomainRequest();
vi.stubEnv("WRANGLER_LOG", "debug");
vi.stubEnv("WRANGLER_LOG_SANITIZE", "false");
await runWrangler("deploy ./my-worker/index.js");
expect(std.debug).toContain(
`{"main_module":"index.js","bindings":[{"name":"xyz","type":"json","json":123}],"compatibility_date":"2022-01-12","compatibility_flags":[]}`
);
});
it("should support wrangler.jsonc", async () => {
fs.mkdirSync("./my-worker", { recursive: true });
fs.writeFileSync(
"./wrangler.jsonc",
JSON.stringify({
name: "test-worker-jsonc",
compatibility_date: "2024-01-01",
vars: { xyz: 123 },
}),
"utf-8"
);
writeWorkerSource({ basePath: "./my-worker" });
mockUploadWorkerRequest({
expectedScriptName: "test-worker-jsonc",
expectedBindings: [
{
json: 123,
name: "xyz",
type: "json",
},
],
expectedCompatibilityDate: "2024-01-01",
});
mockSubDomainRequest();
await runWrangler("deploy ./my-worker/index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Your worker has access to the following bindings:
- Vars:
- xyz: 123
Uploaded test-worker-jsonc (TIMINGS)
Deployed test-worker-jsonc triggers (TIMINGS)
https://test-worker-jsonc.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
it("should not deploy if there's any other kind of error when checking deployment source", async () => {
writeWorkerSource();
writeWranglerConfig();
mockSubDomainRequest();
mockUploadWorkerRequest();
msw.use(...mswSuccessOauthHandlers, ...mswSuccessUserHandlers);
msw.use(
http.get("*/accounts/:accountId/workers/services/:scriptName", () => {
return HttpResponse.json(
createFetchResult(null, false, [
{ code: 10000, message: "Authentication error" },
])
);
}),
http.get(
"*/accounts/:accountId/workers/deployments/by-script/:scriptTag",
() => {
return HttpResponse.json(
createFetchResult({
latest: { number: "2" },
})
);
}
)
);
await expect(
runWrangler("deploy index.js")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[APIError: A request to the Cloudflare API (/accounts/some-account-id/workers/services/test-name) failed.]`
);
expect(std.out).toMatchInlineSnapshot(`
"
[31mX [41;31m[[41;97mERROR[41;31m][0m [1mA request to the Cloudflare API (/accounts/some-account-id/workers/services/test-name) failed.[0m
Authentication error [code: 10000]
📎 It looks like you are authenticating Wrangler via a custom API token set in an environment variable.
Please ensure it has the correct permissions for this operation.
Getting User settings...
ℹ️ The API Token is read from the CLOUDFLARE_API_TOKEN in your environment.
👋 You are logged in with an API Token, associated with the email [email protected].
┌───────────────┬────────────┐
│ Account Name │ Account ID │
├───────────────┼────────────┤
│ Account One │ account-1 │
├───────────────┼────────────┤
│ Account Two │ account-2 │
├───────────────┼────────────┤
│ Account Three │ account-3 │
└───────────────┴────────────┘
🔓 To see token permissions visit https://dash.cloudflare.com/profile/api-tokens."
`);
});
it("should error helpfully if pages_build_output_dir is set in wrangler.toml", async () => {
writeWranglerConfig({
pages_build_output_dir: "public",
name: "test-name",
});
await expect(
runWrangler("deploy")
).rejects.toThrowErrorMatchingInlineSnapshot(
`
[Error: It looks like you've run a Workers-specific command in a Pages project.
For Pages, please run \`wrangler pages deploy\` instead.]
`
);
});
describe("output additional script information", () => {
it("for first party workers, it should print worker information at log level", async () => {
setIsTTY(false);
fs.writeFileSync(
"./wrangler.toml",
TOML.stringify({
compatibility_date: "2022-01-12",
name: "test-name",
first_party_worker: true,
}),
"utf-8"
);
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest({
expectedType: "esm",
useOldUploadApi: true,
});
mockOAuthServerCallback();
await runWrangler("deploy ./index");
expect(std).toMatchInlineSnapshot(`
Object {
"debug": "",
"err": "",
"info": "",
"out": "Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Worker ID: abc12345
Worker ETag: etag98765
Worker PipelineHash: hash9999
Worker Mutable PipelineID (Development ONLY!): mutableId
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class",
"warn": "",
}
`);
});
});
describe("authentication", () => {
mockApiToken({ apiToken: null });
beforeEach(() => {
vi.unstubAllGlobals();
});
it("drops a user into the login flow if they're unauthenticated", async () => {
setIsTTY(true);
writeWranglerConfig();
writeWorkerSource();
mockDomainUsesAccess({ usesAccess: false });
mockSubDomainRequest();
mockUploadWorkerRequest();
mockExchangeRefreshTokenForAccessToken({ respondWith: "refreshSuccess" });
mockOAuthServerCallback("success");
mockDeploymentsListRequest();
await expect(runWrangler("deploy index.js")).resolves.toBeUndefined();
expect(std.out).toMatchInlineSnapshot(`
"Attempting to login via OAuth...
Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=54d11594-84e4-41aa-b438-e81b8fa78ee7&redirect_uri=http%3A%2F%2Flocalhost%3A8976%2Foauth%2Fcallback&scope=account%3Aread%20user%3Aread%20workers%3Awrite%20workers_kv%3Awrite%20workers_routes%3Awrite%20workers_scripts%3Awrite%20workers_tail%3Aread%20d1%3Awrite%20pages%3Awrite%20zone%3Aread%20ssl_certs%3Awrite%20ai%3Awrite%20queues%3Awrite%20pipelines%3Awrite%20offline_access&state=MOCK_STATE_PARAM&code_challenge=MOCK_CODE_CHALLENGE&code_challenge_method=S256
Successfully logged in.
Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.warn).toMatchInlineSnapshot(`""`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
describe("with an alternative auth domain", () => {
mockAuthDomain({ domain: "dash.staging.cloudflare.com" });
it("drops a user into the login flow if they're unauthenticated", async () => {
writeWranglerConfig();
writeWorkerSource();
mockDomainUsesAccess({
usesAccess: false,
domain: "dash.staging.cloudflare.com",
});
mockSubDomainRequest();
mockUploadWorkerRequest();
mockExchangeRefreshTokenForAccessToken({
respondWith: "refreshSuccess",
});
const accessTokenRequest = mockGrantAccessToken({
respondWith: "ok",
domain: "dash.staging.cloudflare.com",
});
mockOAuthServerCallback("success");
mockDeploymentsListRequest();
await expect(runWrangler("deploy index.js")).resolves.toBeUndefined();
expect(accessTokenRequest.actual).toEqual(accessTokenRequest.expected);
expect(std.out).toMatchInlineSnapshot(`
"Attempting to login via OAuth...
Opening a link in your default browser: https://dash.staging.cloudflare.com/oauth2/auth?response_type=code&client_id=54d11594-84e4-41aa-b438-e81b8fa78ee7&redirect_uri=http%3A%2F%2Flocalhost%3A8976%2Foauth%2Fcallback&scope=account%3Aread%20user%3Aread%20workers%3Awrite%20workers_kv%3Awrite%20workers_routes%3Awrite%20workers_scripts%3Awrite%20workers_tail%3Aread%20d1%3Awrite%20pages%3Awrite%20zone%3Aread%20ssl_certs%3Awrite%20ai%3Awrite%20queues%3Awrite%20pipelines%3Awrite%20offline_access&state=MOCK_STATE_PARAM&code_challenge=MOCK_CODE_CHALLENGE&code_challenge_method=S256
Successfully logged in.
Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.warn).toMatchInlineSnapshot(`""`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
});
it("warns a user when they're authenticated with an API token in wrangler config file", async () => {
writeWranglerConfig();
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
writeAuthConfigFile({
api_token: "some-api-token",
});
await expect(runWrangler("deploy index.js")).resolves.toBeUndefined();
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mIt looks like you have used Wrangler v1's \`config\` command to login with an API token.[0m
This is no longer supported in the current version of Wrangler.
If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\`
environment variable.
"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
describe("non-TTY", () => {
it("should not throw an error in non-TTY if 'CLOUDFLARE_API_TOKEN' & 'account_id' are in scope", async () => {
vi.stubEnv("CLOUDFLARE_API_TOKEN", "123456789");
setIsTTY(false);
writeWranglerConfig({
account_id: "some-account-id",
});
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
mockOAuthServerCallback();
await runWrangler("deploy index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
it("should not throw an error if 'CLOUDFLARE_ACCOUNT_ID' & 'CLOUDFLARE_API_TOKEN' are in scope", async () => {
vi.stubEnv("CLOUDFLARE_API_TOKEN", "hunter2");
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "some-account-id");
setIsTTY(false);
writeWranglerConfig();
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
mockOAuthServerCallback();
mockGetMemberships([]);
await runWrangler("deploy index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
it("should throw an error in non-TTY & there is more than one account associated with API token", async () => {
setIsTTY(false);
vi.stubEnv("CLOUDFLARE_API_TOKEN", "hunter2");
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "");
writeWranglerConfig({
account_id: undefined,
});
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
mockOAuthServerCallback();
mockGetMemberships([
{ id: "IG-88", account: { id: "1701", name: "enterprise" } },
{ id: "R2-D2", account: { id: "nx01", name: "enterprise-nx" } },
]);
await expect(runWrangler("deploy index.js")).rejects
.toMatchInlineSnapshot(`
[Error: More than one account available but unable to select one in non-interactive mode.
Please set the appropriate \`account_id\` in your Wrangler configuration file.
Available accounts are (\`<name>\`: \`<account_id>\`):
\`enterprise\`: \`1701\`
\`enterprise-nx\`: \`nx01\`]
`);
});
it("should throw error in non-TTY if 'CLOUDFLARE_API_TOKEN' is missing", async () => {
setIsTTY(false);
writeWranglerConfig({
account_id: undefined,
});
vi.stubEnv("CLOUDFLARE_API_TOKEN", "");
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "badwolf");
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
mockOAuthServerCallback();
mockGetMemberships([
{ id: "IG-88", account: { id: "1701", name: "enterprise" } },
{ id: "R2-D2", account: { id: "nx01", name: "enterprise-nx" } },
]);
await expect(runWrangler("deploy index.js")).rejects.toThrowError();
expect(std.err).toMatchInlineSnapshot(`
"[31mX [41;31m[[41;97mERROR[41;31m][0m [1mIn a non-interactive environment, it's necessary to set a CLOUDFLARE_API_TOKEN environment variable for wrangler to work. Please go to https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN.[0m
"
`);
});
it("should throw error with no account ID provided and no members retrieved", async () => {
setIsTTY(false);
writeWranglerConfig({
account_id: undefined,
});
vi.stubEnv("CLOUDFLARE_API_TOKEN", "picard");
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "");
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
mockOAuthServerCallback();
mockGetMemberships([]);
await expect(runWrangler("deploy index.js")).rejects.toThrowError();
expect(std.err).toMatchInlineSnapshot(`
"[31mX [41;31m[[41;97mERROR[41;31m][0m [1mFailed to automatically retrieve account IDs for the logged in user.[0m
In a non-interactive environment, it is mandatory to specify an account ID, either by assigning
its value to CLOUDFLARE_ACCOUNT_ID, or as \`account_id\` in your Wrangler configuration file.
"
`);
});
});
});
describe("warnings", () => {
it("should warn user when worker was last deployed from api", async () => {
msw.use(...mswSuccessDeploymentScriptAPI);
writeWranglerConfig();
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
mockConfirm({
text: "Would you like to continue?",
result: false,
});
await runWrangler("deploy ./index");
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mYou are about to publish a Workers Service that was last updated via the script API.[0m
Edits that have been made via the script API will be overridden by your local code and config.
"
`);
});
it("should warn user when additional properties are passed to a services config", async () => {
writeWranglerConfig({
d1_databases: [
{
binding: "MY_DB",
database_name: "my-database",
database_id: "xxxxxxxxx",
// @ts-expect-error Depending on a users editor setup a type error in the toml will not be displayed.
// This test is checking that warnings for type errors are displayed
tail_consumers: [{ service: "<TAIL_WORKER_NAME>" }],
},
],
});
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest();
await runWrangler("deploy ./index");
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mProcessing wrangler.toml configuration:[0m
- Unexpected fields found in d1_databases[0] field: \\"tail_consumers\\"
"
`);
});
it("should log esbuild warnings", async () => {
writeWranglerConfig();
fs.writeFileSync(
"index.js",
dedent/* javascript */ `
export default {
fetch() {
return
new Response(dep);
}
}
`
);
mockSubDomainRequest();
mockUploadWorkerRequest();
await runWrangler("deploy ./index");
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mThe following expression is not returned because of an automatically-inserted semicolon[0m [semicolon-after-return]
index.js:3:8:
[37m 3 │ return[32m[37m
╵ [32m^[0m
"
`);
});
});
describe("environments", () => {
it("should use legacy environments by default", async () => {
writeWranglerConfig({ env: { "some-env": {} } });
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest({
env: "some-env",
legacyEnv: true,
});
await runWrangler("deploy index.js --env some-env");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name-some-env (TIMINGS)
Deployed test-name-some-env triggers (TIMINGS)
https://test-name-some-env.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`""`);
});
describe("legacy", () => {
it("uses the script name when no environment is specified", async () => {
writeWranglerConfig();
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest({
legacyEnv: true,
});
await runWrangler("deploy index.js --legacy-env true");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`""`);
});
it("appends the environment name when provided, and there is associated config", async () => {
writeWranglerConfig({ env: { "some-env": {} } });
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest({
env: "some-env",
legacyEnv: true,
});
await runWrangler("deploy index.js --env some-env --legacy-env true");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name-some-env (TIMINGS)
Deployed test-name-some-env triggers (TIMINGS)
https://test-name-some-env.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`""`);
});
it("appends the environment name when provided (with a warning), if there are no configured environments", async () => {
writeWranglerConfig({});
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest({
env: "some-env",
legacyEnv: true,
});
await runWrangler("deploy index.js --env some-env --legacy-env true");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name-some-env (TIMINGS)
Deployed test-name-some-env triggers (TIMINGS)
https://test-name-some-env.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mProcessing wrangler.toml configuration:[0m
- No environment found in configuration with name \\"some-env\\".
Before using \`--env=some-env\` there should be an equivalent environment section in the
configuration.
Consider adding an environment configuration section to the wrangler.toml file:
\`\`\`
[env.some-env]
\`\`\`
"
`);
});
it("should throw an error when an environment name when provided, which doesn't match those in the config", async () => {
writeWranglerConfig({ env: { "other-env": {} } });
writeWorkerSource();
mockSubDomainRequest();
await expect(
runWrangler("deploy index.js --env some-env --legacy-env true")
).rejects.toThrowErrorMatchingInlineSnapshot(`
[Error: Processing wrangler.toml configuration:
- No environment found in configuration with name "some-env".
Before using \`--env=some-env\` there should be an equivalent environment section in the configuration.
The available configured environment names are: ["other-env"]
Consider adding an environment configuration section to the wrangler.toml file:
\`\`\`
[env.some-env]
\`\`\`
]
`);
});
it("should throw an error w/ helpful message when using --env --name", async () => {
writeWranglerConfig({ env: { "some-env": {} } });
writeWorkerSource();
mockSubDomainRequest();
await runWrangler(
"deploy index.js --name voyager --env some-env --legacy-env true"
).catch((err) =>
expect(err).toMatchInlineSnapshot(`
[Error: In legacy environment mode you cannot use --name and --env together. If you want to specify a Worker name for a specific environment you can add the following to your wrangler.toml file:
[env.some-env]
name = "voyager"
]
`)
);
});
});
describe("services", () => {
it("uses the script name when no environment is specified", async () => {
writeWranglerConfig();
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest({
legacyEnv: false,
});
await runWrangler("deploy index.js --legacy-env false");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mProcessing wrangler.toml configuration:[0m
- Experimental: Service environments are in beta, and their behaviour is guaranteed to change in
the future. DO NOT USE IN PRODUCTION.
"
`);
});
it("publishes as an environment when provided", async () => {
writeWranglerConfig({ env: { "some-env": {} } });
writeWorkerSource();
mockSubDomainRequest();
mockUploadWorkerRequest({
env: "some-env",
legacyEnv: false,
useOldUploadApi: true,
});
await runWrangler("deploy index.js --env some-env --legacy-env false");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Uploaded test-name (some-env) (TIMINGS)
Deployed test-name (some-env) triggers (TIMINGS)
https://some-env.test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mProcessing wrangler.toml configuration:[0m
- Experimental: Service environments are in beta, and their behaviour is guaranteed to change in
the future. DO NOT USE IN PRODUCTION.
"
`);
});
});
});
it("should resolve wrangler.toml relative to the entrypoint", async () => {
fs.mkdirSync("./some-path/worker", { recursive: true });
fs.writeFileSync(
"./some-path/wrangler.toml",
TOML.stringify({
name: "test-name",
compatibility_date: "2022-01-12",
vars: { xyz: 123 },
}),
"utf-8"
);
writeWorkerSource({ basePath: "./some-path/worker" });
mockUploadWorkerRequest({
expectedBindings: [
{
json: 123,
name: "xyz",
type: "json",
},
],
expectedCompatibilityDate: "2022-01-12",
});
mockSubDomainRequest();
await runWrangler("deploy ./some-path/worker/index.js");
expect(std.out).toMatchInlineSnapshot(`
"Total Upload: xx KiB / gzip: xx KiB
Worker Startup Time: 100 ms
Your worker has access to the following bindings:
- Vars:
- xyz: 123
Uploaded test-name (TIMINGS)
Deployed test-name triggers (TIMINGS)
https://test-name.test-sub-domain.workers.dev
Current Version ID: Galaxy-Class"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
});
describe("routes", () => {
it("should deploy the worker to a route", async () => {