@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.cjs CHANGED
@@ -28,8 +28,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // packages/fly-node/src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AppIpAddressSchema: () => AppIpAddressSchema,
34
+ AppIpAddressesApiResponseSchema: () => AppIpAddressesApiResponseSchema,
33
35
  CertificateApiResponseSchema: () => CertificateApiResponseSchema,
34
36
  CertificateListApiResponseSchema: () => CertificateListApiResponseSchema,
35
37
  DnsInstructionsSchema: () => DnsInstructionsSchema,
@@ -40,51 +42,68 @@ __export(src_exports, {
40
42
  MachineApiResponseSchema: () => MachineApiResponseSchema,
41
43
  MachineListApiResponseSchema: () => MachineListApiResponseSchema
42
44
  });
43
- module.exports = __toCommonJS(src_exports);
45
+ module.exports = __toCommonJS(index_exports);
44
46
 
45
- // packages/fly-node/src/lib/schemas/certificate.schema.ts
47
+ // packages/fly-node/src/lib/schemas/app-ip-addresses.schema.ts
48
+ var import_zod2 = require("zod");
49
+
50
+ // packages/fly-node/src/lib/schemas/ip-type.schema.ts
46
51
  var import_zod = require("zod");
47
- var CertificateApiResponseSchema = import_zod.z.object({
48
- hostname: import_zod.z.string(),
52
+ var IpTypeSchema = import_zod.z.enum(["v4", "v6", "shared_v4", "private_v6"]).or(import_zod.z.string());
53
+
54
+ // packages/fly-node/src/lib/schemas/app-ip-addresses.schema.ts
55
+ var AppIpAddressSchema = import_zod2.z.object({
56
+ address: import_zod2.z.string(),
57
+ type: IpTypeSchema
58
+ });
59
+ var AppIpAddressesApiResponseSchema = import_zod2.z.object({
60
+ sharedIpAddress: import_zod2.z.string().nullish(),
61
+ ipAddresses: import_zod2.z.object({ nodes: import_zod2.z.array(AppIpAddressSchema) })
62
+ });
63
+
64
+ // packages/fly-node/src/lib/schemas/certificate.schema.ts
65
+ var import_zod3 = require("zod");
66
+ var CertificateApiResponseSchema = import_zod3.z.object({
67
+ hostname: import_zod3.z.string(),
49
68
  /** Issued and serving. This is what decides whether a domain is usable */
50
- isConfigured: import_zod.z.boolean(),
51
- id: import_zod.z.string().optional(),
69
+ isConfigured: import_zod3.z.boolean(),
70
+ id: import_zod3.z.string().optional(),
52
71
  /** The apex or a subdomain — apex domains cannot use a CNAME */
53
- isApex: import_zod.z.boolean().optional(),
54
- isWildcard: import_zod.z.boolean().optional(),
72
+ isApex: import_zod3.z.boolean().optional(),
73
+ isWildcard: import_zod3.z.boolean().optional(),
55
74
  /** Which ACME challenge has been satisfied, if any */
56
- isAcmeDnsConfigured: import_zod.z.boolean().optional(),
57
- isAcmeAlpnConfigured: import_zod.z.boolean().optional(),
58
- isAcmeHttpConfigured: import_zod.z.boolean().optional(),
59
- certificateAuthority: import_zod.z.string().nullish(),
60
- certificateRequestedAt: import_zod.z.string().nullish(),
61
- createdAt: import_zod.z.string().nullish(),
62
- domain: import_zod.z.string().nullish(),
63
- dnsProvider: import_zod.z.string().nullish(),
75
+ isAcmeDnsConfigured: import_zod3.z.boolean().optional(),
76
+ isAcmeAlpnConfigured: import_zod3.z.boolean().optional(),
77
+ isAcmeHttpConfigured: import_zod3.z.boolean().optional(),
78
+ certificateAuthority: import_zod3.z.string().nullish(),
79
+ certificateRequestedAt: import_zod3.z.string().nullish(),
80
+ createdAt: import_zod3.z.string().nullish(),
81
+ domain: import_zod3.z.string().nullish(),
82
+ dnsProvider: import_zod3.z.string().nullish(),
64
83
  /** Hostname the validation record must be created on */
65
- dnsValidationHostname: import_zod.z.string().nullish(),
84
+ dnsValidationHostname: import_zod3.z.string().nullish(),
66
85
  /** Value that record must contain */
67
- dnsValidationTarget: import_zod.z.string().nullish(),
86
+ dnsValidationTarget: import_zod3.z.string().nullish(),
68
87
  /** Fly's own prose describing the records to create */
69
- dnsValidationInstructions: import_zod.z.string().nullish(),
88
+ dnsValidationInstructions: import_zod3.z.string().nullish(),
70
89
  /** Fly's summary of where issuance has got to */
71
- clientStatus: import_zod.z.string().nullish(),
90
+ clientStatus: import_zod3.z.string().nullish(),
72
91
  /**
73
92
  * Set when Let's Encrypt has rate-limited further attempts for this domain.
74
93
  *
75
94
  * Worth surfacing rather than swallowing: it is the one failure a customer
76
95
  * cannot fix by correcting DNS, and retrying only makes it worse.
77
96
  */
78
- rateLimitedUntil: import_zod.z.string().nullish(),
79
- source: import_zod.z.string().nullish(),
97
+ rateLimitedUntil: import_zod3.z.string().nullish(),
98
+ source: import_zod3.z.string().nullish(),
80
99
  /**
81
100
  * Fly's own prose for a failed issuance attempt — what the dashboard shows,
82
101
  * unlike `HostnameCheck.errors`, which is SCREAMING_SNAKE_CASE codes
83
102
  */
84
- validationErrors: import_zod.z.array(
85
- import_zod.z.object({
86
- message: import_zod.z.string(),
87
- timestamp: import_zod.z.string()
103
+ validationErrors: import_zod3.z.array(
104
+ import_zod3.z.object({
105
+ message: import_zod3.z.string(),
106
+ timestamp: import_zod3.z.string()
88
107
  })
89
108
  ).nullish(),
90
109
  /**
@@ -94,52 +113,52 @@ var CertificateApiResponseSchema = import_zod.z.object({
94
113
  * nodes is the normal count — one RSA and one ECDSA — sharing an expiry,
95
114
  * which is why a caller usually wants the expiry rather than the rows.
96
115
  */
97
- issued: import_zod.z.object({
98
- nodes: import_zod.z.array(
99
- import_zod.z.object({
100
- id: import_zod.z.string().nullish(),
116
+ issued: import_zod3.z.object({
117
+ nodes: import_zod3.z.array(
118
+ import_zod3.z.object({
119
+ id: import_zod3.z.string().nullish(),
101
120
  /** Key type, e.g. `RSA` or `ECDSA` */
102
- type: import_zod.z.string().nullish(),
103
- hostname: import_zod.z.string().nullish(),
104
- expiresAt: import_zod.z.string().nullish()
121
+ type: import_zod3.z.string().nullish(),
122
+ hostname: import_zod3.z.string().nullish(),
123
+ expiresAt: import_zod3.z.string().nullish()
105
124
  })
106
125
  ).nullish()
107
126
  }).nullish()
108
127
  });
109
- var HostnameCheckApiResponseSchema = import_zod.z.object({
110
- aRecords: import_zod.z.array(import_zod.z.string()).nullish(),
111
- aaaaRecords: import_zod.z.array(import_zod.z.string()).nullish(),
112
- cnameRecords: import_zod.z.array(import_zod.z.string()).nullish(),
113
- caaRecords: import_zod.z.array(import_zod.z.string()).nullish(),
114
- soa: import_zod.z.string().nullish(),
115
- dnsProvider: import_zod.z.string().nullish(),
116
- dnsVerificationRecord: import_zod.z.string().nullish(),
117
- dnsConfigured: import_zod.z.boolean().nullish(),
118
- acmeDnsConfigured: import_zod.z.boolean().nullish(),
119
- resolvedAddresses: import_zod.z.array(import_zod.z.string()).nullish(),
120
- isProxied: import_zod.z.boolean().nullish(),
121
- errors: import_zod.z.array(import_zod.z.string()).nullish()
128
+ var HostnameCheckApiResponseSchema = import_zod3.z.object({
129
+ aRecords: import_zod3.z.array(import_zod3.z.string()).nullish(),
130
+ aaaaRecords: import_zod3.z.array(import_zod3.z.string()).nullish(),
131
+ cnameRecords: import_zod3.z.array(import_zod3.z.string()).nullish(),
132
+ caaRecords: import_zod3.z.array(import_zod3.z.string()).nullish(),
133
+ soa: import_zod3.z.string().nullish(),
134
+ dnsProvider: import_zod3.z.string().nullish(),
135
+ dnsVerificationRecord: import_zod3.z.string().nullish(),
136
+ dnsConfigured: import_zod3.z.boolean().nullish(),
137
+ acmeDnsConfigured: import_zod3.z.boolean().nullish(),
138
+ resolvedAddresses: import_zod3.z.array(import_zod3.z.string()).nullish(),
139
+ isProxied: import_zod3.z.boolean().nullish(),
140
+ errors: import_zod3.z.array(import_zod3.z.string()).nullish()
122
141
  });
123
- var DnsInstructionsSchema = import_zod.z.object({
124
- hostname: import_zod.z.string().nullish(),
125
- target: import_zod.z.string().nullish(),
126
- instructions: import_zod.z.string().nullish(),
127
- isApex: import_zod.z.boolean().optional()
142
+ var DnsInstructionsSchema = import_zod3.z.object({
143
+ hostname: import_zod3.z.string().nullish(),
144
+ target: import_zod3.z.string().nullish(),
145
+ instructions: import_zod3.z.string().nullish(),
146
+ isApex: import_zod3.z.boolean().optional()
128
147
  });
129
- var CertificateListApiResponseSchema = import_zod.z.array(
148
+ var CertificateListApiResponseSchema = import_zod3.z.array(
130
149
  CertificateApiResponseSchema
131
150
  );
132
151
 
133
152
  // packages/fly-node/src/lib/schemas/machine.schema.ts
134
- var import_zod2 = require("zod");
135
- var MachineApiResponseSchema = import_zod2.z.object({
136
- id: import_zod2.z.string(),
137
- name: import_zod2.z.string().nullish(),
153
+ var import_zod4 = require("zod");
154
+ var MachineApiResponseSchema = import_zod4.z.object({
155
+ id: import_zod4.z.string(),
156
+ name: import_zod4.z.string().nullish(),
138
157
  /** `started`, `stopped`, `suspended`, … — Fly owns this vocabulary */
139
- state: import_zod2.z.string().nullish(),
140
- region: import_zod2.z.string().nullish()
158
+ state: import_zod4.z.string().nullish(),
159
+ region: import_zod4.z.string().nullish()
141
160
  });
142
- var MachineListApiResponseSchema = import_zod2.z.array(MachineApiResponseSchema);
161
+ var MachineListApiResponseSchema = import_zod4.z.array(MachineApiResponseSchema);
143
162
 
144
163
  // packages/fly-node/src/lib/fly-api.class.ts
145
164
  var FLY_API_URL = "https://api.fly.io/graphql";
@@ -332,6 +351,42 @@ var FlyApi = class {
332
351
  );
333
352
  }
334
353
  };
354
+ /** Read an app's addresses */
355
+ ips = {
356
+ /**
357
+ * The addresses an app answers on: `shared_v4`, `v4`, `v6`, and its
358
+ * `private_v6`.
359
+ *
360
+ * The shared v4 is folded in as a `shared_v4` row, the way `fly ips list`
361
+ * shows it; Fly's API keeps it in a separate field. Egress addresses,
362
+ * which the CLI also lists, are not part of this API and never appear.
363
+ * Pick the public types before pointing DNS at them.
364
+ *
365
+ * Rejects for an unknown app, like `certs.list`: a typo in an app name
366
+ * must not read as "this app has no addresses".
367
+ *
368
+ * @returns The addresses, empty when the app has none
369
+ */
370
+ list: async (app) => {
371
+ const data = await this.request(
372
+ `query AppIpAddresses($appName: String!) {
373
+ app(name: $appName) {
374
+ sharedIpAddress
375
+ ipAddresses { nodes { address type } }
376
+ }
377
+ }`,
378
+ { appName: app }
379
+ );
380
+ if (!data.app) {
381
+ return [];
382
+ }
383
+ const { sharedIpAddress, ipAddresses } = AppIpAddressesApiResponseSchema.parse(data.app);
384
+ return [
385
+ ...sharedIpAddress ? [{ address: sharedIpAddress, type: "shared_v4" }] : [],
386
+ ...ipAddresses.nodes
387
+ ];
388
+ }
389
+ };
335
390
  /**
336
391
  * Operate an app's machines.
337
392
  *
@@ -545,6 +600,18 @@ var killProcessTree = (0, import_util2.promisify)(import_tree_kill.default);
545
600
 
546
601
  // libs/shared/util/misc/src/lib/promisified-spawn.ts
547
602
  var import_child_process2 = require("child_process");
603
+ var STREAMED_STDERR_TAIL_LINES = 20;
604
+ var SpawnError = class extends Error {
605
+ exitCode;
606
+ stdout;
607
+ stderr;
608
+ constructor(message, details) {
609
+ super(message);
610
+ this.exitCode = details.exitCode;
611
+ this.stdout = details.stdout;
612
+ this.stderr = details.stderr;
613
+ }
614
+ };
548
615
  function spawn(command, args, options) {
549
616
  return new Promise((resolve, reject) => {
550
617
  const { streamToConsole, ...spawnOptions } = options || {};
@@ -572,8 +639,12 @@ function spawn(command, args, options) {
572
639
  if (code === 0) {
573
640
  resolve({ stdout, stderr });
574
641
  } else {
575
- reject(new Error(`Process exited with code ${code}
576
- Error: ${stderr}`));
642
+ const lines = stderr.replace(/\r?\n$/, "").split(/\r?\n/);
643
+ const message = streamToConsole && lines.length > STREAMED_STDERR_TAIL_LINES ? `Process exited with code ${code}
644
+ Error (last ${STREAMED_STDERR_TAIL_LINES} lines; the full output is above):
645
+ ${lines.slice(-STREAMED_STDERR_TAIL_LINES).join("\n")}` : `Process exited with code ${code}
646
+ Error: ${stderr}`;
647
+ reject(new SpawnError(message, { exitCode: code, stdout, stderr }));
577
648
  }
578
649
  });
579
650
  process2.on("error", reject);
@@ -615,23 +686,23 @@ Output: ${output}`)
615
686
  }
616
687
 
617
688
  // packages/fly-node/src/lib/fly.class.ts
618
- var import_zod36 = require("zod");
689
+ var import_zod40 = require("zod");
619
690
 
620
691
  // libs/shared/util/zod/src/lib/coerce-boolean.ts
621
- var import_zod3 = require("zod");
692
+ var import_zod5 = require("zod");
622
693
 
623
694
  // libs/shared/util/zod/src/lib/create-lowercase-schema.ts
624
- var import_zod4 = require("zod");
695
+ var import_zod6 = require("zod");
625
696
 
626
697
  // libs/shared/util/zod/src/lib/json.schema.ts
627
- var import_zod5 = require("zod");
628
- var LiteralSchema = import_zod5.z.union([import_zod5.z.string(), import_zod5.z.number(), import_zod5.z.boolean(), import_zod5.z.null()]);
629
- var JsonSchema = import_zod5.z.lazy(
630
- () => import_zod5.z.union([LiteralSchema, import_zod5.z.array(JsonSchema), import_zod5.z.record(JsonSchema)])
698
+ var import_zod7 = require("zod");
699
+ var LiteralSchema = import_zod7.z.union([import_zod7.z.string(), import_zod7.z.number(), import_zod7.z.boolean(), import_zod7.z.null()]);
700
+ var JsonSchema = import_zod7.z.lazy(
701
+ () => import_zod7.z.union([LiteralSchema, import_zod7.z.array(JsonSchema), import_zod7.z.record(JsonSchema)])
631
702
  );
632
703
 
633
704
  // libs/shared/util/zod/src/lib/with-camel-case.preprocess.ts
634
- var import_zod6 = require("zod");
705
+ var import_zod8 = require("zod");
635
706
  var toCamelCase = (str, specialCases = {}) => {
636
707
  if (specialCases[str]) {
637
708
  return specialCases[str];
@@ -681,7 +752,7 @@ var transformKeys = (options) => {
681
752
  };
682
753
  var withCamelCase = (schema, options = {}) => {
683
754
  const { preserve = [], specialCases = {} } = options;
684
- return import_zod6.z.preprocess(
755
+ return import_zod8.z.preprocess(
685
756
  (data) => transformKeys({
686
757
  currentPath: [],
687
758
  data,
@@ -693,38 +764,38 @@ var withCamelCase = (schema, options = {}) => {
693
764
  };
694
765
 
695
766
  // libs/shared/util/zod/src/lib/with-env-vars.preprocess.ts
696
- var import_zod7 = require("zod");
767
+ var import_zod9 = require("zod");
697
768
 
698
769
  // libs/shared/util/zod/src/lib/with-replace-all.preprocess.ts
699
- var import_zod8 = require("zod");
770
+ var import_zod10 = require("zod");
700
771
 
701
772
  // packages/fly-node/src/lib/schemas/apps-create.schema.ts
702
- var import_zod10 = require("zod");
773
+ var import_zod12 = require("zod");
703
774
  var AppsCreateTransformedResponseSchema = withCamelCase(
704
- import_zod10.z.object({
705
- id: import_zod10.z.string(),
706
- name: import_zod10.z.string()
775
+ import_zod12.z.object({
776
+ id: import_zod12.z.string(),
777
+ name: import_zod12.z.string()
707
778
  })
708
779
  );
709
780
 
710
781
  // packages/fly-node/src/lib/schemas/apps-list.schema.ts
711
- var import_zod12 = require("zod");
712
- var AppsListTransformedResponseSchema = import_zod12.z.array(
782
+ var import_zod14 = require("zod");
783
+ var AppsListTransformedResponseSchema = import_zod14.z.array(
713
784
  withCamelCase(
714
- import_zod12.z.object({
715
- id: import_zod12.z.string(),
716
- name: import_zod12.z.string(),
717
- status: import_zod12.z.string(),
718
- deployed: import_zod12.z.boolean(),
719
- hostname: import_zod12.z.string(),
720
- organization: import_zod12.z.object({
721
- name: import_zod12.z.string(),
722
- slug: import_zod12.z.string()
785
+ import_zod14.z.object({
786
+ id: import_zod14.z.string(),
787
+ name: import_zod14.z.string(),
788
+ status: import_zod14.z.string(),
789
+ deployed: import_zod14.z.boolean(),
790
+ hostname: import_zod14.z.string(),
791
+ organization: import_zod14.z.object({
792
+ name: import_zod14.z.string(),
793
+ slug: import_zod14.z.string()
723
794
  }),
724
- currentRelease: import_zod12.z.nullable(
725
- import_zod12.z.object({
726
- status: import_zod12.z.string(),
727
- createdAt: import_zod12.z.string().datetime()
795
+ currentRelease: import_zod14.z.nullable(
796
+ import_zod14.z.object({
797
+ status: import_zod14.z.string(),
798
+ createdAt: import_zod14.z.string().datetime()
728
799
  })
729
800
  )
730
801
  })
@@ -732,53 +803,53 @@ var AppsListTransformedResponseSchema = import_zod12.z.array(
732
803
  );
733
804
 
734
805
  // packages/fly-node/src/lib/schemas/build-response.schema.ts
735
- var import_zod13 = require("zod");
736
- var BuildResponseSchema = import_zod13.z.object({
737
- appName: import_zod13.z.string(),
738
- imageRef: import_zod13.z.string()
806
+ var import_zod15 = require("zod");
807
+ var BuildResponseSchema = import_zod15.z.object({
808
+ appName: import_zod15.z.string(),
809
+ imageRef: import_zod15.z.string()
739
810
  });
740
811
 
741
812
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
742
- var import_zod17 = require("zod");
813
+ var import_zod19 = require("zod");
743
814
 
744
815
  // packages/fly-node/src/lib/schemas/certs-list.schema.ts
745
- var import_zod15 = require("zod");
746
- var CertsListFlyResponseElementSchema = import_zod15.z.object({
747
- createdAt: import_zod15.z.string().datetime(),
748
- hostname: import_zod15.z.string(),
749
- clientStatus: import_zod15.z.string()
816
+ var import_zod17 = require("zod");
817
+ var CertsListFlyResponseElementSchema = import_zod17.z.object({
818
+ createdAt: import_zod17.z.string().datetime(),
819
+ hostname: import_zod17.z.string(),
820
+ clientStatus: import_zod17.z.string()
750
821
  });
751
- var CertsListTransformedResponseSchema = import_zod15.z.array(
822
+ var CertsListTransformedResponseSchema = import_zod17.z.array(
752
823
  withCamelCase(CertsListFlyResponseElementSchema)
753
824
  );
754
825
 
755
826
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
756
- var CertsListWithAppTransformedResponseSchema = import_zod17.z.array(
827
+ var CertsListWithAppTransformedResponseSchema = import_zod19.z.array(
757
828
  withCamelCase(
758
829
  CertsListFlyResponseElementSchema.extend({
759
- app: import_zod17.z.string()
830
+ app: import_zod19.z.string()
760
831
  })
761
832
  )
762
833
  );
763
834
 
764
835
  // packages/fly-node/src/lib/schemas/config-show.schema.ts
765
- var import_zod19 = require("zod");
836
+ var import_zod21 = require("zod");
766
837
  var ConfigShowResponseSchema = withCamelCase(
767
- import_zod19.z.object({
768
- app: import_zod19.z.string(),
769
- primaryRegion: import_zod19.z.string().optional(),
770
- build: import_zod19.z.record(import_zod19.z.string(), import_zod19.z.any()).optional().or(
771
- import_zod19.z.object({
772
- args: import_zod19.z.record(import_zod19.z.string(), import_zod19.z.string()).optional(),
773
- dockerfile: import_zod19.z.string().optional(),
774
- image: import_zod19.z.string().optional()
838
+ import_zod21.z.object({
839
+ app: import_zod21.z.string(),
840
+ primaryRegion: import_zod21.z.string().optional(),
841
+ build: import_zod21.z.record(import_zod21.z.string(), import_zod21.z.any()).optional().or(
842
+ import_zod21.z.object({
843
+ args: import_zod21.z.record(import_zod21.z.string(), import_zod21.z.string()).optional(),
844
+ dockerfile: import_zod21.z.string().optional(),
845
+ image: import_zod21.z.string().optional()
775
846
  })
776
847
  ),
777
- deploy: import_zod19.z.record(import_zod19.z.string(), import_zod19.z.any()).optional().or(import_zod19.z.object({ strategy: import_zod19.z.string().optional() })),
778
- env: import_zod19.z.record(import_zod19.z.string(), import_zod19.z.string()).optional(),
779
- httpService: import_zod19.z.record(import_zod19.z.string(), import_zod19.z.any()).optional(),
780
- mounts: import_zod19.z.record(import_zod19.z.string(), import_zod19.z.any()).optional(),
781
- services: import_zod19.z.array(import_zod19.z.record(import_zod19.z.string(), import_zod19.z.any())).optional()
848
+ deploy: import_zod21.z.record(import_zod21.z.string(), import_zod21.z.any()).optional().or(import_zod21.z.object({ strategy: import_zod21.z.string().optional() })),
849
+ env: import_zod21.z.record(import_zod21.z.string(), import_zod21.z.string()).optional(),
850
+ httpService: import_zod21.z.record(import_zod21.z.string(), import_zod21.z.any()).optional(),
851
+ mounts: import_zod21.z.record(import_zod21.z.string(), import_zod21.z.any()).optional(),
852
+ services: import_zod21.z.array(import_zod21.z.record(import_zod21.z.string(), import_zod21.z.any())).optional()
782
853
  }),
783
854
  {
784
855
  preserve: ["build.args", "env"]
@@ -786,126 +857,139 @@ var ConfigShowResponseSchema = withCamelCase(
786
857
  );
787
858
 
788
859
  // packages/fly-node/src/lib/schemas/deploy.schema.ts
789
- var import_zod20 = require("zod");
790
- var DeployResponseSchema = import_zod20.z.object({
791
- app: import_zod20.z.string(),
792
- hostname: import_zod20.z.string(),
793
- url: import_zod20.z.string().url()
860
+ var import_zod22 = require("zod");
861
+ var DeployResponseSchema = import_zod22.z.object({
862
+ app: import_zod22.z.string(),
863
+ hostname: import_zod22.z.string(),
864
+ url: import_zod22.z.string().url()
794
865
  });
795
866
 
796
867
  // packages/fly-node/src/lib/schemas/helper-schemas.ts
797
- var import_zod21 = require("zod");
798
- var AllowEmptyUrlSchema = import_zod21.z.string().url().or(import_zod21.z.literal(""));
799
- var NameSchema = import_zod21.z.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
868
+ var import_zod23 = require("zod");
869
+ var AllowEmptyUrlSchema = import_zod23.z.string().url().or(import_zod23.z.literal(""));
870
+ var NameSchema = import_zod23.z.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
871
+
872
+ // packages/fly-node/src/lib/schemas/ips-list.schema.ts
873
+ var import_zod25 = require("zod");
874
+ var IpsListFlyResponseElementSchema = import_zod25.z.object({
875
+ id: import_zod25.z.string(),
876
+ address: import_zod25.z.string(),
877
+ type: IpTypeSchema,
878
+ region: import_zod25.z.string(),
879
+ createdAt: import_zod25.z.string()
880
+ });
881
+ var IpsListTransformedResponseSchema = import_zod25.z.array(
882
+ withCamelCase(IpsListFlyResponseElementSchema)
883
+ );
800
884
 
801
885
  // packages/fly-node/src/lib/schemas/postgres-list.ts
802
- var import_zod23 = require("zod");
803
- var PostgresListTransformedResponseSchema = import_zod23.z.array(
886
+ var import_zod27 = require("zod");
887
+ var PostgresListTransformedResponseSchema = import_zod27.z.array(
804
888
  withCamelCase(
805
- import_zod23.z.object({
806
- deployed: import_zod23.z.boolean(),
807
- hostname: import_zod23.z.string(),
808
- id: import_zod23.z.string(),
809
- name: import_zod23.z.string(),
810
- organization: import_zod23.z.object({ id: import_zod23.z.string(), slug: import_zod23.z.string() }),
811
- status: import_zod23.z.string(),
812
- version: import_zod23.z.number()
889
+ import_zod27.z.object({
890
+ deployed: import_zod27.z.boolean(),
891
+ hostname: import_zod27.z.string(),
892
+ id: import_zod27.z.string(),
893
+ name: import_zod27.z.string(),
894
+ organization: import_zod27.z.object({ id: import_zod27.z.string(), slug: import_zod27.z.string() }),
895
+ status: import_zod27.z.string(),
896
+ version: import_zod27.z.number()
813
897
  })
814
898
  )
815
- ).or(import_zod23.z.string());
899
+ ).or(import_zod27.z.string());
816
900
 
817
901
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
818
- var import_zod25 = require("zod");
819
- var PostgresUsersListTransformedResponseSchema = import_zod25.z.array(
902
+ var import_zod29 = require("zod");
903
+ var PostgresUsersListTransformedResponseSchema = import_zod29.z.array(
820
904
  withCamelCase(
821
- import_zod25.z.object({
822
- username: import_zod25.z.string(),
823
- superuser: import_zod25.z.boolean(),
824
- databases: import_zod25.z.array(import_zod25.z.string())
905
+ import_zod29.z.object({
906
+ username: import_zod29.z.string(),
907
+ superuser: import_zod29.z.boolean(),
908
+ databases: import_zod29.z.array(import_zod29.z.string())
825
909
  })
826
910
  )
827
911
  );
828
912
 
829
913
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
830
- var import_zod29 = require("zod");
914
+ var import_zod33 = require("zod");
831
915
 
832
916
  // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
833
- var import_zod27 = require("zod");
834
- var SecretsListFlyResponseElementSchema = import_zod27.z.object({
835
- name: import_zod27.z.string(),
836
- digest: import_zod27.z.string()
917
+ var import_zod31 = require("zod");
918
+ var SecretsListFlyResponseElementSchema = import_zod31.z.object({
919
+ name: import_zod31.z.string(),
920
+ digest: import_zod31.z.string()
837
921
  });
838
- var SecretsListTransformedResponseSchema = import_zod27.z.array(
922
+ var SecretsListTransformedResponseSchema = import_zod31.z.array(
839
923
  withCamelCase(SecretsListFlyResponseElementSchema)
840
924
  );
841
925
 
842
926
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
843
- var SecretsListWithAppTransformedResponseSchema = import_zod29.z.array(
927
+ var SecretsListWithAppTransformedResponseSchema = import_zod33.z.array(
844
928
  withCamelCase(
845
929
  SecretsListFlyResponseElementSchema.extend({
846
- app: import_zod29.z.string()
930
+ app: import_zod33.z.string()
847
931
  })
848
932
  )
849
933
  );
850
934
 
851
935
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
852
- var import_zod33 = require("zod");
936
+ var import_zod37 = require("zod");
853
937
 
854
938
  // packages/fly-node/src/lib/schemas/status.schema.ts
855
- var import_zod31 = require("zod");
856
- var statusFlyResponseSchema = import_zod31.z.object({
857
- deployed: import_zod31.z.boolean(),
858
- hostname: import_zod31.z.string(),
859
- id: import_zod31.z.string(),
860
- machines: import_zod31.z.array(
861
- import_zod31.z.object({
862
- id: import_zod31.z.string(),
863
- name: import_zod31.z.string(),
864
- state: import_zod31.z.string(),
865
- region: import_zod31.z.string(),
866
- imageRef: import_zod31.z.object({
867
- registry: import_zod31.z.string(),
868
- repository: import_zod31.z.string(),
869
- tag: import_zod31.z.string(),
870
- digest: import_zod31.z.string(),
871
- labels: import_zod31.z.record(import_zod31.z.string()).optional()
939
+ var import_zod35 = require("zod");
940
+ var statusFlyResponseSchema = import_zod35.z.object({
941
+ deployed: import_zod35.z.boolean(),
942
+ hostname: import_zod35.z.string(),
943
+ id: import_zod35.z.string(),
944
+ machines: import_zod35.z.array(
945
+ import_zod35.z.object({
946
+ id: import_zod35.z.string(),
947
+ name: import_zod35.z.string(),
948
+ state: import_zod35.z.string(),
949
+ region: import_zod35.z.string(),
950
+ imageRef: import_zod35.z.object({
951
+ registry: import_zod35.z.string(),
952
+ repository: import_zod35.z.string(),
953
+ tag: import_zod35.z.string(),
954
+ digest: import_zod35.z.string(),
955
+ labels: import_zod35.z.record(import_zod35.z.string()).optional()
872
956
  }),
873
- createdAt: import_zod31.z.string().datetime(),
874
- updatedAt: import_zod31.z.string().datetime(),
875
- config: import_zod31.z.object({
876
- env: import_zod31.z.record(import_zod31.z.string()),
877
- metadata: import_zod31.z.record(import_zod31.z.string()),
878
- guest: import_zod31.z.object({
879
- cpu_kind: import_zod31.z.string().optional(),
880
- cpus: import_zod31.z.number().optional(),
881
- memory_mb: import_zod31.z.number().optional()
957
+ createdAt: import_zod35.z.string().datetime(),
958
+ updatedAt: import_zod35.z.string().datetime(),
959
+ config: import_zod35.z.object({
960
+ env: import_zod35.z.record(import_zod35.z.string()),
961
+ metadata: import_zod35.z.record(import_zod35.z.string()),
962
+ guest: import_zod35.z.object({
963
+ cpu_kind: import_zod35.z.string().optional(),
964
+ cpus: import_zod35.z.number().optional(),
965
+ memory_mb: import_zod35.z.number().optional()
882
966
  }).optional()
883
967
  }),
884
- events: import_zod31.z.array(
885
- import_zod31.z.object({
886
- type: import_zod31.z.string(),
887
- status: import_zod31.z.string(),
888
- timestamp: import_zod31.z.number()
968
+ events: import_zod35.z.array(
969
+ import_zod35.z.object({
970
+ type: import_zod35.z.string(),
971
+ status: import_zod35.z.string(),
972
+ timestamp: import_zod35.z.number()
889
973
  })
890
974
  ),
891
- checks: import_zod31.z.array(
892
- import_zod31.z.object({
893
- name: import_zod31.z.string(),
894
- status: import_zod31.z.string(),
895
- output: import_zod31.z.string(),
896
- updatedAt: import_zod31.z.string().datetime()
975
+ checks: import_zod35.z.array(
976
+ import_zod35.z.object({
977
+ name: import_zod35.z.string(),
978
+ status: import_zod35.z.string(),
979
+ output: import_zod35.z.string(),
980
+ updatedAt: import_zod35.z.string().datetime()
897
981
  })
898
982
  ).optional(),
899
- hostStatus: import_zod31.z.string()
983
+ hostStatus: import_zod35.z.string()
900
984
  })
901
985
  ),
902
- name: import_zod31.z.string(),
903
- organization: import_zod31.z.object({
904
- id: import_zod31.z.string(),
905
- slug: import_zod31.z.string()
986
+ name: import_zod35.z.string(),
987
+ organization: import_zod35.z.object({
988
+ id: import_zod35.z.string(),
989
+ slug: import_zod35.z.string()
906
990
  }),
907
- status: import_zod31.z.string(),
908
- version: import_zod31.z.number()
991
+ status: import_zod35.z.string(),
992
+ version: import_zod35.z.number()
909
993
  });
910
994
  var StatusTransformedResponseSchema = withCamelCase(
911
995
  statusFlyResponseSchema,
@@ -918,12 +1002,24 @@ var StatusTransformedResponseSchema = withCamelCase(
918
1002
  specialCases: { AppURL: "appUrl" }
919
1003
  }
920
1004
  );
1005
+ var statusLookupSchema = withCamelCase(
1006
+ import_zod35.z.object({
1007
+ name: import_zod35.z.string(),
1008
+ hostname: import_zod35.z.string(),
1009
+ machines: import_zod35.z.array(
1010
+ import_zod35.z.object({
1011
+ id: import_zod35.z.string(),
1012
+ state: import_zod35.z.string()
1013
+ }).passthrough()
1014
+ )
1015
+ }).passthrough()
1016
+ );
921
1017
 
922
1018
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
923
1019
  var StatusExtendedTransformedResponseSchema = withCamelCase(
924
1020
  statusFlyResponseSchema.extend({
925
- domains: import_zod33.z.array(import_zod33.z.object({ hostname: import_zod33.z.string() })),
926
- secrets: import_zod33.z.array(import_zod33.z.object({ name: import_zod33.z.string() }))
1021
+ domains: import_zod37.z.array(import_zod37.z.object({ hostname: import_zod37.z.string() })),
1022
+ secrets: import_zod37.z.array(import_zod37.z.object({ name: import_zod37.z.string() }))
927
1023
  }),
928
1024
  {
929
1025
  preserve: [
@@ -935,21 +1031,35 @@ var StatusExtendedTransformedResponseSchema = withCamelCase(
935
1031
  );
936
1032
 
937
1033
  // packages/fly-node/src/lib/schemas/version.schema.ts
938
- var import_zod35 = require("zod");
1034
+ var import_zod39 = require("zod");
939
1035
  var VersionTransformedResponseSchema = withCamelCase(
940
- import_zod35.z.object({
941
- name: import_zod35.z.string(),
942
- version: import_zod35.z.string(),
943
- commit: import_zod35.z.string(),
944
- branchName: import_zod35.z.string(),
945
- buildDate: import_zod35.z.string().datetime(),
946
- os: import_zod35.z.string(),
947
- architecture: import_zod35.z.string(),
948
- environment: import_zod35.z.string()
1036
+ import_zod39.z.object({
1037
+ name: import_zod39.z.string(),
1038
+ version: import_zod39.z.string(),
1039
+ commit: import_zod39.z.string(),
1040
+ branchName: import_zod39.z.string(),
1041
+ buildDate: import_zod39.z.string().datetime(),
1042
+ os: import_zod39.z.string(),
1043
+ architecture: import_zod39.z.string(),
1044
+ environment: import_zod39.z.string()
949
1045
  })
950
1046
  );
951
1047
 
952
1048
  // packages/fly-node/src/lib/fly.class.ts
1049
+ var TRANSIENT_FLY_ERRORS = [
1050
+ { cause: "no capacity available", pattern: /no capacity available/i },
1051
+ { cause: "builder deadline exceeded", pattern: /deadline_exceeded/i },
1052
+ {
1053
+ cause: "timed out connecting to machine",
1054
+ pattern: /timed out connecting to machine/i
1055
+ },
1056
+ // The status text, not a bare 503: an app whose health check answers
1057
+ // 503 is broken, not unlucky, and must not be deployed three times
1058
+ { cause: "Fly API 503", pattern: /503 Service Unavailable/i }
1059
+ ];
1060
+ var TRANSIENT_RETRY_DELAYS_MS = [1e4, 3e4];
1061
+ var MACHINE_STATE_INTERVAL_MS = 2e3;
1062
+ var MACHINE_STATE_TIMEOUT_MS = 12e4;
953
1063
  var Fly = class {
954
1064
  /** Use underscore to avoid conflict with public `config` property */
955
1065
  _config;
@@ -1033,7 +1143,9 @@ ${error}`);
1033
1143
  return await this.version();
1034
1144
  } catch (error) {
1035
1145
  throw new Error(`[version] something broke
1036
- ${error}`);
1146
+ ${error}`, {
1147
+ cause: error
1148
+ });
1037
1149
  }
1038
1150
  }
1039
1151
  };
@@ -1060,7 +1172,8 @@ ${error}`);
1060
1172
  } catch (error) {
1061
1173
  throw new Error(
1062
1174
  `[create app] something broke, check your apps
1063
- ${error}`
1175
+ ${error}`,
1176
+ { cause: error }
1064
1177
  );
1065
1178
  }
1066
1179
  },
@@ -1086,7 +1199,8 @@ ${error}`
1086
1199
  } catch (error) {
1087
1200
  throw new Error(
1088
1201
  `[destroy app] something broke, check your apps
1089
- ${error}`
1202
+ ${error}`,
1203
+ { cause: error }
1090
1204
  );
1091
1205
  }
1092
1206
  },
@@ -1101,7 +1215,7 @@ ${error}`
1101
1215
  return await this.fetchAllApps("throwOnError");
1102
1216
  } catch (error) {
1103
1217
  throw new Error(`[list] something broke
1104
- ${error}`);
1218
+ ${error}`, { cause: error });
1105
1219
  }
1106
1220
  }
1107
1221
  };
@@ -1126,7 +1240,8 @@ ${error}`);
1126
1240
  } catch (error) {
1127
1241
  throw new Error(
1128
1242
  `[add certificate] something broke, check your app certificates
1129
- ${error}`
1243
+ ${error}`,
1244
+ { cause: error }
1130
1245
  );
1131
1246
  }
1132
1247
  },
@@ -1144,7 +1259,9 @@ ${error}`
1144
1259
  return result;
1145
1260
  } catch (error) {
1146
1261
  throw new Error(`[list certificates] something broke
1147
- ${error}`);
1262
+ ${error}`, {
1263
+ cause: error
1264
+ });
1148
1265
  }
1149
1266
  },
1150
1267
  /**
@@ -1164,7 +1281,8 @@ ${error}`);
1164
1281
  } catch (error) {
1165
1282
  throw new Error(
1166
1283
  `[remove certificate] something broke, check your app certificates
1167
- ${error}`
1284
+ ${error}`,
1285
+ { cause: error }
1168
1286
  );
1169
1287
  }
1170
1288
  }
@@ -1191,7 +1309,9 @@ ${error}`
1191
1309
  );
1192
1310
  } catch (error) {
1193
1311
  throw new Error(`[save config] something broke
1194
- ${error}`);
1312
+ ${error}`, {
1313
+ cause: error
1314
+ });
1195
1315
  }
1196
1316
  },
1197
1317
  /**
@@ -1207,7 +1327,9 @@ ${error}`);
1207
1327
  return await this.showConfig("throwOnError", options);
1208
1328
  } catch (error) {
1209
1329
  throw new Error(`[show config] something broke
1210
- ${error}`);
1330
+ ${error}`, {
1331
+ cause: error
1332
+ });
1211
1333
  }
1212
1334
  }
1213
1335
  };
@@ -1250,7 +1372,7 @@ ${error}`);
1250
1372
  }
1251
1373
  const { appName } = await this.deployApp(options);
1252
1374
  this.logger.info(`Application '${appName}' was deployed`);
1253
- const status = await this.fetchAppStatus("throwOnError", {
1375
+ const status = await this.fetchAppLookup("throwOnError", {
1254
1376
  app: appName
1255
1377
  });
1256
1378
  return DeployResponseSchema.parse({
@@ -1261,10 +1383,74 @@ ${error}`);
1261
1383
  } catch (error) {
1262
1384
  throw new Error(
1263
1385
  `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
1264
- ${error}`
1386
+ ${error}`,
1387
+ { cause: error }
1265
1388
  );
1266
1389
  }
1267
1390
  };
1391
+ /**
1392
+ * Manage public IP addresses
1393
+ */
1394
+ ips = {
1395
+ /**
1396
+ * List the public IP addresses allocated to an application
1397
+ *
1398
+ * @param options - The application or configuration to list addresses for
1399
+ * @returns The allocated addresses, empty when the app has none
1400
+ * @throws An error if listing addresses fails
1401
+ */
1402
+ list: async (options) => {
1403
+ try {
1404
+ await this.ensureInitialized();
1405
+ return await this.fetchAppIps("throwOnError", options);
1406
+ } catch (error) {
1407
+ throw new Error(`[list ips] something broke
1408
+ ${error}`, {
1409
+ cause: error
1410
+ });
1411
+ }
1412
+ },
1413
+ /**
1414
+ * Give an application the public addresses it needs to be reachable.
1415
+ *
1416
+ * Idempotent by inspection: it allocates only what is missing, so it is
1417
+ * safe on every deploy rather than only on create. That matters because
1418
+ * `flyctl` allocates addresses only for an app it creates itself — an app
1419
+ * that arrives any other way, such as a registry push auto-creating it,
1420
+ * deploys green and answers nothing. `deploy` runs it before every
1421
+ * deploy that is not build-only.
1422
+ *
1423
+ * @param options - The application, and which addresses to ensure
1424
+ * @returns The addresses the application holds afterwards
1425
+ * @throws An error if an address cannot be allocated
1426
+ */
1427
+ ensure: async (options) => {
1428
+ try {
1429
+ await this.ensureInitialized();
1430
+ const { sharedV4 = true, v6 = true } = options ?? {};
1431
+ const existing = await this.fetchAppIps("throwOnError", options);
1432
+ const has = (...types) => existing.some((ip) => types.includes(ip.type));
1433
+ let allocated = false;
1434
+ if (sharedV4 && !has("v4", "shared_v4")) {
1435
+ await this.allocateIp("allocate-v4", options);
1436
+ this.logger.info("Allocated a shared IPv4 address");
1437
+ allocated = true;
1438
+ }
1439
+ if (v6 && !has("v6")) {
1440
+ await this.allocateIp("allocate-v6", options);
1441
+ this.logger.info("Allocated a dedicated IPv6 address");
1442
+ allocated = true;
1443
+ }
1444
+ return allocated ? await this.fetchAppIps("throwOnError", options) : existing;
1445
+ } catch (error) {
1446
+ throw new Error(
1447
+ `[ensure ips] something broke, check your app addresses
1448
+ ${error}`,
1449
+ { cause: error }
1450
+ );
1451
+ }
1452
+ }
1453
+ };
1268
1454
  /**
1269
1455
  * Manage machines
1270
1456
  */
@@ -1283,7 +1469,9 @@ ${error}`
1283
1469
  this.logger.info(`Machine '${machineId}' in app '${app}' was started`);
1284
1470
  } catch (error) {
1285
1471
  throw new Error(`[start machine] something broke
1286
- ${error}`);
1472
+ ${error}`, {
1473
+ cause: error
1474
+ });
1287
1475
  }
1288
1476
  },
1289
1477
  /**
@@ -1300,11 +1488,17 @@ ${error}`);
1300
1488
  this.logger.info(`Machine '${machineId}' in app '${app}' was stopped`);
1301
1489
  } catch (error) {
1302
1490
  throw new Error(`[stop machine] something broke
1303
- ${error}`);
1491
+ ${error}`, {
1492
+ cause: error
1493
+ });
1304
1494
  }
1305
1495
  },
1306
1496
  /**
1307
- * Restart a machine by stopping then starting it
1497
+ * Restart a machine by stopping then starting it.
1498
+ *
1499
+ * Waits until Fly reports the machine stopped (or suspended) before
1500
+ * starting it, then until it is started. If the start fails after the
1501
+ * stop, the error says the machine was left stopped.
1308
1502
  *
1309
1503
  * @param app - The name of the application
1310
1504
  * @param machineId - The machine ID to restart
@@ -1319,7 +1513,9 @@ ${error}`);
1319
1513
  );
1320
1514
  } catch (error) {
1321
1515
  throw new Error(`[restart machine] something broke
1322
- ${error}`);
1516
+ ${error}`, {
1517
+ cause: error
1518
+ });
1323
1519
  }
1324
1520
  },
1325
1521
  /**
@@ -1340,7 +1536,9 @@ ${error}`);
1340
1536
  this.logger.info(`Machine '${machineId}' in app '${app}' was updated`);
1341
1537
  } catch (error) {
1342
1538
  throw new Error(`[update machine] something broke
1343
- ${error}`);
1539
+ ${error}`, {
1540
+ cause: error
1541
+ });
1344
1542
  }
1345
1543
  }
1346
1544
  };
@@ -1374,7 +1572,9 @@ ${error}`);
1374
1572
  return await this.sshExec(app, command);
1375
1573
  } catch (error) {
1376
1574
  throw new Error(`[ssh exec] something broke
1377
- ${error}`);
1575
+ ${error}`, {
1576
+ cause: error
1577
+ });
1378
1578
  }
1379
1579
  }
1380
1580
  };
@@ -1400,7 +1600,8 @@ ${error}`);
1400
1600
  } catch (error) {
1401
1601
  throw new Error(
1402
1602
  `[set secrets] something broke, check your app secrets
1403
- ${error}`
1603
+ ${error}`,
1604
+ { cause: error }
1404
1605
  );
1405
1606
  }
1406
1607
  },
@@ -1423,7 +1624,9 @@ ${error}`
1423
1624
  this.logger.info(`Staged secrets were deployed for '${app}'`);
1424
1625
  } catch (error) {
1425
1626
  throw new Error(`[deploy secrets] something broke
1426
- ${error}`);
1627
+ ${error}`, {
1628
+ cause: error
1629
+ });
1427
1630
  }
1428
1631
  },
1429
1632
  /**
@@ -1440,7 +1643,9 @@ ${error}`);
1440
1643
  return result;
1441
1644
  } catch (error) {
1442
1645
  throw new Error(`[list secrets] something broke
1443
- ${error}`);
1646
+ ${error}`, {
1647
+ cause: error
1648
+ });
1444
1649
  }
1445
1650
  },
1446
1651
  /**
@@ -1461,7 +1666,8 @@ ${error}`);
1461
1666
  } catch (error) {
1462
1667
  throw new Error(
1463
1668
  `[unset secrets] something broke, check your app secrets
1464
- ${error}`
1669
+ ${error}`,
1670
+ { cause: error }
1465
1671
  );
1466
1672
  }
1467
1673
  }
@@ -1553,7 +1759,6 @@ ${error}`);
1553
1759
  */
1554
1760
  async deployApp(options) {
1555
1761
  let appName = "";
1556
- let appSecrets = [];
1557
1762
  let deployConfig = options?.config || this.instanceConfig;
1558
1763
  let lookupApp = options?.app || this.instanceApp;
1559
1764
  const lookupConfig = deployConfig;
@@ -1575,7 +1780,7 @@ ${error}`);
1575
1780
  lookupApp = appConfig.app;
1576
1781
  }
1577
1782
  if (lookupApp) {
1578
- const status = await this.fetchAppStatus("nullOnError", {
1783
+ const status = await this.fetchAppLookup("nullOnError", {
1579
1784
  app: lookupApp
1580
1785
  });
1581
1786
  if (status) {
@@ -1618,26 +1823,30 @@ ${error}`);
1618
1823
  appName = name;
1619
1824
  this.logger.info(`Application '${appName}' was created`);
1620
1825
  } else {
1621
- appSecrets = await this.fetchAppSecrets("throwOnError", { app: appName });
1622
1826
  this.logger.info(`Updating existing application '${appName}'`);
1623
1827
  }
1624
1828
  NameSchema.parse(appName);
1625
1829
  if (!options?.buildOnly && options?.secrets) {
1626
- const existingSecrets = new Set(appSecrets.map(({ name }) => name));
1627
- const newSecrets = {};
1830
+ const staged = {};
1831
+ const empty = [];
1628
1832
  for (const [key, value] of Object.entries(options.secrets)) {
1629
- if (!existingSecrets.has(key)) {
1630
- newSecrets[key] = value;
1833
+ if (value === "") {
1834
+ empty.push(key);
1631
1835
  } else {
1632
- this.logger.info(
1633
- `Secret '${key}' already exists for '${appName}', skipping`
1634
- );
1836
+ staged[key] = value;
1635
1837
  }
1636
1838
  }
1637
- const keys = Object.keys(newSecrets);
1839
+ if (empty.length > 0) {
1840
+ this.logger.error(
1841
+ `Refusing to blank secrets with no value for '${appName}': ${empty.join(", ")}`
1842
+ );
1843
+ }
1844
+ const keys = Object.keys(staged);
1638
1845
  if (keys.length > 0) {
1639
- this.logger.info(`Adding secrets to '${appName}': ${keys.join(", ")}`);
1640
- await this.setAppSecrets(newSecrets, {
1846
+ this.logger.info(
1847
+ `Staging secrets for '${appName}': ${keys.join(", ")}`
1848
+ );
1849
+ await this.setAppSecrets(staged, {
1641
1850
  app: appName,
1642
1851
  stage: true
1643
1852
  });
@@ -1673,6 +1882,10 @@ ${error}`);
1673
1882
  );
1674
1883
  }
1675
1884
  }
1885
+ const servesTraffic = !!appConfig.httpService || (appConfig.services?.length ?? 0) > 0;
1886
+ if (!options?.buildOnly && servesTraffic) {
1887
+ await this.ips.ensure({ app: appName });
1888
+ }
1676
1889
  const args = ["deploy", "--app", appName, "--config", deployConfig];
1677
1890
  if (options?.region) {
1678
1891
  args.push("--region", options.region);
@@ -1699,10 +1912,10 @@ ${error}`);
1699
1912
  this.logger.info(
1700
1913
  options?.buildOnly ? `Building image for '${appName}'...` : `Deploying '${appName}'...`
1701
1914
  );
1702
- const output = await this.execFly(
1703
- args,
1704
- options?.buildOnly ? { streamStrategy: "combined" } : void 0
1705
- );
1915
+ const output = await this.execFly(args, {
1916
+ streamStrategy: options?.buildOnly ? "combined" : "stdout",
1917
+ retry: true
1918
+ });
1706
1919
  const imageRef = options?.buildOnly ? output?.match(/registry\.fly\.io\/\S+/)?.[0] : void 0;
1707
1920
  return { appName, imageRef };
1708
1921
  }
@@ -1748,7 +1961,7 @@ ${error}`);
1748
1961
  * @throws An error if the secrets cannot be set
1749
1962
  */
1750
1963
  async setAppSecrets(secrets, options) {
1751
- const status = await this.fetchAppStatus("throwOnError", options);
1964
+ const status = await this.fetchAppLookup("throwOnError", options);
1752
1965
  const args = ["secrets", "set"];
1753
1966
  args.push(...this.getAppOrConfigArgs(options));
1754
1967
  if (options?.stage) {
@@ -1757,7 +1970,7 @@ ${error}`);
1757
1970
  for (const [key, value] of Object.entries(secrets)) {
1758
1971
  args.push(`${key}=${this.safeArg(value)}`);
1759
1972
  }
1760
- await this.execFly(args);
1973
+ await this.execFly(args, { retry: options?.stage === true });
1761
1974
  return NameSchema.parse(status.name);
1762
1975
  }
1763
1976
  /**
@@ -1766,7 +1979,7 @@ ${error}`);
1766
1979
  * @throws An error if the secrets cannot be unset
1767
1980
  */
1768
1981
  async unsetAppSecrets(keys, options) {
1769
- const status = await this.fetchAppStatus("throwOnError", options);
1982
+ const status = await this.fetchAppLookup("throwOnError", options);
1770
1983
  const args = ["secrets", "unset"];
1771
1984
  args.push(...this.getAppOrConfigArgs(options));
1772
1985
  if (options?.stage) {
@@ -1782,20 +1995,59 @@ ${error}`);
1782
1995
  * @throws An error if the domain cannot be added
1783
1996
  */
1784
1997
  async addAppCertificate(hostname, options) {
1785
- const status = await this.fetchAppStatus("throwOnError", options);
1998
+ const status = await this.fetchAppLookup("throwOnError", options);
1786
1999
  const args = ["certs", "add", hostname];
1787
2000
  args.push(...this.getAppOrConfigArgs(options));
1788
2001
  args.push("--json");
1789
2002
  await this.execFly(args);
1790
2003
  return NameSchema.parse(status.name);
1791
2004
  }
2005
+ /**
2006
+ * Allocate one public address.
2007
+ *
2008
+ * A dedicated v4 is billed, so the v4 path is always `--shared`.
2009
+ *
2010
+ * The two commands do not take the same flags: `allocate-v4` has `--yes`
2011
+ * because a dedicated v4 costs money and prompts, while `allocate-v6` is
2012
+ * free, never prompts, and rejects the flag outright with `unknown flag`.
2013
+ * The asymmetry is flyctl's, not ours — do not tidy it away.
2014
+ *
2015
+ * @private
2016
+ * @throws An error if the address cannot be allocated
2017
+ */
2018
+ async allocateIp(command, options) {
2019
+ const args = ["ips", command];
2020
+ if (command === "allocate-v4") {
2021
+ args.push("--shared");
2022
+ }
2023
+ args.push(...this.getAppOrConfigArgs(options));
2024
+ if (command === "allocate-v4") {
2025
+ args.push("--yes");
2026
+ }
2027
+ await this.execFly(args);
2028
+ }
2029
+ async fetchAppIps(onError, options) {
2030
+ const args = ["ips", "list"];
2031
+ args.push(...this.getAppOrConfigArgs(options));
2032
+ args.push("--json");
2033
+ try {
2034
+ return await IpsListTransformedResponseSchema.parseAsync(
2035
+ await this.execFly(args, { retry: true })
2036
+ );
2037
+ } catch (error) {
2038
+ if (onError === "throwOnError") {
2039
+ throw error;
2040
+ }
2041
+ return null;
2042
+ }
2043
+ }
1792
2044
  /**
1793
2045
  * @private
1794
2046
  * @returns The name of the application
1795
2047
  * @throws An error if the domain cannot be removed
1796
2048
  */
1797
2049
  async removeAppCertificate(hostname, options) {
1798
- const status = await this.fetchAppStatus("throwOnError", options);
2050
+ const status = await this.fetchAppLookup("throwOnError", options);
1799
2051
  const args = ["certs", "remove", hostname];
1800
2052
  args.push(...this.getAppOrConfigArgs(options));
1801
2053
  args.push("--yes");
@@ -1841,13 +2093,47 @@ ${error}`);
1841
2093
  }
1842
2094
  /**
1843
2095
  * @private
1844
- * Restart a machine by stopping then starting it
1845
- * @throws An error if the machine cannot be restarted
2096
+ * Restart a machine by stopping then starting it, waiting on the state Fly
2097
+ * reports rather than a fixed delay: the start is only issued once the
2098
+ * machine is stopped (or suspended), and the restart is done once it is
2099
+ * started again.
2100
+ * @throws An error saying the machine was left stopped when anything after
2101
+ * the stop fails
1846
2102
  */
1847
2103
  async restartMachine(app, machineId) {
1848
2104
  await this.stopMachine(app, machineId);
1849
- await new Promise((resolve) => setTimeout(resolve, 2e3));
1850
- await this.startMachine(app, machineId);
2105
+ try {
2106
+ await this.waitForMachineState(app, machineId, ["stopped", "suspended"]);
2107
+ await this.startMachine(app, machineId);
2108
+ await this.waitForMachineState(app, machineId, ["started"]);
2109
+ } catch (error) {
2110
+ const reason = error instanceof Error ? error.message : String(error);
2111
+ throw new Error(
2112
+ `Machine '${machineId}' in app '${app}' was stopped but did not start again: ${reason}`,
2113
+ { cause: error }
2114
+ );
2115
+ }
2116
+ }
2117
+ /**
2118
+ * @private
2119
+ * Poll the app status until the machine reports one of the given states
2120
+ * @throws An error if the machine does not reach a state in time
2121
+ */
2122
+ async waitForMachineState(app, machineId, states) {
2123
+ const deadline = Date.now() + MACHINE_STATE_TIMEOUT_MS;
2124
+ while (Date.now() < deadline) {
2125
+ const status = await this.fetchAppLookup("nullOnError", { app });
2126
+ const machine = status?.machines.find(({ id }) => id === machineId);
2127
+ if (machine && states.includes(machine.state)) {
2128
+ return;
2129
+ }
2130
+ await new Promise(
2131
+ (resolve) => setTimeout(resolve, MACHINE_STATE_INTERVAL_MS)
2132
+ );
2133
+ }
2134
+ throw new Error(
2135
+ `Machine '${machineId}' in app '${app}' did not reach ${states.join("/")} in time`
2136
+ );
1851
2137
  }
1852
2138
  /**
1853
2139
  * @private
@@ -1943,7 +2229,28 @@ ${error}`);
1943
2229
  if (onError === "throwOnError") {
1944
2230
  throw error;
1945
2231
  }
1946
- if (error instanceof import_zod36.ZodError) {
2232
+ if (error instanceof import_zod40.ZodError) {
2233
+ this.logger.info(`Failed to parse response:
2234
+ ${error.message}`);
2235
+ this.logger.info(`Raw response:
2236
+ ${JSON.stringify(response, null, 2)}`);
2237
+ }
2238
+ return null;
2239
+ }
2240
+ }
2241
+ async fetchAppLookup(onError, options) {
2242
+ const args = ["status"];
2243
+ args.push(...this.getAppOrConfigArgs(options));
2244
+ args.push("--json");
2245
+ let response = null;
2246
+ try {
2247
+ response = await this.execFly(args);
2248
+ return statusLookupSchema.parse(response);
2249
+ } catch (error) {
2250
+ if (onError === "throwOnError") {
2251
+ throw error;
2252
+ }
2253
+ if (error instanceof import_zod40.ZodError) {
1947
2254
  this.logger.info(`Failed to parse response:
1948
2255
  ${error.message}`);
1949
2256
  this.logger.info(`Raw response:
@@ -2054,8 +2361,7 @@ ${JSON.stringify(response, null, 2)}`);
2054
2361
  * @throws An error if Fly CLI is not installed or not authenticated
2055
2362
  */
2056
2363
  async ensureInitialized() {
2057
- if (this.initialized)
2058
- return;
2364
+ if (this.initialized) return;
2059
2365
  try {
2060
2366
  if (!await this.isInstalled()) {
2061
2367
  throw new Error("Fly CLI must be installed to use this library");
@@ -2080,33 +2386,32 @@ ${JSON.stringify(response, null, 2)}`);
2080
2386
  }
2081
2387
  const flyCmd = "flyctl";
2082
2388
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
2389
+ const { retry = false, ...execOpts } = options ?? {};
2083
2390
  let output = "";
2084
- try {
2085
- this.traceCLI("CALL", toLogCmd);
2086
- if (options?.prompt) {
2087
- output = await spawnPty(flyCmd, args, { prompt: options.prompt });
2088
- this.traceCLI("RESULT", output);
2089
- } else {
2090
- const { streamStrategy = "stdout", ...spawnOpts } = options ?? {};
2091
- const result = await spawn(flyCmd, args, {
2092
- ...spawnOpts,
2093
- streamToConsole: this.logger.streamToConsole
2094
- });
2095
- const stdout = result.stdout.trim();
2096
- const stderr = result.stderr.trim();
2097
- this.traceCLI("RESULT", `${stdout}${stderr ? `
2098
- ${stderr}` : ""}`);
2099
- output = streamStrategy === "combined" ? `${stdout}
2100
- ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
2101
- }
2102
- } catch (error) {
2103
- const errorMsg = error.message;
2104
- this.traceCLI("RESULT", errorMsg);
2105
- if (onError === "throwOnError") {
2106
- throw new Error(`Command failed: ${toLogCmd}
2107
- ${errorMsg}`);
2391
+ for (let attempt = 1; ; attempt++) {
2392
+ try {
2393
+ output = await this.spawnFly(flyCmd, args, toLogCmd, execOpts);
2394
+ break;
2395
+ } catch (error) {
2396
+ const errorMsg = error.message;
2397
+ this.traceCLI("RESULT", errorMsg);
2398
+ const cause = retry ? this.transientCause(error) : null;
2399
+ const delay = TRANSIENT_RETRY_DELAYS_MS[attempt - 1];
2400
+ if (cause && delay !== void 0) {
2401
+ this.logger.info(
2402
+ `Transient Fly error (${cause}), retrying in ${delay / 1e3}s (attempt ${attempt + 1} of ${TRANSIENT_RETRY_DELAYS_MS.length + 1}): ${toLogCmd}`
2403
+ );
2404
+ await new Promise((resolve) => setTimeout(resolve, delay));
2405
+ continue;
2406
+ }
2407
+ if (onError === "throwOnError") {
2408
+ throw new Error(`Command failed: ${toLogCmd}
2409
+ ${errorMsg}`, {
2410
+ cause: error
2411
+ });
2412
+ }
2413
+ return null;
2108
2414
  }
2109
- return null;
2110
2415
  }
2111
2416
  try {
2112
2417
  return JSON.parse(output);
@@ -2120,6 +2425,55 @@ ${errorMsg}`);
2120
2425
  }
2121
2426
  return void 0;
2122
2427
  }
2428
+ /**
2429
+ * @private
2430
+ * Run one fly command and assemble its output
2431
+ *
2432
+ * @returns The output selected by `streamStrategy`
2433
+ * @throws An error if the command fails
2434
+ */
2435
+ async spawnFly(flyCmd, args, toLogCmd, options) {
2436
+ this.traceCLI("CALL", toLogCmd);
2437
+ if (options.prompt) {
2438
+ const output = await spawnPty(flyCmd, args, { prompt: options.prompt });
2439
+ this.traceCLI("RESULT", output);
2440
+ return output;
2441
+ }
2442
+ const { streamStrategy = "stdout", ...spawnOpts } = options;
2443
+ const result = await spawn(flyCmd, args, {
2444
+ ...spawnOpts,
2445
+ streamToConsole: this.logger.streamToConsole
2446
+ });
2447
+ const stdout = result.stdout.trim();
2448
+ const stderr = result.stderr.trim();
2449
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
2450
+ ${stderr}` : ""}`);
2451
+ return streamStrategy === "combined" ? `${stdout}
2452
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
2453
+ }
2454
+ /**
2455
+ * @private
2456
+ * Name the transient Fly error behind a failed command, if it was one.
2457
+ *
2458
+ * Only the error flyctl ended with counts: from its last `Error` line to
2459
+ * the end of stderr, or the last few lines when there is none. A deploy
2460
+ * streams the app's own output and errors flyctl recovered from, and
2461
+ * matching those would repeat a deploy that failed for a real reason.
2462
+ *
2463
+ * @returns The cause, or `null` when the failure is not a known transient one
2464
+ */
2465
+ transientCause(error) {
2466
+ let text;
2467
+ if (error instanceof SpawnError) {
2468
+ const lines = error.stderr.split(/\r?\n/).filter((line) => line.trim());
2469
+ const errorLines = lines.map((line) => /^\s*Error\b/.test(line));
2470
+ const last = errorLines.lastIndexOf(true);
2471
+ text = lines.slice(last >= 0 ? last : -3).join("\n");
2472
+ } else {
2473
+ text = String(error?.message ?? error);
2474
+ }
2475
+ return TRANSIENT_FLY_ERRORS.find(({ pattern }) => pattern.test(text))?.cause ?? null;
2476
+ }
2123
2477
  /**
2124
2478
  * @private
2125
2479
  * Get the arguments for `AppOrConfig` options
@@ -2268,6 +2622,8 @@ ${errorMsg}`);
2268
2622
  };
2269
2623
  // Annotate the CommonJS export names for ESM import in node:
2270
2624
  0 && (module.exports = {
2625
+ AppIpAddressSchema,
2626
+ AppIpAddressesApiResponseSchema,
2271
2627
  CertificateApiResponseSchema,
2272
2628
  CertificateListApiResponseSchema,
2273
2629
  DnsInstructionsSchema,