@cdwr/fly-node 0.3.1 → 0.3.3

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/index.js CHANGED
@@ -1,46 +1,63 @@
1
- // packages/fly-node/src/lib/schemas/certificate.schema.ts
1
+ // packages/fly-node/src/lib/schemas/app-ip-addresses.schema.ts
2
+ import { z as z2 } from "zod";
3
+
4
+ // packages/fly-node/src/lib/schemas/ip-type.schema.ts
2
5
  import { z } from "zod";
3
- var CertificateApiResponseSchema = z.object({
4
- hostname: z.string(),
6
+ var IpTypeSchema = z.enum(["v4", "v6", "shared_v4", "private_v6"]).or(z.string());
7
+
8
+ // packages/fly-node/src/lib/schemas/app-ip-addresses.schema.ts
9
+ var AppIpAddressSchema = z2.object({
10
+ address: z2.string(),
11
+ type: IpTypeSchema
12
+ });
13
+ var AppIpAddressesApiResponseSchema = z2.object({
14
+ sharedIpAddress: z2.string().nullish(),
15
+ ipAddresses: z2.object({ nodes: z2.array(AppIpAddressSchema) })
16
+ });
17
+
18
+ // packages/fly-node/src/lib/schemas/certificate.schema.ts
19
+ import { z as z3 } from "zod";
20
+ var CertificateApiResponseSchema = z3.object({
21
+ hostname: z3.string(),
5
22
  /** Issued and serving. This is what decides whether a domain is usable */
6
- isConfigured: z.boolean(),
7
- id: z.string().optional(),
23
+ isConfigured: z3.boolean(),
24
+ id: z3.string().optional(),
8
25
  /** The apex or a subdomain — apex domains cannot use a CNAME */
9
- isApex: z.boolean().optional(),
10
- isWildcard: z.boolean().optional(),
26
+ isApex: z3.boolean().optional(),
27
+ isWildcard: z3.boolean().optional(),
11
28
  /** Which ACME challenge has been satisfied, if any */
12
- isAcmeDnsConfigured: z.boolean().optional(),
13
- isAcmeAlpnConfigured: z.boolean().optional(),
14
- isAcmeHttpConfigured: z.boolean().optional(),
15
- certificateAuthority: z.string().nullish(),
16
- certificateRequestedAt: z.string().nullish(),
17
- createdAt: z.string().nullish(),
18
- domain: z.string().nullish(),
19
- dnsProvider: z.string().nullish(),
29
+ isAcmeDnsConfigured: z3.boolean().optional(),
30
+ isAcmeAlpnConfigured: z3.boolean().optional(),
31
+ isAcmeHttpConfigured: z3.boolean().optional(),
32
+ certificateAuthority: z3.string().nullish(),
33
+ certificateRequestedAt: z3.string().nullish(),
34
+ createdAt: z3.string().nullish(),
35
+ domain: z3.string().nullish(),
36
+ dnsProvider: z3.string().nullish(),
20
37
  /** Hostname the validation record must be created on */
21
- dnsValidationHostname: z.string().nullish(),
38
+ dnsValidationHostname: z3.string().nullish(),
22
39
  /** Value that record must contain */
23
- dnsValidationTarget: z.string().nullish(),
40
+ dnsValidationTarget: z3.string().nullish(),
24
41
  /** Fly's own prose describing the records to create */
25
- dnsValidationInstructions: z.string().nullish(),
42
+ dnsValidationInstructions: z3.string().nullish(),
26
43
  /** Fly's summary of where issuance has got to */
27
- clientStatus: z.string().nullish(),
44
+ clientStatus: z3.string().nullish(),
28
45
  /**
29
46
  * Set when Let's Encrypt has rate-limited further attempts for this domain.
30
47
  *
31
48
  * Worth surfacing rather than swallowing: it is the one failure a customer
32
49
  * cannot fix by correcting DNS, and retrying only makes it worse.
33
50
  */
34
- rateLimitedUntil: z.string().nullish(),
35
- source: z.string().nullish(),
51
+ rateLimitedUntil: z3.string().nullish(),
52
+ source: z3.string().nullish(),
36
53
  /**
37
54
  * Fly's own prose for a failed issuance attempt — what the dashboard shows,
38
55
  * unlike `HostnameCheck.errors`, which is SCREAMING_SNAKE_CASE codes
39
56
  */
40
- validationErrors: z.array(
41
- z.object({
42
- message: z.string(),
43
- timestamp: z.string()
57
+ validationErrors: z3.array(
58
+ z3.object({
59
+ message: z3.string(),
60
+ timestamp: z3.string()
44
61
  })
45
62
  ).nullish(),
46
63
  /**
@@ -50,52 +67,52 @@ var CertificateApiResponseSchema = z.object({
50
67
  * nodes is the normal count — one RSA and one ECDSA — sharing an expiry,
51
68
  * which is why a caller usually wants the expiry rather than the rows.
52
69
  */
53
- issued: z.object({
54
- nodes: z.array(
55
- z.object({
56
- id: z.string().nullish(),
70
+ issued: z3.object({
71
+ nodes: z3.array(
72
+ z3.object({
73
+ id: z3.string().nullish(),
57
74
  /** Key type, e.g. `RSA` or `ECDSA` */
58
- type: z.string().nullish(),
59
- hostname: z.string().nullish(),
60
- expiresAt: z.string().nullish()
75
+ type: z3.string().nullish(),
76
+ hostname: z3.string().nullish(),
77
+ expiresAt: z3.string().nullish()
61
78
  })
62
79
  ).nullish()
63
80
  }).nullish()
64
81
  });
65
- var HostnameCheckApiResponseSchema = z.object({
66
- aRecords: z.array(z.string()).nullish(),
67
- aaaaRecords: z.array(z.string()).nullish(),
68
- cnameRecords: z.array(z.string()).nullish(),
69
- caaRecords: z.array(z.string()).nullish(),
70
- soa: z.string().nullish(),
71
- dnsProvider: z.string().nullish(),
72
- dnsVerificationRecord: z.string().nullish(),
73
- dnsConfigured: z.boolean().nullish(),
74
- acmeDnsConfigured: z.boolean().nullish(),
75
- resolvedAddresses: z.array(z.string()).nullish(),
76
- isProxied: z.boolean().nullish(),
77
- errors: z.array(z.string()).nullish()
82
+ var HostnameCheckApiResponseSchema = z3.object({
83
+ aRecords: z3.array(z3.string()).nullish(),
84
+ aaaaRecords: z3.array(z3.string()).nullish(),
85
+ cnameRecords: z3.array(z3.string()).nullish(),
86
+ caaRecords: z3.array(z3.string()).nullish(),
87
+ soa: z3.string().nullish(),
88
+ dnsProvider: z3.string().nullish(),
89
+ dnsVerificationRecord: z3.string().nullish(),
90
+ dnsConfigured: z3.boolean().nullish(),
91
+ acmeDnsConfigured: z3.boolean().nullish(),
92
+ resolvedAddresses: z3.array(z3.string()).nullish(),
93
+ isProxied: z3.boolean().nullish(),
94
+ errors: z3.array(z3.string()).nullish()
78
95
  });
79
- var DnsInstructionsSchema = z.object({
80
- hostname: z.string().nullish(),
81
- target: z.string().nullish(),
82
- instructions: z.string().nullish(),
83
- isApex: z.boolean().optional()
96
+ var DnsInstructionsSchema = z3.object({
97
+ hostname: z3.string().nullish(),
98
+ target: z3.string().nullish(),
99
+ instructions: z3.string().nullish(),
100
+ isApex: z3.boolean().optional()
84
101
  });
85
- var CertificateListApiResponseSchema = z.array(
102
+ var CertificateListApiResponseSchema = z3.array(
86
103
  CertificateApiResponseSchema
87
104
  );
88
105
 
89
106
  // packages/fly-node/src/lib/schemas/machine.schema.ts
90
- import { z as z2 } from "zod";
91
- var MachineApiResponseSchema = z2.object({
92
- id: z2.string(),
93
- name: z2.string().nullish(),
107
+ import { z as z4 } from "zod";
108
+ var MachineApiResponseSchema = z4.object({
109
+ id: z4.string(),
110
+ name: z4.string().nullish(),
94
111
  /** `started`, `stopped`, `suspended`, … — Fly owns this vocabulary */
95
- state: z2.string().nullish(),
96
- region: z2.string().nullish()
112
+ state: z4.string().nullish(),
113
+ region: z4.string().nullish()
97
114
  });
98
- var MachineListApiResponseSchema = z2.array(MachineApiResponseSchema);
115
+ var MachineListApiResponseSchema = z4.array(MachineApiResponseSchema);
99
116
 
100
117
  // packages/fly-node/src/lib/fly-api.class.ts
101
118
  var FLY_API_URL = "https://api.fly.io/graphql";
@@ -288,6 +305,42 @@ var FlyApi = class {
288
305
  );
289
306
  }
290
307
  };
308
+ /** Read an app's addresses */
309
+ ips = {
310
+ /**
311
+ * The addresses an app answers on: `shared_v4`, `v4`, `v6`, and its
312
+ * `private_v6`.
313
+ *
314
+ * The shared v4 is folded in as a `shared_v4` row, the way `fly ips list`
315
+ * shows it; Fly's API keeps it in a separate field. Egress addresses,
316
+ * which the CLI also lists, are not part of this API and never appear.
317
+ * Pick the public types before pointing DNS at them.
318
+ *
319
+ * Rejects for an unknown app, like `certs.list`: a typo in an app name
320
+ * must not read as "this app has no addresses".
321
+ *
322
+ * @returns The addresses, empty when the app has none
323
+ */
324
+ list: async (app) => {
325
+ const data = await this.request(
326
+ `query AppIpAddresses($appName: String!) {
327
+ app(name: $appName) {
328
+ sharedIpAddress
329
+ ipAddresses { nodes { address type } }
330
+ }
331
+ }`,
332
+ { appName: app }
333
+ );
334
+ if (!data.app) {
335
+ return [];
336
+ }
337
+ const { sharedIpAddress, ipAddresses } = AppIpAddressesApiResponseSchema.parse(data.app);
338
+ return [
339
+ ...sharedIpAddress ? [{ address: sharedIpAddress, type: "shared_v4" }] : [],
340
+ ...ipAddresses.nodes
341
+ ];
342
+ }
343
+ };
291
344
  /**
292
345
  * Operate an app's machines.
293
346
  *
@@ -503,6 +556,18 @@ var killProcessTree = promisify2(treeKill);
503
556
  import {
504
557
  spawn as cpSpawn
505
558
  } from "child_process";
559
+ var STREAMED_STDERR_TAIL_LINES = 20;
560
+ var SpawnError = class extends Error {
561
+ exitCode;
562
+ stdout;
563
+ stderr;
564
+ constructor(message, details) {
565
+ super(message);
566
+ this.exitCode = details.exitCode;
567
+ this.stdout = details.stdout;
568
+ this.stderr = details.stderr;
569
+ }
570
+ };
506
571
  function spawn(command, args, options) {
507
572
  return new Promise((resolve, reject) => {
508
573
  const { streamToConsole, ...spawnOptions } = options || {};
@@ -530,8 +595,12 @@ function spawn(command, args, options) {
530
595
  if (code === 0) {
531
596
  resolve({ stdout, stderr });
532
597
  } else {
533
- reject(new Error(`Process exited with code ${code}
534
- Error: ${stderr}`));
598
+ const lines = stderr.replace(/\r?\n$/, "").split(/\r?\n/);
599
+ const message = streamToConsole && lines.length > STREAMED_STDERR_TAIL_LINES ? `Process exited with code ${code}
600
+ Error (last ${STREAMED_STDERR_TAIL_LINES} lines; the full output is above):
601
+ ${lines.slice(-STREAMED_STDERR_TAIL_LINES).join("\n")}` : `Process exited with code ${code}
602
+ Error: ${stderr}`;
603
+ reject(new SpawnError(message, { exitCode: code, stdout, stderr }));
535
604
  }
536
605
  });
537
606
  process2.on("error", reject);
@@ -576,20 +645,20 @@ Output: ${output}`)
576
645
  import { ZodError } from "zod";
577
646
 
578
647
  // libs/shared/util/zod/src/lib/coerce-boolean.ts
579
- import { z as z3 } from "zod";
648
+ import { z as z5 } from "zod";
580
649
 
581
650
  // libs/shared/util/zod/src/lib/create-lowercase-schema.ts
582
- import { z as z4 } from "zod";
651
+ import { z as z6 } from "zod";
583
652
 
584
653
  // libs/shared/util/zod/src/lib/json.schema.ts
585
- import { z as z5 } from "zod";
586
- var LiteralSchema = z5.union([z5.string(), z5.number(), z5.boolean(), z5.null()]);
587
- var JsonSchema = z5.lazy(
588
- () => z5.union([LiteralSchema, z5.array(JsonSchema), z5.record(JsonSchema)])
654
+ import { z as z7 } from "zod";
655
+ var LiteralSchema = z7.union([z7.string(), z7.number(), z7.boolean(), z7.null()]);
656
+ var JsonSchema = z7.lazy(
657
+ () => z7.union([LiteralSchema, z7.array(JsonSchema), z7.record(JsonSchema)])
589
658
  );
590
659
 
591
660
  // libs/shared/util/zod/src/lib/with-camel-case.preprocess.ts
592
- import { z as z6 } from "zod";
661
+ import { z as z8 } from "zod";
593
662
  var toCamelCase = (str, specialCases = {}) => {
594
663
  if (specialCases[str]) {
595
664
  return specialCases[str];
@@ -639,7 +708,7 @@ var transformKeys = (options) => {
639
708
  };
640
709
  var withCamelCase = (schema, options = {}) => {
641
710
  const { preserve = [], specialCases = {} } = options;
642
- return z6.preprocess(
711
+ return z8.preprocess(
643
712
  (data) => transformKeys({
644
713
  currentPath: [],
645
714
  data,
@@ -651,38 +720,38 @@ var withCamelCase = (schema, options = {}) => {
651
720
  };
652
721
 
653
722
  // libs/shared/util/zod/src/lib/with-env-vars.preprocess.ts
654
- import { z as z7 } from "zod";
723
+ import { z as z9 } from "zod";
655
724
 
656
725
  // libs/shared/util/zod/src/lib/with-replace-all.preprocess.ts
657
- import { z as z8 } from "zod";
726
+ import { z as z10 } from "zod";
658
727
 
659
728
  // packages/fly-node/src/lib/schemas/apps-create.schema.ts
660
- import { z as z9 } from "zod";
729
+ import { z as z11 } from "zod";
661
730
  var AppsCreateTransformedResponseSchema = withCamelCase(
662
- z9.object({
663
- id: z9.string(),
664
- name: z9.string()
731
+ z11.object({
732
+ id: z11.string(),
733
+ name: z11.string()
665
734
  })
666
735
  );
667
736
 
668
737
  // packages/fly-node/src/lib/schemas/apps-list.schema.ts
669
- import { z as z10 } from "zod";
670
- var AppsListTransformedResponseSchema = z10.array(
738
+ import { z as z12 } from "zod";
739
+ var AppsListTransformedResponseSchema = z12.array(
671
740
  withCamelCase(
672
- z10.object({
673
- id: z10.string(),
674
- name: z10.string(),
675
- status: z10.string(),
676
- deployed: z10.boolean(),
677
- hostname: z10.string(),
678
- organization: z10.object({
679
- name: z10.string(),
680
- slug: z10.string()
741
+ z12.object({
742
+ id: z12.string(),
743
+ name: z12.string(),
744
+ status: z12.string(),
745
+ deployed: z12.boolean(),
746
+ hostname: z12.string(),
747
+ organization: z12.object({
748
+ name: z12.string(),
749
+ slug: z12.string()
681
750
  }),
682
- currentRelease: z10.nullable(
683
- z10.object({
684
- status: z10.string(),
685
- createdAt: z10.string().datetime()
751
+ currentRelease: z12.nullable(
752
+ z12.object({
753
+ status: z12.string(),
754
+ createdAt: z12.string().datetime()
686
755
  })
687
756
  )
688
757
  })
@@ -690,53 +759,53 @@ var AppsListTransformedResponseSchema = z10.array(
690
759
  );
691
760
 
692
761
  // packages/fly-node/src/lib/schemas/build-response.schema.ts
693
- import { z as z11 } from "zod";
694
- var BuildResponseSchema = z11.object({
695
- appName: z11.string(),
696
- imageRef: z11.string()
762
+ import { z as z13 } from "zod";
763
+ var BuildResponseSchema = z13.object({
764
+ appName: z13.string(),
765
+ imageRef: z13.string()
697
766
  });
698
767
 
699
768
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
700
- import { z as z13 } from "zod";
769
+ import { z as z15 } from "zod";
701
770
 
702
771
  // packages/fly-node/src/lib/schemas/certs-list.schema.ts
703
- import { z as z12 } from "zod";
704
- var CertsListFlyResponseElementSchema = z12.object({
705
- createdAt: z12.string().datetime(),
706
- hostname: z12.string(),
707
- clientStatus: z12.string()
772
+ import { z as z14 } from "zod";
773
+ var CertsListFlyResponseElementSchema = z14.object({
774
+ createdAt: z14.string().datetime(),
775
+ hostname: z14.string(),
776
+ clientStatus: z14.string()
708
777
  });
709
- var CertsListTransformedResponseSchema = z12.array(
778
+ var CertsListTransformedResponseSchema = z14.array(
710
779
  withCamelCase(CertsListFlyResponseElementSchema)
711
780
  );
712
781
 
713
782
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
714
- var CertsListWithAppTransformedResponseSchema = z13.array(
783
+ var CertsListWithAppTransformedResponseSchema = z15.array(
715
784
  withCamelCase(
716
785
  CertsListFlyResponseElementSchema.extend({
717
- app: z13.string()
786
+ app: z15.string()
718
787
  })
719
788
  )
720
789
  );
721
790
 
722
791
  // packages/fly-node/src/lib/schemas/config-show.schema.ts
723
- import { z as z14 } from "zod";
792
+ import { z as z16 } from "zod";
724
793
  var ConfigShowResponseSchema = withCamelCase(
725
- z14.object({
726
- app: z14.string(),
727
- primaryRegion: z14.string().optional(),
728
- build: z14.record(z14.string(), z14.any()).optional().or(
729
- z14.object({
730
- args: z14.record(z14.string(), z14.string()).optional(),
731
- dockerfile: z14.string().optional(),
732
- image: z14.string().optional()
794
+ z16.object({
795
+ app: z16.string(),
796
+ primaryRegion: z16.string().optional(),
797
+ build: z16.record(z16.string(), z16.any()).optional().or(
798
+ z16.object({
799
+ args: z16.record(z16.string(), z16.string()).optional(),
800
+ dockerfile: z16.string().optional(),
801
+ image: z16.string().optional()
733
802
  })
734
803
  ),
735
- deploy: z14.record(z14.string(), z14.any()).optional().or(z14.object({ strategy: z14.string().optional() })),
736
- env: z14.record(z14.string(), z14.string()).optional(),
737
- httpService: z14.record(z14.string(), z14.any()).optional(),
738
- mounts: z14.record(z14.string(), z14.any()).optional(),
739
- services: z14.array(z14.record(z14.string(), z14.any())).optional()
804
+ deploy: z16.record(z16.string(), z16.any()).optional().or(z16.object({ strategy: z16.string().optional() })),
805
+ env: z16.record(z16.string(), z16.string()).optional(),
806
+ httpService: z16.record(z16.string(), z16.any()).optional(),
807
+ mounts: z16.record(z16.string(), z16.any()).optional(),
808
+ services: z16.array(z16.record(z16.string(), z16.any())).optional()
740
809
  }),
741
810
  {
742
811
  preserve: ["build.args", "env"]
@@ -744,126 +813,139 @@ var ConfigShowResponseSchema = withCamelCase(
744
813
  );
745
814
 
746
815
  // packages/fly-node/src/lib/schemas/deploy.schema.ts
747
- import { z as z15 } from "zod";
748
- var DeployResponseSchema = z15.object({
749
- app: z15.string(),
750
- hostname: z15.string(),
751
- url: z15.string().url()
816
+ import { z as z17 } from "zod";
817
+ var DeployResponseSchema = z17.object({
818
+ app: z17.string(),
819
+ hostname: z17.string(),
820
+ url: z17.string().url()
752
821
  });
753
822
 
754
823
  // packages/fly-node/src/lib/schemas/helper-schemas.ts
755
- import { z as z16 } from "zod";
756
- var AllowEmptyUrlSchema = z16.string().url().or(z16.literal(""));
757
- var NameSchema = z16.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
824
+ import { z as z18 } from "zod";
825
+ var AllowEmptyUrlSchema = z18.string().url().or(z18.literal(""));
826
+ var NameSchema = z18.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
827
+
828
+ // packages/fly-node/src/lib/schemas/ips-list.schema.ts
829
+ import { z as z19 } from "zod";
830
+ var IpsListFlyResponseElementSchema = z19.object({
831
+ id: z19.string(),
832
+ address: z19.string(),
833
+ type: IpTypeSchema,
834
+ region: z19.string(),
835
+ createdAt: z19.string()
836
+ });
837
+ var IpsListTransformedResponseSchema = z19.array(
838
+ withCamelCase(IpsListFlyResponseElementSchema)
839
+ );
758
840
 
759
841
  // packages/fly-node/src/lib/schemas/postgres-list.ts
760
- import { z as z17 } from "zod";
761
- var PostgresListTransformedResponseSchema = z17.array(
842
+ import { z as z20 } from "zod";
843
+ var PostgresListTransformedResponseSchema = z20.array(
762
844
  withCamelCase(
763
- z17.object({
764
- deployed: z17.boolean(),
765
- hostname: z17.string(),
766
- id: z17.string(),
767
- name: z17.string(),
768
- organization: z17.object({ id: z17.string(), slug: z17.string() }),
769
- status: z17.string(),
770
- version: z17.number()
845
+ z20.object({
846
+ deployed: z20.boolean(),
847
+ hostname: z20.string(),
848
+ id: z20.string(),
849
+ name: z20.string(),
850
+ organization: z20.object({ id: z20.string(), slug: z20.string() }),
851
+ status: z20.string(),
852
+ version: z20.number()
771
853
  })
772
854
  )
773
- ).or(z17.string());
855
+ ).or(z20.string());
774
856
 
775
857
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
776
- import { z as z18 } from "zod";
777
- var PostgresUsersListTransformedResponseSchema = z18.array(
858
+ import { z as z21 } from "zod";
859
+ var PostgresUsersListTransformedResponseSchema = z21.array(
778
860
  withCamelCase(
779
- z18.object({
780
- username: z18.string(),
781
- superuser: z18.boolean(),
782
- databases: z18.array(z18.string())
861
+ z21.object({
862
+ username: z21.string(),
863
+ superuser: z21.boolean(),
864
+ databases: z21.array(z21.string())
783
865
  })
784
866
  )
785
867
  );
786
868
 
787
869
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
788
- import { z as z20 } from "zod";
870
+ import { z as z23 } from "zod";
789
871
 
790
872
  // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
791
- import { z as z19 } from "zod";
792
- var SecretsListFlyResponseElementSchema = z19.object({
793
- name: z19.string(),
794
- digest: z19.string()
873
+ import { z as z22 } from "zod";
874
+ var SecretsListFlyResponseElementSchema = z22.object({
875
+ name: z22.string(),
876
+ digest: z22.string()
795
877
  });
796
- var SecretsListTransformedResponseSchema = z19.array(
878
+ var SecretsListTransformedResponseSchema = z22.array(
797
879
  withCamelCase(SecretsListFlyResponseElementSchema)
798
880
  );
799
881
 
800
882
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
801
- var SecretsListWithAppTransformedResponseSchema = z20.array(
883
+ var SecretsListWithAppTransformedResponseSchema = z23.array(
802
884
  withCamelCase(
803
885
  SecretsListFlyResponseElementSchema.extend({
804
- app: z20.string()
886
+ app: z23.string()
805
887
  })
806
888
  )
807
889
  );
808
890
 
809
891
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
810
- import { z as z22 } from "zod";
892
+ import { z as z25 } from "zod";
811
893
 
812
894
  // packages/fly-node/src/lib/schemas/status.schema.ts
813
- import { z as z21 } from "zod";
814
- var statusFlyResponseSchema = z21.object({
815
- deployed: z21.boolean(),
816
- hostname: z21.string(),
817
- id: z21.string(),
818
- machines: z21.array(
819
- z21.object({
820
- id: z21.string(),
821
- name: z21.string(),
822
- state: z21.string(),
823
- region: z21.string(),
824
- imageRef: z21.object({
825
- registry: z21.string(),
826
- repository: z21.string(),
827
- tag: z21.string(),
828
- digest: z21.string(),
829
- labels: z21.record(z21.string()).optional()
895
+ import { z as z24 } from "zod";
896
+ var statusFlyResponseSchema = z24.object({
897
+ deployed: z24.boolean(),
898
+ hostname: z24.string(),
899
+ id: z24.string(),
900
+ machines: z24.array(
901
+ z24.object({
902
+ id: z24.string(),
903
+ name: z24.string(),
904
+ state: z24.string(),
905
+ region: z24.string(),
906
+ imageRef: z24.object({
907
+ registry: z24.string(),
908
+ repository: z24.string(),
909
+ tag: z24.string(),
910
+ digest: z24.string(),
911
+ labels: z24.record(z24.string()).optional()
830
912
  }),
831
- createdAt: z21.string().datetime(),
832
- updatedAt: z21.string().datetime(),
833
- config: z21.object({
834
- env: z21.record(z21.string()),
835
- metadata: z21.record(z21.string()),
836
- guest: z21.object({
837
- cpu_kind: z21.string().optional(),
838
- cpus: z21.number().optional(),
839
- memory_mb: z21.number().optional()
913
+ createdAt: z24.string().datetime(),
914
+ updatedAt: z24.string().datetime(),
915
+ config: z24.object({
916
+ env: z24.record(z24.string()),
917
+ metadata: z24.record(z24.string()),
918
+ guest: z24.object({
919
+ cpu_kind: z24.string().optional(),
920
+ cpus: z24.number().optional(),
921
+ memory_mb: z24.number().optional()
840
922
  }).optional()
841
923
  }),
842
- events: z21.array(
843
- z21.object({
844
- type: z21.string(),
845
- status: z21.string(),
846
- timestamp: z21.number()
924
+ events: z24.array(
925
+ z24.object({
926
+ type: z24.string(),
927
+ status: z24.string(),
928
+ timestamp: z24.number()
847
929
  })
848
930
  ),
849
- checks: z21.array(
850
- z21.object({
851
- name: z21.string(),
852
- status: z21.string(),
853
- output: z21.string(),
854
- updatedAt: z21.string().datetime()
931
+ checks: z24.array(
932
+ z24.object({
933
+ name: z24.string(),
934
+ status: z24.string(),
935
+ output: z24.string(),
936
+ updatedAt: z24.string().datetime()
855
937
  })
856
938
  ).optional(),
857
- hostStatus: z21.string()
939
+ hostStatus: z24.string()
858
940
  })
859
941
  ),
860
- name: z21.string(),
861
- organization: z21.object({
862
- id: z21.string(),
863
- slug: z21.string()
942
+ name: z24.string(),
943
+ organization: z24.object({
944
+ id: z24.string(),
945
+ slug: z24.string()
864
946
  }),
865
- status: z21.string(),
866
- version: z21.number()
947
+ status: z24.string(),
948
+ version: z24.number()
867
949
  });
868
950
  var StatusTransformedResponseSchema = withCamelCase(
869
951
  statusFlyResponseSchema,
@@ -876,12 +958,24 @@ var StatusTransformedResponseSchema = withCamelCase(
876
958
  specialCases: { AppURL: "appUrl" }
877
959
  }
878
960
  );
961
+ var statusLookupSchema = withCamelCase(
962
+ z24.object({
963
+ name: z24.string(),
964
+ hostname: z24.string(),
965
+ machines: z24.array(
966
+ z24.object({
967
+ id: z24.string(),
968
+ state: z24.string()
969
+ }).passthrough()
970
+ )
971
+ }).passthrough()
972
+ );
879
973
 
880
974
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
881
975
  var StatusExtendedTransformedResponseSchema = withCamelCase(
882
976
  statusFlyResponseSchema.extend({
883
- domains: z22.array(z22.object({ hostname: z22.string() })),
884
- secrets: z22.array(z22.object({ name: z22.string() }))
977
+ domains: z25.array(z25.object({ hostname: z25.string() })),
978
+ secrets: z25.array(z25.object({ name: z25.string() }))
885
979
  }),
886
980
  {
887
981
  preserve: [
@@ -893,21 +987,35 @@ var StatusExtendedTransformedResponseSchema = withCamelCase(
893
987
  );
894
988
 
895
989
  // packages/fly-node/src/lib/schemas/version.schema.ts
896
- import { z as z23 } from "zod";
990
+ import { z as z26 } from "zod";
897
991
  var VersionTransformedResponseSchema = withCamelCase(
898
- z23.object({
899
- name: z23.string(),
900
- version: z23.string(),
901
- commit: z23.string(),
902
- branchName: z23.string(),
903
- buildDate: z23.string().datetime(),
904
- os: z23.string(),
905
- architecture: z23.string(),
906
- environment: z23.string()
992
+ z26.object({
993
+ name: z26.string(),
994
+ version: z26.string(),
995
+ commit: z26.string(),
996
+ branchName: z26.string(),
997
+ buildDate: z26.string().datetime(),
998
+ os: z26.string(),
999
+ architecture: z26.string(),
1000
+ environment: z26.string()
907
1001
  })
908
1002
  );
909
1003
 
910
1004
  // packages/fly-node/src/lib/fly.class.ts
1005
+ var TRANSIENT_FLY_ERRORS = [
1006
+ { cause: "no capacity available", pattern: /no capacity available/i },
1007
+ { cause: "builder deadline exceeded", pattern: /deadline_exceeded/i },
1008
+ {
1009
+ cause: "timed out connecting to machine",
1010
+ pattern: /timed out connecting to machine/i
1011
+ },
1012
+ // The status text, not a bare 503: an app whose health check answers
1013
+ // 503 is broken, not unlucky, and must not be deployed three times
1014
+ { cause: "Fly API 503", pattern: /503 Service Unavailable/i }
1015
+ ];
1016
+ var TRANSIENT_RETRY_DELAYS_MS = [1e4, 3e4];
1017
+ var MACHINE_STATE_INTERVAL_MS = 2e3;
1018
+ var MACHINE_STATE_TIMEOUT_MS = 12e4;
911
1019
  var Fly = class {
912
1020
  /** Use underscore to avoid conflict with public `config` property */
913
1021
  _config;
@@ -991,7 +1099,9 @@ ${error}`);
991
1099
  return await this.version();
992
1100
  } catch (error) {
993
1101
  throw new Error(`[version] something broke
994
- ${error}`);
1102
+ ${error}`, {
1103
+ cause: error
1104
+ });
995
1105
  }
996
1106
  }
997
1107
  };
@@ -1018,7 +1128,8 @@ ${error}`);
1018
1128
  } catch (error) {
1019
1129
  throw new Error(
1020
1130
  `[create app] something broke, check your apps
1021
- ${error}`
1131
+ ${error}`,
1132
+ { cause: error }
1022
1133
  );
1023
1134
  }
1024
1135
  },
@@ -1044,7 +1155,8 @@ ${error}`
1044
1155
  } catch (error) {
1045
1156
  throw new Error(
1046
1157
  `[destroy app] something broke, check your apps
1047
- ${error}`
1158
+ ${error}`,
1159
+ { cause: error }
1048
1160
  );
1049
1161
  }
1050
1162
  },
@@ -1059,7 +1171,7 @@ ${error}`
1059
1171
  return await this.fetchAllApps("throwOnError");
1060
1172
  } catch (error) {
1061
1173
  throw new Error(`[list] something broke
1062
- ${error}`);
1174
+ ${error}`, { cause: error });
1063
1175
  }
1064
1176
  }
1065
1177
  };
@@ -1084,7 +1196,8 @@ ${error}`);
1084
1196
  } catch (error) {
1085
1197
  throw new Error(
1086
1198
  `[add certificate] something broke, check your app certificates
1087
- ${error}`
1199
+ ${error}`,
1200
+ { cause: error }
1088
1201
  );
1089
1202
  }
1090
1203
  },
@@ -1102,7 +1215,9 @@ ${error}`
1102
1215
  return result;
1103
1216
  } catch (error) {
1104
1217
  throw new Error(`[list certificates] something broke
1105
- ${error}`);
1218
+ ${error}`, {
1219
+ cause: error
1220
+ });
1106
1221
  }
1107
1222
  },
1108
1223
  /**
@@ -1122,7 +1237,8 @@ ${error}`);
1122
1237
  } catch (error) {
1123
1238
  throw new Error(
1124
1239
  `[remove certificate] something broke, check your app certificates
1125
- ${error}`
1240
+ ${error}`,
1241
+ { cause: error }
1126
1242
  );
1127
1243
  }
1128
1244
  }
@@ -1149,7 +1265,9 @@ ${error}`
1149
1265
  );
1150
1266
  } catch (error) {
1151
1267
  throw new Error(`[save config] something broke
1152
- ${error}`);
1268
+ ${error}`, {
1269
+ cause: error
1270
+ });
1153
1271
  }
1154
1272
  },
1155
1273
  /**
@@ -1165,7 +1283,9 @@ ${error}`);
1165
1283
  return await this.showConfig("throwOnError", options);
1166
1284
  } catch (error) {
1167
1285
  throw new Error(`[show config] something broke
1168
- ${error}`);
1286
+ ${error}`, {
1287
+ cause: error
1288
+ });
1169
1289
  }
1170
1290
  }
1171
1291
  };
@@ -1208,7 +1328,7 @@ ${error}`);
1208
1328
  }
1209
1329
  const { appName } = await this.deployApp(options);
1210
1330
  this.logger.info(`Application '${appName}' was deployed`);
1211
- const status = await this.fetchAppStatus("throwOnError", {
1331
+ const status = await this.fetchAppLookup("throwOnError", {
1212
1332
  app: appName
1213
1333
  });
1214
1334
  return DeployResponseSchema.parse({
@@ -1219,10 +1339,74 @@ ${error}`);
1219
1339
  } catch (error) {
1220
1340
  throw new Error(
1221
1341
  `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
1222
- ${error}`
1342
+ ${error}`,
1343
+ { cause: error }
1223
1344
  );
1224
1345
  }
1225
1346
  };
1347
+ /**
1348
+ * Manage public IP addresses
1349
+ */
1350
+ ips = {
1351
+ /**
1352
+ * List the public IP addresses allocated to an application
1353
+ *
1354
+ * @param options - The application or configuration to list addresses for
1355
+ * @returns The allocated addresses, empty when the app has none
1356
+ * @throws An error if listing addresses fails
1357
+ */
1358
+ list: async (options) => {
1359
+ try {
1360
+ await this.ensureInitialized();
1361
+ return await this.fetchAppIps("throwOnError", options);
1362
+ } catch (error) {
1363
+ throw new Error(`[list ips] something broke
1364
+ ${error}`, {
1365
+ cause: error
1366
+ });
1367
+ }
1368
+ },
1369
+ /**
1370
+ * Give an application the public addresses it needs to be reachable.
1371
+ *
1372
+ * Idempotent by inspection: it allocates only what is missing, so it is
1373
+ * safe on every deploy rather than only on create. That matters because
1374
+ * `flyctl` allocates addresses only for an app it creates itself — an app
1375
+ * that arrives any other way, such as a registry push auto-creating it,
1376
+ * deploys green and answers nothing. `deploy` runs it before every
1377
+ * deploy that is not build-only.
1378
+ *
1379
+ * @param options - The application, and which addresses to ensure
1380
+ * @returns The addresses the application holds afterwards
1381
+ * @throws An error if an address cannot be allocated
1382
+ */
1383
+ ensure: async (options) => {
1384
+ try {
1385
+ await this.ensureInitialized();
1386
+ const { sharedV4 = true, v6 = true } = options ?? {};
1387
+ const existing = await this.fetchAppIps("throwOnError", options);
1388
+ const has = (...types) => existing.some((ip) => types.includes(ip.type));
1389
+ let allocated = false;
1390
+ if (sharedV4 && !has("v4", "shared_v4")) {
1391
+ await this.allocateIp("allocate-v4", options);
1392
+ this.logger.info("Allocated a shared IPv4 address");
1393
+ allocated = true;
1394
+ }
1395
+ if (v6 && !has("v6")) {
1396
+ await this.allocateIp("allocate-v6", options);
1397
+ this.logger.info("Allocated a dedicated IPv6 address");
1398
+ allocated = true;
1399
+ }
1400
+ return allocated ? await this.fetchAppIps("throwOnError", options) : existing;
1401
+ } catch (error) {
1402
+ throw new Error(
1403
+ `[ensure ips] something broke, check your app addresses
1404
+ ${error}`,
1405
+ { cause: error }
1406
+ );
1407
+ }
1408
+ }
1409
+ };
1226
1410
  /**
1227
1411
  * Manage machines
1228
1412
  */
@@ -1241,7 +1425,9 @@ ${error}`
1241
1425
  this.logger.info(`Machine '${machineId}' in app '${app}' was started`);
1242
1426
  } catch (error) {
1243
1427
  throw new Error(`[start machine] something broke
1244
- ${error}`);
1428
+ ${error}`, {
1429
+ cause: error
1430
+ });
1245
1431
  }
1246
1432
  },
1247
1433
  /**
@@ -1258,11 +1444,17 @@ ${error}`);
1258
1444
  this.logger.info(`Machine '${machineId}' in app '${app}' was stopped`);
1259
1445
  } catch (error) {
1260
1446
  throw new Error(`[stop machine] something broke
1261
- ${error}`);
1447
+ ${error}`, {
1448
+ cause: error
1449
+ });
1262
1450
  }
1263
1451
  },
1264
1452
  /**
1265
- * Restart a machine by stopping then starting it
1453
+ * Restart a machine by stopping then starting it.
1454
+ *
1455
+ * Waits until Fly reports the machine stopped (or suspended) before
1456
+ * starting it, then until it is started. If the start fails after the
1457
+ * stop, the error says the machine was left stopped.
1266
1458
  *
1267
1459
  * @param app - The name of the application
1268
1460
  * @param machineId - The machine ID to restart
@@ -1277,7 +1469,9 @@ ${error}`);
1277
1469
  );
1278
1470
  } catch (error) {
1279
1471
  throw new Error(`[restart machine] something broke
1280
- ${error}`);
1472
+ ${error}`, {
1473
+ cause: error
1474
+ });
1281
1475
  }
1282
1476
  },
1283
1477
  /**
@@ -1298,7 +1492,9 @@ ${error}`);
1298
1492
  this.logger.info(`Machine '${machineId}' in app '${app}' was updated`);
1299
1493
  } catch (error) {
1300
1494
  throw new Error(`[update machine] something broke
1301
- ${error}`);
1495
+ ${error}`, {
1496
+ cause: error
1497
+ });
1302
1498
  }
1303
1499
  }
1304
1500
  };
@@ -1332,7 +1528,9 @@ ${error}`);
1332
1528
  return await this.sshExec(app, command);
1333
1529
  } catch (error) {
1334
1530
  throw new Error(`[ssh exec] something broke
1335
- ${error}`);
1531
+ ${error}`, {
1532
+ cause: error
1533
+ });
1336
1534
  }
1337
1535
  }
1338
1536
  };
@@ -1358,7 +1556,8 @@ ${error}`);
1358
1556
  } catch (error) {
1359
1557
  throw new Error(
1360
1558
  `[set secrets] something broke, check your app secrets
1361
- ${error}`
1559
+ ${error}`,
1560
+ { cause: error }
1362
1561
  );
1363
1562
  }
1364
1563
  },
@@ -1381,7 +1580,9 @@ ${error}`
1381
1580
  this.logger.info(`Staged secrets were deployed for '${app}'`);
1382
1581
  } catch (error) {
1383
1582
  throw new Error(`[deploy secrets] something broke
1384
- ${error}`);
1583
+ ${error}`, {
1584
+ cause: error
1585
+ });
1385
1586
  }
1386
1587
  },
1387
1588
  /**
@@ -1398,7 +1599,9 @@ ${error}`);
1398
1599
  return result;
1399
1600
  } catch (error) {
1400
1601
  throw new Error(`[list secrets] something broke
1401
- ${error}`);
1602
+ ${error}`, {
1603
+ cause: error
1604
+ });
1402
1605
  }
1403
1606
  },
1404
1607
  /**
@@ -1419,7 +1622,8 @@ ${error}`);
1419
1622
  } catch (error) {
1420
1623
  throw new Error(
1421
1624
  `[unset secrets] something broke, check your app secrets
1422
- ${error}`
1625
+ ${error}`,
1626
+ { cause: error }
1423
1627
  );
1424
1628
  }
1425
1629
  }
@@ -1511,7 +1715,6 @@ ${error}`);
1511
1715
  */
1512
1716
  async deployApp(options) {
1513
1717
  let appName = "";
1514
- let appSecrets = [];
1515
1718
  let deployConfig = options?.config || this.instanceConfig;
1516
1719
  let lookupApp = options?.app || this.instanceApp;
1517
1720
  const lookupConfig = deployConfig;
@@ -1533,7 +1736,7 @@ ${error}`);
1533
1736
  lookupApp = appConfig.app;
1534
1737
  }
1535
1738
  if (lookupApp) {
1536
- const status = await this.fetchAppStatus("nullOnError", {
1739
+ const status = await this.fetchAppLookup("nullOnError", {
1537
1740
  app: lookupApp
1538
1741
  });
1539
1742
  if (status) {
@@ -1576,26 +1779,30 @@ ${error}`);
1576
1779
  appName = name;
1577
1780
  this.logger.info(`Application '${appName}' was created`);
1578
1781
  } else {
1579
- appSecrets = await this.fetchAppSecrets("throwOnError", { app: appName });
1580
1782
  this.logger.info(`Updating existing application '${appName}'`);
1581
1783
  }
1582
1784
  NameSchema.parse(appName);
1583
1785
  if (!options?.buildOnly && options?.secrets) {
1584
- const existingSecrets = new Set(appSecrets.map(({ name }) => name));
1585
- const newSecrets = {};
1786
+ const staged = {};
1787
+ const empty = [];
1586
1788
  for (const [key, value] of Object.entries(options.secrets)) {
1587
- if (!existingSecrets.has(key)) {
1588
- newSecrets[key] = value;
1789
+ if (value === "") {
1790
+ empty.push(key);
1589
1791
  } else {
1590
- this.logger.info(
1591
- `Secret '${key}' already exists for '${appName}', skipping`
1592
- );
1792
+ staged[key] = value;
1593
1793
  }
1594
1794
  }
1595
- const keys = Object.keys(newSecrets);
1795
+ if (empty.length > 0) {
1796
+ this.logger.error(
1797
+ `Refusing to blank secrets with no value for '${appName}': ${empty.join(", ")}`
1798
+ );
1799
+ }
1800
+ const keys = Object.keys(staged);
1596
1801
  if (keys.length > 0) {
1597
- this.logger.info(`Adding secrets to '${appName}': ${keys.join(", ")}`);
1598
- await this.setAppSecrets(newSecrets, {
1802
+ this.logger.info(
1803
+ `Staging secrets for '${appName}': ${keys.join(", ")}`
1804
+ );
1805
+ await this.setAppSecrets(staged, {
1599
1806
  app: appName,
1600
1807
  stage: true
1601
1808
  });
@@ -1631,6 +1838,10 @@ ${error}`);
1631
1838
  );
1632
1839
  }
1633
1840
  }
1841
+ const servesTraffic = !!appConfig.httpService || (appConfig.services?.length ?? 0) > 0;
1842
+ if (!options?.buildOnly && servesTraffic) {
1843
+ await this.ips.ensure({ app: appName });
1844
+ }
1634
1845
  const args = ["deploy", "--app", appName, "--config", deployConfig];
1635
1846
  if (options?.region) {
1636
1847
  args.push("--region", options.region);
@@ -1657,10 +1868,10 @@ ${error}`);
1657
1868
  this.logger.info(
1658
1869
  options?.buildOnly ? `Building image for '${appName}'...` : `Deploying '${appName}'...`
1659
1870
  );
1660
- const output = await this.execFly(
1661
- args,
1662
- options?.buildOnly ? { streamStrategy: "combined" } : void 0
1663
- );
1871
+ const output = await this.execFly(args, {
1872
+ streamStrategy: options?.buildOnly ? "combined" : "stdout",
1873
+ retry: true
1874
+ });
1664
1875
  const imageRef = options?.buildOnly ? output?.match(/registry\.fly\.io\/\S+/)?.[0] : void 0;
1665
1876
  return { appName, imageRef };
1666
1877
  }
@@ -1706,7 +1917,7 @@ ${error}`);
1706
1917
  * @throws An error if the secrets cannot be set
1707
1918
  */
1708
1919
  async setAppSecrets(secrets, options) {
1709
- const status = await this.fetchAppStatus("throwOnError", options);
1920
+ const status = await this.fetchAppLookup("throwOnError", options);
1710
1921
  const args = ["secrets", "set"];
1711
1922
  args.push(...this.getAppOrConfigArgs(options));
1712
1923
  if (options?.stage) {
@@ -1715,7 +1926,7 @@ ${error}`);
1715
1926
  for (const [key, value] of Object.entries(secrets)) {
1716
1927
  args.push(`${key}=${this.safeArg(value)}`);
1717
1928
  }
1718
- await this.execFly(args);
1929
+ await this.execFly(args, { retry: options?.stage === true });
1719
1930
  return NameSchema.parse(status.name);
1720
1931
  }
1721
1932
  /**
@@ -1724,7 +1935,7 @@ ${error}`);
1724
1935
  * @throws An error if the secrets cannot be unset
1725
1936
  */
1726
1937
  async unsetAppSecrets(keys, options) {
1727
- const status = await this.fetchAppStatus("throwOnError", options);
1938
+ const status = await this.fetchAppLookup("throwOnError", options);
1728
1939
  const args = ["secrets", "unset"];
1729
1940
  args.push(...this.getAppOrConfigArgs(options));
1730
1941
  if (options?.stage) {
@@ -1740,20 +1951,59 @@ ${error}`);
1740
1951
  * @throws An error if the domain cannot be added
1741
1952
  */
1742
1953
  async addAppCertificate(hostname, options) {
1743
- const status = await this.fetchAppStatus("throwOnError", options);
1954
+ const status = await this.fetchAppLookup("throwOnError", options);
1744
1955
  const args = ["certs", "add", hostname];
1745
1956
  args.push(...this.getAppOrConfigArgs(options));
1746
1957
  args.push("--json");
1747
1958
  await this.execFly(args);
1748
1959
  return NameSchema.parse(status.name);
1749
1960
  }
1961
+ /**
1962
+ * Allocate one public address.
1963
+ *
1964
+ * A dedicated v4 is billed, so the v4 path is always `--shared`.
1965
+ *
1966
+ * The two commands do not take the same flags: `allocate-v4` has `--yes`
1967
+ * because a dedicated v4 costs money and prompts, while `allocate-v6` is
1968
+ * free, never prompts, and rejects the flag outright with `unknown flag`.
1969
+ * The asymmetry is flyctl's, not ours — do not tidy it away.
1970
+ *
1971
+ * @private
1972
+ * @throws An error if the address cannot be allocated
1973
+ */
1974
+ async allocateIp(command, options) {
1975
+ const args = ["ips", command];
1976
+ if (command === "allocate-v4") {
1977
+ args.push("--shared");
1978
+ }
1979
+ args.push(...this.getAppOrConfigArgs(options));
1980
+ if (command === "allocate-v4") {
1981
+ args.push("--yes");
1982
+ }
1983
+ await this.execFly(args);
1984
+ }
1985
+ async fetchAppIps(onError, options) {
1986
+ const args = ["ips", "list"];
1987
+ args.push(...this.getAppOrConfigArgs(options));
1988
+ args.push("--json");
1989
+ try {
1990
+ return await IpsListTransformedResponseSchema.parseAsync(
1991
+ await this.execFly(args, { retry: true })
1992
+ );
1993
+ } catch (error) {
1994
+ if (onError === "throwOnError") {
1995
+ throw error;
1996
+ }
1997
+ return null;
1998
+ }
1999
+ }
1750
2000
  /**
1751
2001
  * @private
1752
2002
  * @returns The name of the application
1753
2003
  * @throws An error if the domain cannot be removed
1754
2004
  */
1755
2005
  async removeAppCertificate(hostname, options) {
1756
- const status = await this.fetchAppStatus("throwOnError", options);
2006
+ const status = await this.fetchAppLookup("throwOnError", options);
1757
2007
  const args = ["certs", "remove", hostname];
1758
2008
  args.push(...this.getAppOrConfigArgs(options));
1759
2009
  args.push("--yes");
@@ -1799,13 +2049,47 @@ ${error}`);
1799
2049
  }
1800
2050
  /**
1801
2051
  * @private
1802
- * Restart a machine by stopping then starting it
1803
- * @throws An error if the machine cannot be restarted
2052
+ * Restart a machine by stopping then starting it, waiting on the state Fly
2053
+ * reports rather than a fixed delay: the start is only issued once the
2054
+ * machine is stopped (or suspended), and the restart is done once it is
2055
+ * started again.
2056
+ * @throws An error saying the machine was left stopped when anything after
2057
+ * the stop fails
1804
2058
  */
1805
2059
  async restartMachine(app, machineId) {
1806
2060
  await this.stopMachine(app, machineId);
1807
- await new Promise((resolve) => setTimeout(resolve, 2e3));
1808
- await this.startMachine(app, machineId);
2061
+ try {
2062
+ await this.waitForMachineState(app, machineId, ["stopped", "suspended"]);
2063
+ await this.startMachine(app, machineId);
2064
+ await this.waitForMachineState(app, machineId, ["started"]);
2065
+ } catch (error) {
2066
+ const reason = error instanceof Error ? error.message : String(error);
2067
+ throw new Error(
2068
+ `Machine '${machineId}' in app '${app}' was stopped but did not start again: ${reason}`,
2069
+ { cause: error }
2070
+ );
2071
+ }
2072
+ }
2073
+ /**
2074
+ * @private
2075
+ * Poll the app status until the machine reports one of the given states
2076
+ * @throws An error if the machine does not reach a state in time
2077
+ */
2078
+ async waitForMachineState(app, machineId, states) {
2079
+ const deadline = Date.now() + MACHINE_STATE_TIMEOUT_MS;
2080
+ while (Date.now() < deadline) {
2081
+ const status = await this.fetchAppLookup("nullOnError", { app });
2082
+ const machine = status?.machines.find(({ id }) => id === machineId);
2083
+ if (machine && states.includes(machine.state)) {
2084
+ return;
2085
+ }
2086
+ await new Promise(
2087
+ (resolve) => setTimeout(resolve, MACHINE_STATE_INTERVAL_MS)
2088
+ );
2089
+ }
2090
+ throw new Error(
2091
+ `Machine '${machineId}' in app '${app}' did not reach ${states.join("/")} in time`
2092
+ );
1809
2093
  }
1810
2094
  /**
1811
2095
  * @private
@@ -1905,6 +2189,27 @@ ${error}`);
1905
2189
  this.logger.info(`Failed to parse response:
1906
2190
  ${error.message}`);
1907
2191
  this.logger.info(`Raw response:
2192
+ ${JSON.stringify(response, null, 2)}`);
2193
+ }
2194
+ return null;
2195
+ }
2196
+ }
2197
+ async fetchAppLookup(onError, options) {
2198
+ const args = ["status"];
2199
+ args.push(...this.getAppOrConfigArgs(options));
2200
+ args.push("--json");
2201
+ let response = null;
2202
+ try {
2203
+ response = await this.execFly(args);
2204
+ return statusLookupSchema.parse(response);
2205
+ } catch (error) {
2206
+ if (onError === "throwOnError") {
2207
+ throw error;
2208
+ }
2209
+ if (error instanceof ZodError) {
2210
+ this.logger.info(`Failed to parse response:
2211
+ ${error.message}`);
2212
+ this.logger.info(`Raw response:
1908
2213
  ${JSON.stringify(response, null, 2)}`);
1909
2214
  }
1910
2215
  return null;
@@ -2012,8 +2317,7 @@ ${JSON.stringify(response, null, 2)}`);
2012
2317
  * @throws An error if Fly CLI is not installed or not authenticated
2013
2318
  */
2014
2319
  async ensureInitialized() {
2015
- if (this.initialized)
2016
- return;
2320
+ if (this.initialized) return;
2017
2321
  try {
2018
2322
  if (!await this.isInstalled()) {
2019
2323
  throw new Error("Fly CLI must be installed to use this library");
@@ -2038,33 +2342,32 @@ ${JSON.stringify(response, null, 2)}`);
2038
2342
  }
2039
2343
  const flyCmd = "flyctl";
2040
2344
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
2345
+ const { retry = false, ...execOpts } = options ?? {};
2041
2346
  let output = "";
2042
- try {
2043
- this.traceCLI("CALL", toLogCmd);
2044
- if (options?.prompt) {
2045
- output = await spawnPty(flyCmd, args, { prompt: options.prompt });
2046
- this.traceCLI("RESULT", output);
2047
- } else {
2048
- const { streamStrategy = "stdout", ...spawnOpts } = options ?? {};
2049
- const result = await spawn(flyCmd, args, {
2050
- ...spawnOpts,
2051
- streamToConsole: this.logger.streamToConsole
2052
- });
2053
- const stdout = result.stdout.trim();
2054
- const stderr = result.stderr.trim();
2055
- this.traceCLI("RESULT", `${stdout}${stderr ? `
2056
- ${stderr}` : ""}`);
2057
- output = streamStrategy === "combined" ? `${stdout}
2058
- ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
2059
- }
2060
- } catch (error) {
2061
- const errorMsg = error.message;
2062
- this.traceCLI("RESULT", errorMsg);
2063
- if (onError === "throwOnError") {
2064
- throw new Error(`Command failed: ${toLogCmd}
2065
- ${errorMsg}`);
2347
+ for (let attempt = 1; ; attempt++) {
2348
+ try {
2349
+ output = await this.spawnFly(flyCmd, args, toLogCmd, execOpts);
2350
+ break;
2351
+ } catch (error) {
2352
+ const errorMsg = error.message;
2353
+ this.traceCLI("RESULT", errorMsg);
2354
+ const cause = retry ? this.transientCause(error) : null;
2355
+ const delay = TRANSIENT_RETRY_DELAYS_MS[attempt - 1];
2356
+ if (cause && delay !== void 0) {
2357
+ this.logger.info(
2358
+ `Transient Fly error (${cause}), retrying in ${delay / 1e3}s (attempt ${attempt + 1} of ${TRANSIENT_RETRY_DELAYS_MS.length + 1}): ${toLogCmd}`
2359
+ );
2360
+ await new Promise((resolve) => setTimeout(resolve, delay));
2361
+ continue;
2362
+ }
2363
+ if (onError === "throwOnError") {
2364
+ throw new Error(`Command failed: ${toLogCmd}
2365
+ ${errorMsg}`, {
2366
+ cause: error
2367
+ });
2368
+ }
2369
+ return null;
2066
2370
  }
2067
- return null;
2068
2371
  }
2069
2372
  try {
2070
2373
  return JSON.parse(output);
@@ -2078,6 +2381,55 @@ ${errorMsg}`);
2078
2381
  }
2079
2382
  return void 0;
2080
2383
  }
2384
+ /**
2385
+ * @private
2386
+ * Run one fly command and assemble its output
2387
+ *
2388
+ * @returns The output selected by `streamStrategy`
2389
+ * @throws An error if the command fails
2390
+ */
2391
+ async spawnFly(flyCmd, args, toLogCmd, options) {
2392
+ this.traceCLI("CALL", toLogCmd);
2393
+ if (options.prompt) {
2394
+ const output = await spawnPty(flyCmd, args, { prompt: options.prompt });
2395
+ this.traceCLI("RESULT", output);
2396
+ return output;
2397
+ }
2398
+ const { streamStrategy = "stdout", ...spawnOpts } = options;
2399
+ const result = await spawn(flyCmd, args, {
2400
+ ...spawnOpts,
2401
+ streamToConsole: this.logger.streamToConsole
2402
+ });
2403
+ const stdout = result.stdout.trim();
2404
+ const stderr = result.stderr.trim();
2405
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
2406
+ ${stderr}` : ""}`);
2407
+ return streamStrategy === "combined" ? `${stdout}
2408
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
2409
+ }
2410
+ /**
2411
+ * @private
2412
+ * Name the transient Fly error behind a failed command, if it was one.
2413
+ *
2414
+ * Only the error flyctl ended with counts: from its last `Error` line to
2415
+ * the end of stderr, or the last few lines when there is none. A deploy
2416
+ * streams the app's own output and errors flyctl recovered from, and
2417
+ * matching those would repeat a deploy that failed for a real reason.
2418
+ *
2419
+ * @returns The cause, or `null` when the failure is not a known transient one
2420
+ */
2421
+ transientCause(error) {
2422
+ let text;
2423
+ if (error instanceof SpawnError) {
2424
+ const lines = error.stderr.split(/\r?\n/).filter((line) => line.trim());
2425
+ const errorLines = lines.map((line) => /^\s*Error\b/.test(line));
2426
+ const last = errorLines.lastIndexOf(true);
2427
+ text = lines.slice(last >= 0 ? last : -3).join("\n");
2428
+ } else {
2429
+ text = String(error?.message ?? error);
2430
+ }
2431
+ return TRANSIENT_FLY_ERRORS.find(({ pattern }) => pattern.test(text))?.cause ?? null;
2432
+ }
2081
2433
  /**
2082
2434
  * @private
2083
2435
  * Get the arguments for `AppOrConfig` options
@@ -2225,6 +2577,8 @@ ${errorMsg}`);
2225
2577
  }
2226
2578
  };
2227
2579
  export {
2580
+ AppIpAddressSchema,
2581
+ AppIpAddressesApiResponseSchema,
2228
2582
  CertificateApiResponseSchema,
2229
2583
  CertificateListApiResponseSchema,
2230
2584
  DnsInstructionsSchema,