@cdwr/fly-node 0.3.0 → 0.3.2

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,54 +28,543 @@ 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, {
33
- Fly: () => Fly
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CertificateApiResponseSchema: () => CertificateApiResponseSchema,
34
+ CertificateListApiResponseSchema: () => CertificateListApiResponseSchema,
35
+ DnsInstructionsSchema: () => DnsInstructionsSchema,
36
+ Fly: () => Fly,
37
+ FlyApi: () => FlyApi,
38
+ FlyApiError: () => FlyApiError,
39
+ HostnameCheckApiResponseSchema: () => HostnameCheckApiResponseSchema,
40
+ MachineApiResponseSchema: () => MachineApiResponseSchema,
41
+ MachineListApiResponseSchema: () => MachineListApiResponseSchema
34
42
  });
35
- module.exports = __toCommonJS(src_exports);
43
+ module.exports = __toCommonJS(index_exports);
44
+
45
+ // packages/fly-node/src/lib/schemas/certificate.schema.ts
46
+ var import_zod = require("zod");
47
+ var CertificateApiResponseSchema = import_zod.z.object({
48
+ hostname: import_zod.z.string(),
49
+ /** 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(),
52
+ /** 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(),
55
+ /** 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(),
64
+ /** Hostname the validation record must be created on */
65
+ dnsValidationHostname: import_zod.z.string().nullish(),
66
+ /** Value that record must contain */
67
+ dnsValidationTarget: import_zod.z.string().nullish(),
68
+ /** Fly's own prose describing the records to create */
69
+ dnsValidationInstructions: import_zod.z.string().nullish(),
70
+ /** Fly's summary of where issuance has got to */
71
+ clientStatus: import_zod.z.string().nullish(),
72
+ /**
73
+ * Set when Let's Encrypt has rate-limited further attempts for this domain.
74
+ *
75
+ * Worth surfacing rather than swallowing: it is the one failure a customer
76
+ * cannot fix by correcting DNS, and retrying only makes it worse.
77
+ */
78
+ rateLimitedUntil: import_zod.z.string().nullish(),
79
+ source: import_zod.z.string().nullish(),
80
+ /**
81
+ * Fly's own prose for a failed issuance attempt — what the dashboard shows,
82
+ * unlike `HostnameCheck.errors`, which is SCREAMING_SNAKE_CASE codes
83
+ */
84
+ validationErrors: import_zod.z.array(
85
+ import_zod.z.object({
86
+ message: import_zod.z.string(),
87
+ timestamp: import_zod.z.string()
88
+ })
89
+ ).nullish(),
90
+ /**
91
+ * The certificates actually issued for this hostname, once any have been.
92
+ *
93
+ * A connection rather than a list because that is how Fly models it. Two
94
+ * nodes is the normal count — one RSA and one ECDSA — sharing an expiry,
95
+ * which is why a caller usually wants the expiry rather than the rows.
96
+ */
97
+ issued: import_zod.z.object({
98
+ nodes: import_zod.z.array(
99
+ import_zod.z.object({
100
+ id: import_zod.z.string().nullish(),
101
+ /** 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()
105
+ })
106
+ ).nullish()
107
+ }).nullish()
108
+ });
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()
122
+ });
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()
128
+ });
129
+ var CertificateListApiResponseSchema = import_zod.z.array(
130
+ CertificateApiResponseSchema
131
+ );
132
+
133
+ // 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(),
138
+ /** `started`, `stopped`, `suspended`, … — Fly owns this vocabulary */
139
+ state: import_zod2.z.string().nullish(),
140
+ region: import_zod2.z.string().nullish()
141
+ });
142
+ var MachineListApiResponseSchema = import_zod2.z.array(MachineApiResponseSchema);
143
+
144
+ // packages/fly-node/src/lib/fly-api.class.ts
145
+ var FLY_API_URL = "https://api.fly.io/graphql";
146
+ var FLY_MACHINES_URL = "https://api.machines.dev/v1";
147
+ var FlyApiError = class extends Error {
148
+ errors;
149
+ constructor(message, errors) {
150
+ super(message);
151
+ this.name = "FlyApiError";
152
+ this.errors = errors;
153
+ }
154
+ /** Whether every error is Fly saying the thing simply does not exist */
155
+ get isNotFound() {
156
+ return this.errors.length > 0 && this.errors.every((error) => error.extensions?.code === "NOT_FOUND");
157
+ }
158
+ /**
159
+ * Whether every error is Fly refusing a hostname that already has a
160
+ * certificate on the app.
161
+ *
162
+ * No `extensions.code` comes with this one — Fly's own dashboard and
163
+ * `flyctl` hit the same message, and both work around it the same way this
164
+ * class does, by re-reading rather than retrying the mutation.
165
+ */
166
+ get isAlreadyExists() {
167
+ return this.errors.length > 0 && this.errors.every((error) => /already exists/i.test(error.message));
168
+ }
169
+ };
170
+ var FlyApi = class {
171
+ token;
172
+ apiUrl;
173
+ machinesUrl;
174
+ log;
175
+ constructor(config) {
176
+ if (!config.token) {
177
+ throw new Error("[fly-api] A Fly API token is required");
178
+ }
179
+ this.token = config.token;
180
+ this.apiUrl = config.apiUrl ?? FLY_API_URL;
181
+ this.machinesUrl = config.machinesUrl ?? FLY_MACHINES_URL;
182
+ this.log = config.log ?? (() => void 0);
183
+ }
184
+ /**
185
+ * Manage certificates for an app.
186
+ *
187
+ * Every method takes the app name explicitly: this client is used by a
188
+ * process acting on *other* apps — the cms managing a tenant's web app — so
189
+ * there is no ambient "current app" to default to.
190
+ */
191
+ certs = {
192
+ /**
193
+ * Request a certificate for a hostname.
194
+ *
195
+ * Safe to call when one already exists: Fly's own mutation is not
196
+ * idempotent — a hostname it already has a certificate for on this app is
197
+ * a fault, not a no-op, so this re-reads the existing certificate itself
198
+ * rather than surfacing that as an error a caller has to know to expect.
199
+ *
200
+ * Requesting before DNS is in place is normal and expected — the
201
+ * certificate stays pending until the records resolve, and the returned
202
+ * validation fields are what you show the customer meanwhile.
203
+ *
204
+ * @param app - Fly app name the domain should serve from
205
+ * @param hostname - Domain without a scheme, e.g. `tours.example.com`
206
+ * @returns The certificate, plus what Fly resolves for that hostname now
207
+ */
208
+ add: async (app, hostname) => {
209
+ try {
210
+ const data = await this.request(
211
+ `mutation AddCertificate($appId: ID!, $hostname: String!) {
212
+ addCertificate(appId: $appId, hostname: $hostname) {
213
+ certificate { ${CERTIFICATE_FIELDS} }
214
+ check { ${HOSTNAME_CHECK_FIELDS} }
215
+ }
216
+ }`,
217
+ { appId: app, hostname }
218
+ );
219
+ return {
220
+ certificate: CertificateApiResponseSchema.parse(
221
+ data.addCertificate.certificate
222
+ ),
223
+ // Live resolution, and it comes back with the mutation for free —
224
+ // the customer has usually just edited DNS and wants to know if it
225
+ // took
226
+ check: data.addCertificate.check ? HostnameCheckApiResponseSchema.parse(data.addCertificate.check) : null
227
+ };
228
+ } catch (error) {
229
+ if (error instanceof FlyApiError && error.isAlreadyExists) {
230
+ const certificate = await this.certs.get(app, hostname);
231
+ if (certificate) {
232
+ return { certificate, check: null };
233
+ }
234
+ }
235
+ throw error;
236
+ }
237
+ },
238
+ /**
239
+ * Read one certificate, or `null` when the app has none for that hostname.
240
+ *
241
+ * This is the call behind a "check" button: it re-reads issuance state from
242
+ * Fly rather than trusting anything stored locally.
243
+ *
244
+ * Fly reports an absent certificate as a `NOT_FOUND` *error* rather than a
245
+ * null field, so that case is translated here — asking about a domain
246
+ * nobody has added yet is an ordinary question with an ordinary answer.
247
+ */
248
+ get: async (app, hostname) => {
249
+ let data;
250
+ try {
251
+ data = await this.request(
252
+ `query AppCertificate($appName: String!, $hostname: String!) {
253
+ app(name: $appName) {
254
+ certificate(hostname: $hostname) { ${CERTIFICATE_FIELDS} }
255
+ }
256
+ }`,
257
+ { appName: app, hostname }
258
+ );
259
+ } catch (error) {
260
+ if (error instanceof FlyApiError && error.isNotFound) {
261
+ return null;
262
+ }
263
+ throw error;
264
+ }
265
+ const certificate = data.app?.certificate;
266
+ return certificate ? CertificateApiResponseSchema.parse(certificate) : null;
267
+ },
268
+ /**
269
+ * What Fly resolves for a hostname right now, and what it objects to.
270
+ *
271
+ * A mutation on Fly's side despite reading rather than writing anything —
272
+ * `AppCertificate.check` is a plain boolean flag, and `HostnameCheck` is
273
+ * only ever returned by `addCertificate` and this, `checkCertificate`.
274
+ * Separate from `get` rather than folded into it: triggering a live dns
275
+ * resolution on every read would cost a caller that only wants issuance
276
+ * state. Pair the two when a person has just edited their records and
277
+ * wants to know whether it took.
278
+ *
279
+ * `errors` is the useful half — it is what Fly's own dashboard prints as
280
+ * "validation issues", already phrased for whoever owns the domain.
281
+ *
282
+ * @returns `null` when the app has no certificate for that hostname
283
+ */
284
+ check: async (app, hostname) => {
285
+ let data;
286
+ try {
287
+ data = await this.request(
288
+ `mutation CheckCertificate($appId: ID!, $hostname: String!) {
289
+ checkCertificate(input: { appId: $appId, hostname: $hostname }) {
290
+ check { ${HOSTNAME_CHECK_FIELDS} }
291
+ }
292
+ }`,
293
+ { appId: app, hostname }
294
+ );
295
+ } catch (error) {
296
+ if (error instanceof FlyApiError && error.isNotFound) {
297
+ return null;
298
+ }
299
+ throw error;
300
+ }
301
+ const check = data.checkCertificate?.check;
302
+ return check ? HostnameCheckApiResponseSchema.parse(check) : null;
303
+ },
304
+ /** Every certificate on an app */
305
+ list: async (app) => {
306
+ const data = await this.request(
307
+ `query AppCertificates($appName: String!) {
308
+ app(name: $appName) {
309
+ certificates { nodes { ${CERTIFICATE_FIELDS} } }
310
+ }
311
+ }`,
312
+ { appName: app }
313
+ );
314
+ return CertificateListApiResponseSchema.parse(
315
+ data.app?.certificates?.nodes ?? []
316
+ );
317
+ },
318
+ /**
319
+ * Remove a certificate.
320
+ *
321
+ * The hostname keeps resolving until its DNS is changed — this only stops
322
+ * Fly serving TLS for it.
323
+ */
324
+ remove: async (app, hostname) => {
325
+ await this.request(
326
+ `mutation DeleteCertificate($appId: ID!, $hostname: String!) {
327
+ deleteCertificate(appId: $appId, hostname: $hostname) {
328
+ certificate { hostname }
329
+ }
330
+ }`,
331
+ { appId: app, hostname }
332
+ );
333
+ }
334
+ };
335
+ /**
336
+ * Operate an app's machines.
337
+ *
338
+ * Over Fly's REST Machines API rather than GraphQL, which has no current
339
+ * equivalent — the GraphQL mutations date from the Nomad platform and no
340
+ * longer apply.
341
+ */
342
+ machines = {
343
+ /** Every machine on an app */
344
+ list: async (app) => {
345
+ const data = await this.machinesRequest(
346
+ "GET",
347
+ `/apps/${encodeURIComponent(app)}/machines`
348
+ );
349
+ return MachineListApiResponseSchema.parse(data ?? []);
350
+ },
351
+ /**
352
+ * Restart an app's machines.
353
+ *
354
+ * One at a time on purpose: a settings change that only takes effect at
355
+ * boot should not cost the app its availability to apply. Restarting them
356
+ * together would drop every machine at once, while sequentially leaves the
357
+ * others serving. The trade is that a large app takes longer.
358
+ *
359
+ * A machine that fails to restart stops the run rather than being skipped —
360
+ * a half-restarted app is running two configurations at the same time, and
361
+ * silently returning "some of them" invites calling that done.
362
+ *
363
+ * @param app - Fly app name
364
+ * @param machineId - Restart only this machine, instead of all of them
365
+ * @returns Ids of the machines that were restarted, in the order they were
366
+ */
367
+ restart: async (app, machineId) => {
368
+ const ids = machineId ? [machineId] : (await this.machines.list(app)).map((machine) => machine.id);
369
+ const restarted = [];
370
+ for (const id of ids) {
371
+ await this.machinesRequest(
372
+ "POST",
373
+ `/apps/${encodeURIComponent(app)}/machines/${encodeURIComponent(id)}/restart`
374
+ );
375
+ restarted.push(id);
376
+ }
377
+ return restarted;
378
+ }
379
+ };
380
+ /**
381
+ * The DNS records a customer must create for a certificate to validate.
382
+ *
383
+ * Pulled out of the certificate rather than fetched, so a caller that
384
+ * already has one does not pay for a second round trip.
385
+ */
386
+ static dnsInstructions(certificate) {
387
+ return {
388
+ hostname: certificate.dnsValidationHostname,
389
+ target: certificate.dnsValidationTarget,
390
+ instructions: certificate.dnsValidationInstructions,
391
+ isApex: certificate.isApex
392
+ };
393
+ }
394
+ /**
395
+ * @private
396
+ * One GraphQL round trip.
397
+ *
398
+ * Fly answers a failed query with HTTP 200 and an `errors` array, so a
399
+ * response is only successful when both are checked — trusting the status
400
+ * alone would turn "permission denied" into a parse error further down.
401
+ */
402
+ async request(query, variables) {
403
+ const operation = /(?:query|mutation)\s+(\w+)/.exec(query)?.[1] ?? "query";
404
+ this.log(`[fly-api] ${operation} ${JSON.stringify(variables)}`);
405
+ let response;
406
+ try {
407
+ response = await fetch(this.apiUrl, {
408
+ method: "POST",
409
+ headers: {
410
+ Authorization: `Bearer ${this.token}`,
411
+ "Content-Type": "application/json"
412
+ },
413
+ body: JSON.stringify({ query, variables })
414
+ });
415
+ } catch (error) {
416
+ throw new Error(`[fly-api] ${operation} could not reach Fly: ${error}`);
417
+ }
418
+ if (!response.ok) {
419
+ throw new Error(
420
+ `[fly-api] ${operation} failed: ${response.status} ${response.statusText}`
421
+ );
422
+ }
423
+ const body = await response.json();
424
+ if (body.errors?.length) {
425
+ throw new FlyApiError(
426
+ `[fly-api] ${operation} failed: ${body.errors.map((error) => error.message).join("; ")}`,
427
+ body.errors
428
+ );
429
+ }
430
+ if (!body.data) {
431
+ throw new Error(`[fly-api] ${operation} returned no data`);
432
+ }
433
+ return body.data;
434
+ }
435
+ /**
436
+ * @private
437
+ * One call to the Machines REST API.
438
+ *
439
+ * Unlike GraphQL this one reports failure through the status code, and puts
440
+ * its reason in an `error` field. Worth reading rather than reporting the
441
+ * status alone: "machine not found" and "unauthorized" are different problems
442
+ * with different fixes.
443
+ */
444
+ async machinesRequest(method, path) {
445
+ this.log(`[fly-api] ${method} ${path}`);
446
+ let response;
447
+ try {
448
+ response = await fetch(`${this.machinesUrl}${path}`, {
449
+ method,
450
+ headers: {
451
+ Authorization: `Bearer ${this.token}`,
452
+ "Content-Type": "application/json"
453
+ }
454
+ });
455
+ } catch (error) {
456
+ throw new Error(
457
+ `[fly-api] ${method} ${path} could not reach Fly: ${error}`
458
+ );
459
+ }
460
+ const body = await response.json().catch(() => null);
461
+ if (!response.ok) {
462
+ throw new Error(
463
+ `[fly-api] ${method} ${path} failed: ${response.status} ${body?.error ?? response.statusText}`
464
+ );
465
+ }
466
+ return body;
467
+ }
468
+ };
469
+ var CERTIFICATE_FIELDS = `
470
+ id
471
+ hostname
472
+ isConfigured
473
+ isApex
474
+ isWildcard
475
+ isAcmeDnsConfigured
476
+ isAcmeAlpnConfigured
477
+ isAcmeHttpConfigured
478
+ certificateAuthority
479
+ certificateRequestedAt
480
+ createdAt
481
+ domain
482
+ dnsProvider
483
+ dnsValidationHostname
484
+ dnsValidationTarget
485
+ dnsValidationInstructions
486
+ clientStatus
487
+ rateLimitedUntil
488
+ source
489
+ validationErrors {
490
+ message
491
+ timestamp
492
+ }
493
+ # Fly issues one certificate per key type (RSA and ECDSA), so a hostname
494
+ # with a single expiry date still comes back as two rows
495
+ issued(first: 10) {
496
+ nodes {
497
+ id
498
+ type
499
+ hostname
500
+ expiresAt
501
+ }
502
+ }
503
+ `;
504
+ var HOSTNAME_CHECK_FIELDS = `
505
+ aRecords
506
+ aaaaRecords
507
+ cnameRecords
508
+ caaRecords
509
+ soa
510
+ dnsProvider
511
+ dnsVerificationRecord
512
+ dnsConfigured
513
+ acmeDnsConfigured
514
+ resolvedAddresses
515
+ isProxied
516
+ errors
517
+ `;
36
518
 
37
519
  // packages/fly-node/src/lib/fly.class.ts
38
520
  var import_fs = require("fs");
39
521
  var import_path = require("path");
40
522
  var import_process = require("process");
41
523
 
42
- // packages/core/src/lib/utils/docker-build.ts
524
+ // libs/shared/util/misc/src/lib/docker-build.ts
43
525
  var import_docker_cli_js = require("docker-cli-js");
44
526
  var import_tiny_invariant = __toESM(require("tiny-invariant"), 1);
45
527
 
46
- // packages/core/src/lib/utils/log-utils.ts
528
+ // libs/shared/util/misc/src/lib/log-utils.ts
47
529
  var import_chalk = __toESM(require("chalk"), 1);
48
530
 
49
- // packages/core/src/lib/utils/promisified-exec.ts
531
+ // libs/shared/util/misc/src/lib/promisified-exec.ts
50
532
  var import_child_process = require("child_process");
51
533
  var import_util = require("util");
52
534
  var exec = (0, import_util.promisify)(import_child_process.exec);
53
535
  var execFile = (0, import_util.promisify)(import_child_process.execFile);
54
536
 
55
- // packages/core/src/lib/utils/kill-port.ts
537
+ // libs/shared/util/misc/src/lib/kill-port.ts
56
538
  var import_kill_port = __toESM(require("kill-port"), 1);
57
539
  var import_tcp_port_used = require("tcp-port-used");
58
540
 
59
- // packages/core/src/lib/utils/kill-process-tree.ts
541
+ // libs/shared/util/misc/src/lib/kill-process-tree.ts
60
542
  var import_util2 = require("util");
61
543
  var import_tree_kill = __toESM(require("tree-kill"), 1);
62
544
  var killProcessTree = (0, import_util2.promisify)(import_tree_kill.default);
63
545
 
64
- // packages/core/src/lib/utils/promisified-spawn.ts
546
+ // libs/shared/util/misc/src/lib/promisified-spawn.ts
65
547
  var import_child_process2 = require("child_process");
66
548
  function spawn(command, args, options) {
67
549
  return new Promise((resolve, reject) => {
550
+ const { streamToConsole, ...spawnOptions } = options || {};
68
551
  const process2 = (0, import_child_process2.spawn)(command, args, {
69
- ...options,
552
+ ...spawnOptions,
70
553
  stdio: "pipe"
71
554
  });
72
555
  const stdoutChunks = [];
73
556
  const stderrChunks = [];
74
557
  process2.stdout.on("data", (data) => {
75
558
  stdoutChunks.push(Buffer.from(data));
559
+ if (streamToConsole) {
560
+ global.process.stdout.write(data);
561
+ }
76
562
  });
77
563
  process2.stderr.on("data", (data) => {
78
564
  stderrChunks.push(Buffer.from(data));
565
+ if (streamToConsole) {
566
+ global.process.stderr.write(data);
567
+ }
79
568
  });
80
569
  process2.on("close", (code) => {
81
570
  const stdout = Buffer.concat(stdoutChunks).toString();
@@ -91,10 +580,7 @@ Error: ${stderr}`));
91
580
  });
92
581
  }
93
582
 
94
- // packages/core/src/lib/utils/run-command.ts
95
- var import_testing = require("@nx/plugin/testing");
96
-
97
- // packages/core/src/lib/utils/spawn-pty.ts
583
+ // libs/shared/util/misc/src/lib/spawn-pty.ts
98
584
  var import_node_pty_prebuilt_multiarch = require("@homebridge/node-pty-prebuilt-multiarch");
99
585
  function spawnPty(command, args, options) {
100
586
  return new Promise((resolve, reject) => {
@@ -128,21 +614,24 @@ Output: ${output}`)
128
614
  });
129
615
  }
130
616
 
131
- // packages/core/src/lib/utils/whoami.ts
132
- var import_npm_whoami = __toESM(require("npm-whoami"), 1);
133
-
134
617
  // packages/fly-node/src/lib/fly.class.ts
135
- var import_zod30 = require("zod");
618
+ var import_zod38 = require("zod");
136
619
 
137
- // packages/core/src/lib/zod/json.schema.ts
138
- var import_zod = require("zod");
139
- var LiteralSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean(), import_zod.z.null()]);
140
- var JsonSchema = import_zod.z.lazy(
141
- () => import_zod.z.union([LiteralSchema, import_zod.z.array(JsonSchema), import_zod.z.record(JsonSchema)])
620
+ // libs/shared/util/zod/src/lib/coerce-boolean.ts
621
+ var import_zod3 = require("zod");
622
+
623
+ // libs/shared/util/zod/src/lib/create-lowercase-schema.ts
624
+ var import_zod4 = require("zod");
625
+
626
+ // 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)])
142
631
  );
143
632
 
144
- // packages/core/src/lib/zod/with-camel-case.preprocess.ts
145
- var import_zod2 = require("zod");
633
+ // libs/shared/util/zod/src/lib/with-camel-case.preprocess.ts
634
+ var import_zod6 = require("zod");
146
635
  var toCamelCase = (str, specialCases = {}) => {
147
636
  if (specialCases[str]) {
148
637
  return specialCases[str];
@@ -168,28 +657,31 @@ var transformKeys = (options) => {
168
657
  );
169
658
  }
170
659
  if (data && typeof data === "object" && data !== null) {
171
- return Object.entries(data).reduce((acc, [key, value]) => {
172
- const shouldPreserveValue = preserve.some(
173
- (path) => [...currentPath, key].join(".").match(new RegExp(`^${path}.`))
174
- );
175
- const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
176
- const newPath = [...currentPath, newKey];
177
- return {
178
- ...acc,
179
- [newKey]: transformKeys({
180
- currentPath: newPath,
181
- data: value,
182
- preserve,
183
- specialCases
184
- })
185
- };
186
- }, {});
660
+ return Object.fromEntries(
661
+ Object.entries(data).map(([key, value]) => {
662
+ const fullPath = [...currentPath, key].join(".");
663
+ const shouldPreserveValue = preserve.some(
664
+ (path) => fullPath.startsWith(`${path}.`)
665
+ );
666
+ const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
667
+ const newPath = [...currentPath, newKey];
668
+ return [
669
+ newKey,
670
+ transformKeys({
671
+ currentPath: newPath,
672
+ data: value,
673
+ preserve,
674
+ specialCases
675
+ })
676
+ ];
677
+ })
678
+ );
187
679
  }
188
680
  return data;
189
681
  };
190
682
  var withCamelCase = (schema, options = {}) => {
191
683
  const { preserve = [], specialCases = {} } = options;
192
- return import_zod2.z.preprocess(
684
+ return import_zod6.z.preprocess(
193
685
  (data) => transformKeys({
194
686
  currentPath: [],
195
687
  data,
@@ -200,83 +692,93 @@ var withCamelCase = (schema, options = {}) => {
200
692
  );
201
693
  };
202
694
 
203
- // packages/core/src/lib/zod/with-replace-all.preprocess.ts
204
- var import_zod3 = require("zod");
695
+ // libs/shared/util/zod/src/lib/with-env-vars.preprocess.ts
696
+ var import_zod7 = require("zod");
697
+
698
+ // libs/shared/util/zod/src/lib/with-replace-all.preprocess.ts
699
+ var import_zod8 = require("zod");
205
700
 
206
701
  // packages/fly-node/src/lib/schemas/apps-create.schema.ts
207
- var import_zod5 = require("zod");
702
+ var import_zod10 = require("zod");
208
703
  var AppsCreateTransformedResponseSchema = withCamelCase(
209
- import_zod5.z.object({
210
- id: import_zod5.z.string(),
211
- name: import_zod5.z.string()
704
+ import_zod10.z.object({
705
+ id: import_zod10.z.string(),
706
+ name: import_zod10.z.string()
212
707
  })
213
708
  );
214
709
 
215
710
  // packages/fly-node/src/lib/schemas/apps-list.schema.ts
216
- var import_zod7 = require("zod");
217
- var AppsListTransformedResponseSchema = import_zod7.z.array(
711
+ var import_zod12 = require("zod");
712
+ var AppsListTransformedResponseSchema = import_zod12.z.array(
218
713
  withCamelCase(
219
- import_zod7.z.object({
220
- id: import_zod7.z.string(),
221
- name: import_zod7.z.string(),
222
- status: import_zod7.z.string(),
223
- deployed: import_zod7.z.boolean(),
224
- hostname: import_zod7.z.string(),
225
- organization: import_zod7.z.object({
226
- name: import_zod7.z.string(),
227
- slug: import_zod7.z.string()
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()
228
723
  }),
229
- currentRelease: import_zod7.z.nullable(
230
- import_zod7.z.object({
231
- status: import_zod7.z.string(),
232
- createdAt: import_zod7.z.string().datetime()
724
+ currentRelease: import_zod12.z.nullable(
725
+ import_zod12.z.object({
726
+ status: import_zod12.z.string(),
727
+ createdAt: import_zod12.z.string().datetime()
233
728
  })
234
729
  )
235
730
  })
236
731
  )
237
732
  );
238
733
 
734
+ // 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()
739
+ });
740
+
239
741
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
240
- var import_zod11 = require("zod");
742
+ var import_zod17 = require("zod");
241
743
 
242
744
  // packages/fly-node/src/lib/schemas/certs-list.schema.ts
243
- var import_zod9 = require("zod");
244
- var CertsListFlyResponseElementSchema = import_zod9.z.object({
245
- createdAt: import_zod9.z.string().datetime(),
246
- hostname: import_zod9.z.string(),
247
- clientStatus: import_zod9.z.string()
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()
248
750
  });
249
- var CertsListTransformedResponseSchema = import_zod9.z.array(
751
+ var CertsListTransformedResponseSchema = import_zod15.z.array(
250
752
  withCamelCase(CertsListFlyResponseElementSchema)
251
753
  );
252
754
 
253
755
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
254
- var CertsListWithAppTransformedResponseSchema = import_zod11.z.array(
756
+ var CertsListWithAppTransformedResponseSchema = import_zod17.z.array(
255
757
  withCamelCase(
256
758
  CertsListFlyResponseElementSchema.extend({
257
- app: import_zod11.z.string()
759
+ app: import_zod17.z.string()
258
760
  })
259
761
  )
260
762
  );
261
763
 
262
764
  // packages/fly-node/src/lib/schemas/config-show.schema.ts
263
- var import_zod13 = require("zod");
765
+ var import_zod19 = require("zod");
264
766
  var ConfigShowResponseSchema = withCamelCase(
265
- import_zod13.z.object({
266
- app: import_zod13.z.string(),
267
- primaryRegion: import_zod13.z.string().optional(),
268
- build: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any()).optional().or(
269
- import_zod13.z.object({
270
- args: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.string()).optional(),
271
- dockerfile: import_zod13.z.string().optional(),
272
- image: import_zod13.z.string().optional()
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()
273
775
  })
274
776
  ),
275
- deploy: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any()).optional().or(import_zod13.z.object({ strategy: import_zod13.z.string().optional() })),
276
- env: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.string()).optional(),
277
- httpService: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any()).optional(),
278
- mounts: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any()).optional(),
279
- services: import_zod13.z.array(import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any())).optional()
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()
280
782
  }),
281
783
  {
282
784
  preserve: ["build.args", "env"]
@@ -284,119 +786,149 @@ var ConfigShowResponseSchema = withCamelCase(
284
786
  );
285
787
 
286
788
  // packages/fly-node/src/lib/schemas/deploy.schema.ts
287
- var import_zod14 = require("zod");
288
- var DeployResponseSchema = import_zod14.z.object({
289
- app: import_zod14.z.string(),
290
- hostname: import_zod14.z.string(),
291
- url: import_zod14.z.string().url()
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()
292
794
  });
293
795
 
294
796
  // packages/fly-node/src/lib/schemas/helper-schemas.ts
295
- var import_zod15 = require("zod");
296
- var AllowEmptyUrlSchema = import_zod15.z.string().url().or(import_zod15.z.literal(""));
297
- var NameSchema = import_zod15.z.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
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-]+$/);
800
+
801
+ // packages/fly-node/src/lib/schemas/ips-list.schema.ts
802
+ var import_zod23 = require("zod");
803
+ var IpTypeSchema = import_zod23.z.enum(["v4", "v6", "shared_v4", "private_v6"]).or(import_zod23.z.string());
804
+ var IpsListFlyResponseElementSchema = import_zod23.z.object({
805
+ id: import_zod23.z.string(),
806
+ address: import_zod23.z.string(),
807
+ type: IpTypeSchema,
808
+ region: import_zod23.z.string(),
809
+ createdAt: import_zod23.z.string()
810
+ });
811
+ var IpsListTransformedResponseSchema = import_zod23.z.array(
812
+ withCamelCase(IpsListFlyResponseElementSchema)
813
+ );
298
814
 
299
815
  // packages/fly-node/src/lib/schemas/postgres-list.ts
300
- var import_zod17 = require("zod");
301
- var PostgresListTransformedResponseSchema = import_zod17.z.array(
816
+ var import_zod25 = require("zod");
817
+ var PostgresListTransformedResponseSchema = import_zod25.z.array(
302
818
  withCamelCase(
303
- import_zod17.z.object({
304
- deployed: import_zod17.z.boolean(),
305
- hostname: import_zod17.z.string(),
306
- id: import_zod17.z.string(),
307
- name: import_zod17.z.string(),
308
- organization: import_zod17.z.object({ id: import_zod17.z.string(), slug: import_zod17.z.string() }),
309
- status: import_zod17.z.string(),
310
- version: import_zod17.z.number()
819
+ import_zod25.z.object({
820
+ deployed: import_zod25.z.boolean(),
821
+ hostname: import_zod25.z.string(),
822
+ id: import_zod25.z.string(),
823
+ name: import_zod25.z.string(),
824
+ organization: import_zod25.z.object({ id: import_zod25.z.string(), slug: import_zod25.z.string() }),
825
+ status: import_zod25.z.string(),
826
+ version: import_zod25.z.number()
311
827
  })
312
828
  )
313
- ).or(import_zod17.z.string());
829
+ ).or(import_zod25.z.string());
314
830
 
315
831
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
316
- var import_zod19 = require("zod");
317
- var PostgresUsersListTransformedResponseSchema = import_zod19.z.array(
832
+ var import_zod27 = require("zod");
833
+ var PostgresUsersListTransformedResponseSchema = import_zod27.z.array(
318
834
  withCamelCase(
319
- import_zod19.z.object({
320
- username: import_zod19.z.string(),
321
- superuser: import_zod19.z.boolean(),
322
- databases: import_zod19.z.array(import_zod19.z.string())
835
+ import_zod27.z.object({
836
+ username: import_zod27.z.string(),
837
+ superuser: import_zod27.z.boolean(),
838
+ databases: import_zod27.z.array(import_zod27.z.string())
323
839
  })
324
840
  )
325
841
  );
326
842
 
327
843
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
328
- var import_zod23 = require("zod");
844
+ var import_zod31 = require("zod");
329
845
 
330
846
  // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
331
- var import_zod21 = require("zod");
332
- var SecretsListFlyResponseElementSchema = import_zod21.z.object({
333
- name: import_zod21.z.string(),
334
- digest: import_zod21.z.string()
847
+ var import_zod29 = require("zod");
848
+ var SecretsListFlyResponseElementSchema = import_zod29.z.object({
849
+ name: import_zod29.z.string(),
850
+ digest: import_zod29.z.string()
335
851
  });
336
- var SecretsListTransformedResponseSchema = import_zod21.z.array(
852
+ var SecretsListTransformedResponseSchema = import_zod29.z.array(
337
853
  withCamelCase(SecretsListFlyResponseElementSchema)
338
854
  );
339
855
 
340
856
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
341
- var SecretsListWithAppTransformedResponseSchema = import_zod23.z.array(
857
+ var SecretsListWithAppTransformedResponseSchema = import_zod31.z.array(
342
858
  withCamelCase(
343
859
  SecretsListFlyResponseElementSchema.extend({
344
- app: import_zod23.z.string()
860
+ app: import_zod31.z.string()
345
861
  })
346
862
  )
347
863
  );
348
864
 
349
865
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
350
- var import_zod27 = require("zod");
866
+ var import_zod35 = require("zod");
351
867
 
352
868
  // packages/fly-node/src/lib/schemas/status.schema.ts
353
- var import_zod25 = require("zod");
354
- var statusFlyResponseSchema = import_zod25.z.object({
355
- deployed: import_zod25.z.boolean(),
356
- hostname: import_zod25.z.string(),
357
- id: import_zod25.z.string(),
358
- machines: import_zod25.z.array(
359
- import_zod25.z.object({
360
- id: import_zod25.z.string(),
361
- name: import_zod25.z.string(),
362
- state: import_zod25.z.string(),
363
- region: import_zod25.z.string(),
364
- createdAt: import_zod25.z.string().datetime(),
365
- updatedAt: import_zod25.z.string().datetime(),
366
- config: import_zod25.z.object({
367
- env: import_zod25.z.record(import_zod25.z.string()),
368
- metadata: import_zod25.z.record(import_zod25.z.string())
869
+ var import_zod33 = require("zod");
870
+ var statusFlyResponseSchema = import_zod33.z.object({
871
+ deployed: import_zod33.z.boolean(),
872
+ hostname: import_zod33.z.string(),
873
+ id: import_zod33.z.string(),
874
+ machines: import_zod33.z.array(
875
+ import_zod33.z.object({
876
+ id: import_zod33.z.string(),
877
+ name: import_zod33.z.string(),
878
+ state: import_zod33.z.string(),
879
+ region: import_zod33.z.string(),
880
+ imageRef: import_zod33.z.object({
881
+ registry: import_zod33.z.string(),
882
+ repository: import_zod33.z.string(),
883
+ tag: import_zod33.z.string(),
884
+ digest: import_zod33.z.string(),
885
+ labels: import_zod33.z.record(import_zod33.z.string()).optional()
369
886
  }),
370
- events: import_zod25.z.array(
371
- import_zod25.z.object({
372
- type: import_zod25.z.string(),
373
- status: import_zod25.z.string(),
374
- timestamp: import_zod25.z.number()
887
+ createdAt: import_zod33.z.string().datetime(),
888
+ updatedAt: import_zod33.z.string().datetime(),
889
+ config: import_zod33.z.object({
890
+ env: import_zod33.z.record(import_zod33.z.string()),
891
+ metadata: import_zod33.z.record(import_zod33.z.string()),
892
+ guest: import_zod33.z.object({
893
+ cpu_kind: import_zod33.z.string().optional(),
894
+ cpus: import_zod33.z.number().optional(),
895
+ memory_mb: import_zod33.z.number().optional()
896
+ }).optional()
897
+ }),
898
+ events: import_zod33.z.array(
899
+ import_zod33.z.object({
900
+ type: import_zod33.z.string(),
901
+ status: import_zod33.z.string(),
902
+ timestamp: import_zod33.z.number()
375
903
  })
376
904
  ),
377
- checks: import_zod25.z.array(
378
- import_zod25.z.object({
379
- name: import_zod25.z.string(),
380
- status: import_zod25.z.string(),
381
- output: import_zod25.z.string(),
382
- updatedAt: import_zod25.z.string().datetime()
905
+ checks: import_zod33.z.array(
906
+ import_zod33.z.object({
907
+ name: import_zod33.z.string(),
908
+ status: import_zod33.z.string(),
909
+ output: import_zod33.z.string(),
910
+ updatedAt: import_zod33.z.string().datetime()
383
911
  })
384
912
  ).optional(),
385
- hostStatus: import_zod25.z.string()
913
+ hostStatus: import_zod33.z.string()
386
914
  })
387
915
  ),
388
- name: import_zod25.z.string(),
389
- organization: import_zod25.z.object({
390
- id: import_zod25.z.string(),
391
- slug: import_zod25.z.string()
916
+ name: import_zod33.z.string(),
917
+ organization: import_zod33.z.object({
918
+ id: import_zod33.z.string(),
919
+ slug: import_zod33.z.string()
392
920
  }),
393
- status: import_zod25.z.string(),
394
- version: import_zod25.z.number()
921
+ status: import_zod33.z.string(),
922
+ version: import_zod33.z.number()
395
923
  });
396
924
  var StatusTransformedResponseSchema = withCamelCase(
397
925
  statusFlyResponseSchema,
398
926
  {
399
- preserve: ["machines.config.env", "machines.config.metadata"],
927
+ preserve: [
928
+ "machines.config.env",
929
+ "machines.config.metadata",
930
+ "machines.config.guest"
931
+ ],
400
932
  specialCases: { AppURL: "appUrl" }
401
933
  }
402
934
  );
@@ -404,30 +936,36 @@ var StatusTransformedResponseSchema = withCamelCase(
404
936
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
405
937
  var StatusExtendedTransformedResponseSchema = withCamelCase(
406
938
  statusFlyResponseSchema.extend({
407
- domains: import_zod27.z.array(import_zod27.z.object({ hostname: import_zod27.z.string() })),
408
- secrets: import_zod27.z.array(import_zod27.z.object({ name: import_zod27.z.string() }))
939
+ domains: import_zod35.z.array(import_zod35.z.object({ hostname: import_zod35.z.string() })),
940
+ secrets: import_zod35.z.array(import_zod35.z.object({ name: import_zod35.z.string() }))
409
941
  }),
410
942
  {
411
- preserve: ["machines.config.env", "machines.config.metadata"]
943
+ preserve: [
944
+ "machines.config.env",
945
+ "machines.config.metadata",
946
+ "machines.config.guest"
947
+ ]
412
948
  }
413
949
  );
414
950
 
415
951
  // packages/fly-node/src/lib/schemas/version.schema.ts
416
- var import_zod29 = require("zod");
952
+ var import_zod37 = require("zod");
417
953
  var VersionTransformedResponseSchema = withCamelCase(
418
- import_zod29.z.object({
419
- name: import_zod29.z.string(),
420
- version: import_zod29.z.string(),
421
- commit: import_zod29.z.string(),
422
- branchName: import_zod29.z.string(),
423
- buildDate: import_zod29.z.string().datetime(),
424
- os: import_zod29.z.string(),
425
- architecture: import_zod29.z.string(),
426
- environment: import_zod29.z.string()
954
+ import_zod37.z.object({
955
+ name: import_zod37.z.string(),
956
+ version: import_zod37.z.string(),
957
+ commit: import_zod37.z.string(),
958
+ branchName: import_zod37.z.string(),
959
+ buildDate: import_zod37.z.string().datetime(),
960
+ os: import_zod37.z.string(),
961
+ architecture: import_zod37.z.string(),
962
+ environment: import_zod37.z.string()
427
963
  })
428
964
  );
429
965
 
430
966
  // packages/fly-node/src/lib/fly.class.ts
967
+ var MACHINE_STATE_INTERVAL_MS = 2e3;
968
+ var MACHINE_STATE_TIMEOUT_MS = 12e4;
431
969
  var Fly = class {
432
970
  /** Use underscore to avoid conflict with public `config` property */
433
971
  _config;
@@ -457,7 +995,10 @@ var Fly = class {
457
995
  info: config?.logger?.info || console.log,
458
996
  error: config?.logger?.error || console.error,
459
997
  traceCLI: config?.logger?.traceCLI ?? false,
460
- redactSecrets: config?.logger?.redactSecrets ?? true
998
+ redactSecrets: config?.logger?.redactSecrets ?? true,
999
+ verbose: config?.logger?.verbose ?? false,
1000
+ debug: config?.logger?.debug ?? false,
1001
+ streamToConsole: config?.logger?.streamToConsole ?? false
461
1002
  };
462
1003
  if (this._config.token) {
463
1004
  process.env["FLY_ACCESS_TOKEN"] = this._config.token;
@@ -649,7 +1190,10 @@ ${error}`
649
1190
  */
650
1191
  config = {
651
1192
  /**
652
- * Save an application's remote configuration locally as TOML file.
1193
+ * Save an application's remote configuration locally.
1194
+ *
1195
+ * TOML by default; name the path `.json` or `.yaml`/`.yml` for either of
1196
+ * those instead.
653
1197
  *
654
1198
  * @param options - Options for saving an application's configuration
655
1199
  * @throws An error if the configuration cannot be saved
@@ -684,7 +1228,12 @@ ${error}`);
684
1228
  }
685
1229
  };
686
1230
  /**
687
- * Deploy an application.
1231
+ * Deploy an application, or just build its Docker image without deploying when
1232
+ * `buildOnly` is set (equivalent to using `build(options)`).
1233
+ *
1234
+ * Pre-building is useful to ensure the image can be built successfully and exists
1235
+ * before running a deploy that depends on it, and also to get the image reference for use in
1236
+ * subsequent operations.
688
1237
  *
689
1238
  * A valid config file is required but the app doesn't have to exist,
690
1239
  * since it gets created if needed.
@@ -694,15 +1243,28 @@ ${error}`);
694
1243
  * 2. Instance app name
695
1244
  * 3. App name from the provided config file
696
1245
  *
697
- * Existing secrets are preserved.
698
- *
699
- * @param options - Options for deploying an application
700
- * @throws An error if the deployment fails
1246
+ * @param options - Deployment or build options
1247
+ * @returns Build or deploy response depending on `buildOnly` option
1248
+ * @throws An error if the operation fails
701
1249
  */
702
1250
  deploy = async (options) => {
1251
+ const isBuildOnly = options?.buildOnly === true;
703
1252
  try {
704
1253
  await this.ensureInitialized();
705
- const appName = await this.deployApp(options);
1254
+ if (isBuildOnly) {
1255
+ const { appName: appName2, imageRef } = await this.deployApp({
1256
+ ...options,
1257
+ buildOnly: true
1258
+ });
1259
+ if (!imageRef) {
1260
+ throw new Error(
1261
+ "Build completed but image reference not found in output"
1262
+ );
1263
+ }
1264
+ this.logger.info(`Image for '${appName2}' built: ${imageRef}`);
1265
+ return BuildResponseSchema.parse({ appName: appName2, imageRef });
1266
+ }
1267
+ const { appName } = await this.deployApp(options);
706
1268
  this.logger.info(`Application '${appName}' was deployed`);
707
1269
  const status = await this.fetchAppStatus("throwOnError", {
708
1270
  app: appName
@@ -714,16 +1276,184 @@ ${error}`);
714
1276
  });
715
1277
  } catch (error) {
716
1278
  throw new Error(
717
- `[deploy] something broke, check your deployments
1279
+ `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
718
1280
  ${error}`
719
1281
  );
720
1282
  }
721
1283
  };
1284
+ /**
1285
+ * Manage public IP addresses
1286
+ */
1287
+ ips = {
1288
+ /**
1289
+ * List the public IP addresses allocated to an application
1290
+ *
1291
+ * @param options - The application or configuration to list addresses for
1292
+ * @returns The allocated addresses, empty when the app has none
1293
+ * @throws An error if listing addresses fails
1294
+ */
1295
+ list: async (options) => {
1296
+ try {
1297
+ await this.ensureInitialized();
1298
+ return await this.fetchAppIps("throwOnError", options);
1299
+ } catch (error) {
1300
+ throw new Error(`[list ips] something broke
1301
+ ${error}`);
1302
+ }
1303
+ },
1304
+ /**
1305
+ * Give an application the public addresses it needs to be reachable.
1306
+ *
1307
+ * Idempotent by inspection: it allocates only what is missing, so it is
1308
+ * safe on every deploy rather than only on create. That matters because
1309
+ * `flyctl` allocates addresses only for an app it creates itself — an app
1310
+ * that arrives any other way, such as a registry push auto-creating it,
1311
+ * deploys green and answers nothing.
1312
+ *
1313
+ * @param options - The application, and which addresses to ensure
1314
+ * @returns The addresses the application holds afterwards
1315
+ * @throws An error if an address cannot be allocated
1316
+ */
1317
+ ensure: async (options) => {
1318
+ try {
1319
+ await this.ensureInitialized();
1320
+ const { sharedV4 = true, v6 = true } = options ?? {};
1321
+ const existing = await this.fetchAppIps("throwOnError", options);
1322
+ const has = (...types) => existing.some((ip) => types.includes(ip.type));
1323
+ if (sharedV4 && !has("v4", "shared_v4")) {
1324
+ await this.allocateIp("allocate-v4", options);
1325
+ this.logger.info("Allocated a shared IPv4 address");
1326
+ }
1327
+ if (v6 && !has("v6")) {
1328
+ await this.allocateIp("allocate-v6", options);
1329
+ this.logger.info("Allocated a dedicated IPv6 address");
1330
+ }
1331
+ return await this.fetchAppIps("throwOnError", options);
1332
+ } catch (error) {
1333
+ throw new Error(
1334
+ `[ensure ips] something broke, check your app addresses
1335
+ ${error}`
1336
+ );
1337
+ }
1338
+ }
1339
+ };
1340
+ /**
1341
+ * Manage machines
1342
+ */
1343
+ machines = {
1344
+ /**
1345
+ * Start a machine
1346
+ *
1347
+ * @param app - The name of the application
1348
+ * @param machineId - The machine ID to start
1349
+ * @throws An error if the machine cannot be started
1350
+ */
1351
+ start: async (app, machineId) => {
1352
+ try {
1353
+ await this.ensureInitialized();
1354
+ await this.startMachine(app, machineId);
1355
+ this.logger.info(`Machine '${machineId}' in app '${app}' was started`);
1356
+ } catch (error) {
1357
+ throw new Error(`[start machine] something broke
1358
+ ${error}`);
1359
+ }
1360
+ },
1361
+ /**
1362
+ * Stop a machine
1363
+ *
1364
+ * @param app - The name of the application
1365
+ * @param machineId - The machine ID to stop
1366
+ * @throws An error if the machine cannot be stopped
1367
+ */
1368
+ stop: async (app, machineId) => {
1369
+ try {
1370
+ await this.ensureInitialized();
1371
+ await this.stopMachine(app, machineId);
1372
+ this.logger.info(`Machine '${machineId}' in app '${app}' was stopped`);
1373
+ } catch (error) {
1374
+ throw new Error(`[stop machine] something broke
1375
+ ${error}`);
1376
+ }
1377
+ },
1378
+ /**
1379
+ * Restart a machine by stopping then starting it.
1380
+ *
1381
+ * Waits until Fly reports the machine stopped (or suspended) before
1382
+ * starting it, then until it is started. If the start fails after the
1383
+ * stop, the error says the machine was left stopped.
1384
+ *
1385
+ * @param app - The name of the application
1386
+ * @param machineId - The machine ID to restart
1387
+ * @throws An error if the machine cannot be restarted
1388
+ */
1389
+ restart: async (app, machineId) => {
1390
+ try {
1391
+ await this.ensureInitialized();
1392
+ await this.restartMachine(app, machineId);
1393
+ this.logger.info(
1394
+ `Machine '${machineId}' in app '${app}' was restarted`
1395
+ );
1396
+ } catch (error) {
1397
+ throw new Error(`[restart machine] something broke
1398
+ ${error}`);
1399
+ }
1400
+ },
1401
+ /**
1402
+ * Update a machine's per-machine configuration (env vars, etc.).
1403
+ *
1404
+ * Unlike `restart`, this creates a new machine version from the updated config
1405
+ * and forces a cold start — it does NOT resume from a suspended memory snapshot.
1406
+ *
1407
+ * @param app - The name of the application
1408
+ * @param machineId - The machine ID to update
1409
+ * @param options - Fields to update; env values set to `''` clear that var
1410
+ * @throws An error if the machine cannot be updated
1411
+ */
1412
+ update: async (app, machineId, options) => {
1413
+ try {
1414
+ await this.ensureInitialized();
1415
+ await this.updateMachine(app, machineId, options);
1416
+ this.logger.info(`Machine '${machineId}' in app '${app}' was updated`);
1417
+ } catch (error) {
1418
+ throw new Error(`[update machine] something broke
1419
+ ${error}`);
1420
+ }
1421
+ }
1422
+ };
722
1423
  postgres = {
723
1424
  detach: async (cluster, app) => {
724
1425
  await this.detachPostgres(cluster, app);
725
1426
  }
726
1427
  };
1428
+ /**
1429
+ * Run commands inside a running machine
1430
+ */
1431
+ ssh = {
1432
+ /**
1433
+ * Execute a command in a running machine and return its output.
1434
+ *
1435
+ * Requires a started machine - Fly cannot connect to a stopped or
1436
+ * suspended one. Use `machines.start` first when the app may be idle.
1437
+ *
1438
+ * The output is returned to the caller and not logged unless CLI tracing
1439
+ * is enabled, so it can be used to read values that are otherwise
1440
+ * write-only, such as secrets injected at deploy time.
1441
+ *
1442
+ * @param app - The name of the application
1443
+ * @param command - The command to run inside the machine
1444
+ * @returns The command output
1445
+ * @throws An error if there is no started machine or the command fails
1446
+ */
1447
+ exec: async (app, command) => {
1448
+ try {
1449
+ await this.ensureInitialized();
1450
+ return await this.sshExec(app, command);
1451
+ } catch (error) {
1452
+ throw new Error(`[ssh exec] something broke
1453
+ ${error}`);
1454
+ }
1455
+ }
1456
+ };
727
1457
  /**
728
1458
  * Manage application secrets
729
1459
  */
@@ -750,6 +1480,28 @@ ${error}`
750
1480
  );
751
1481
  }
752
1482
  },
1483
+ /**
1484
+ * Apply secrets that were staged with `set({ stage: true })`.
1485
+ *
1486
+ * Staging first and deploying afterwards lets a set of apps take a new
1487
+ * value together, instead of each restarting as its own secret is written.
1488
+ *
1489
+ * Fly needs a started machine to update, so an app whose machines are all
1490
+ * stopped or suspended has to be started before this will do anything.
1491
+ *
1492
+ * @param app - The name of the application
1493
+ * @throws An error if the staged secrets cannot be deployed
1494
+ */
1495
+ deploy: async (app) => {
1496
+ try {
1497
+ await this.ensureInitialized();
1498
+ await this.deployStagedSecrets(app);
1499
+ this.logger.info(`Staged secrets were deployed for '${app}'`);
1500
+ } catch (error) {
1501
+ throw new Error(`[deploy secrets] something broke
1502
+ ${error}`);
1503
+ }
1504
+ },
753
1505
  /**
754
1506
  * List secrets for an application or all secrets when options is 'all'
755
1507
  *
@@ -810,6 +1562,22 @@ ${error}`);
810
1562
  return null;
811
1563
  }
812
1564
  };
1565
+ //
1566
+ // DX friendly methods outside what Fly CLI provides
1567
+ //
1568
+ /**
1569
+ * Build a Docker image for an application and push it to the Fly registry
1570
+ * without deploying.
1571
+ *
1572
+ * The image reference is returned for use in a subsequent `deploy` that depends on it.
1573
+ *
1574
+ * Shorthand for `deploy({ ...options, buildOnly: true })`.
1575
+ *
1576
+ * @param options - Build options
1577
+ * @returns The app name and image reference for use in a subsequent `deploy`
1578
+ * @throws An error if the build fails or the image reference cannot be parsed
1579
+ */
1580
+ build = (options) => this.deploy({ ...options, buildOnly: true });
813
1581
  /**
814
1582
  * Get the extended details of an application
815
1583
  *
@@ -856,12 +1624,11 @@ ${error}`);
856
1624
  }
857
1625
  /**
858
1626
  * @private
859
- * @returns The name of the deployed application
1627
+ * @returns The app name and optional image reference (only set when buildOnly is true)
860
1628
  * @throws An error if the deployment fails
861
1629
  */
862
1630
  async deployApp(options) {
863
1631
  let appName = "";
864
- let appSecrets = [];
865
1632
  let deployConfig = options?.config || this.instanceConfig;
866
1633
  let lookupApp = options?.app || this.instanceApp;
867
1634
  const lookupConfig = deployConfig;
@@ -926,26 +1693,30 @@ ${error}`);
926
1693
  appName = name;
927
1694
  this.logger.info(`Application '${appName}' was created`);
928
1695
  } else {
929
- appSecrets = await this.fetchAppSecrets("throwOnError", { app: appName });
930
1696
  this.logger.info(`Updating existing application '${appName}'`);
931
1697
  }
932
1698
  NameSchema.parse(appName);
933
- if (options?.secrets) {
934
- const existingSecrets = new Set(appSecrets.map(({ name }) => name));
935
- const newSecrets = {};
1699
+ if (!options?.buildOnly && options?.secrets) {
1700
+ const staged = {};
1701
+ const empty = [];
936
1702
  for (const [key, value] of Object.entries(options.secrets)) {
937
- if (!existingSecrets.has(key)) {
938
- newSecrets[key] = value;
1703
+ if (value === "") {
1704
+ empty.push(key);
939
1705
  } else {
940
- this.logger.info(
941
- `Secret '${key}' already exists for '${appName}', skipping`
942
- );
1706
+ staged[key] = value;
943
1707
  }
944
1708
  }
945
- const keys = Object.keys(newSecrets);
1709
+ if (empty.length > 0) {
1710
+ this.logger.error(
1711
+ `Refusing to blank secrets with no value for '${appName}': ${empty.join(", ")}`
1712
+ );
1713
+ }
1714
+ const keys = Object.keys(staged);
946
1715
  if (keys.length > 0) {
947
- this.logger.info(`Adding secrets to '${appName}': ${keys.join(", ")}`);
948
- await this.setAppSecrets(newSecrets, {
1716
+ this.logger.info(
1717
+ `Staging secrets for '${appName}': ${keys.join(", ")}`
1718
+ );
1719
+ await this.setAppSecrets(staged, {
949
1720
  app: appName,
950
1721
  stage: true
951
1722
  });
@@ -957,7 +1728,7 @@ ${error}`);
957
1728
  );
958
1729
  appName = options.app;
959
1730
  }
960
- if (options?.postgres) {
1731
+ if (!options?.buildOnly && options?.postgres) {
961
1732
  const users = await this.fetchPostgresUsers(
962
1733
  options.postgres,
963
1734
  "nullOnError"
@@ -972,9 +1743,13 @@ ${error}`);
972
1743
  );
973
1744
  } else {
974
1745
  this.logger.info(
975
- `Attach Postgres cluster '${options.postgres}' to '${appName}'`
1746
+ `Attach Postgres cluster '${options.postgres}' to '${appName}'${options.databaseName ? ` with database '${options.databaseName}'` : ""}`
1747
+ );
1748
+ await this.attachPostgres(
1749
+ options.postgres,
1750
+ appName,
1751
+ options.databaseName
976
1752
  );
977
- await this.attachPostgres(options.postgres, appName);
978
1753
  }
979
1754
  }
980
1755
  const args = ["deploy", "--app", appName, "--config", deployConfig];
@@ -987,20 +1762,39 @@ ${error}`);
987
1762
  for (const [key, value] of Object.entries(options?.env || {})) {
988
1763
  args.push("--env", `${key}=${this.safeArg(value)}`);
989
1764
  }
1765
+ for (const [key, value] of Object.entries(options?.buildArgs || {})) {
1766
+ args.push("--build-arg", `${key}=${this.safeArg(value)}`);
1767
+ }
1768
+ if (options?.image) {
1769
+ args.push("--image", options.image);
1770
+ }
1771
+ if (options?.buildOnly) {
1772
+ args.push("--build-only", "--push");
1773
+ }
990
1774
  if (options?.optOutDepotBuilder) {
991
1775
  args.push("--depot=false");
992
1776
  }
993
1777
  args.push("--yes");
994
- this.logger.info(`Deploying '${appName}'...`);
995
- await this.execFly(args);
996
- return appName;
1778
+ this.logger.info(
1779
+ options?.buildOnly ? `Building image for '${appName}'...` : `Deploying '${appName}'...`
1780
+ );
1781
+ const output = await this.execFly(
1782
+ args,
1783
+ options?.buildOnly ? { streamStrategy: "combined" } : void 0
1784
+ );
1785
+ const imageRef = options?.buildOnly ? output?.match(/registry\.fly\.io\/\S+/)?.[0] : void 0;
1786
+ return { appName, imageRef };
997
1787
  }
998
1788
  /**
999
1789
  * @private
1000
1790
  * @throws An error if the Postgres database cannot be attached
1001
1791
  */
1002
- async attachPostgres(postgres, app) {
1003
- const args = ["postgres", "attach", postgres, "--app", app, "--yes"];
1792
+ async attachPostgres(postgres, app, databaseName) {
1793
+ const args = ["postgres", "attach", postgres, "--app", app];
1794
+ if (databaseName) {
1795
+ args.push("--database-name", databaseName);
1796
+ }
1797
+ args.push("--yes");
1004
1798
  await this.execFly(args);
1005
1799
  }
1006
1800
  /**
@@ -1074,6 +1868,45 @@ ${error}`);
1074
1868
  await this.execFly(args);
1075
1869
  return NameSchema.parse(status.name);
1076
1870
  }
1871
+ /**
1872
+ * Allocate one public address.
1873
+ *
1874
+ * A dedicated v4 is billed, so the v4 path is always `--shared`.
1875
+ *
1876
+ * The two commands do not take the same flags: `allocate-v4` has `--yes`
1877
+ * because a dedicated v4 costs money and prompts, while `allocate-v6` is
1878
+ * free, never prompts, and rejects the flag outright with `unknown flag`.
1879
+ * The asymmetry is flyctl's, not ours — do not tidy it away.
1880
+ *
1881
+ * @private
1882
+ * @throws An error if the address cannot be allocated
1883
+ */
1884
+ async allocateIp(command, options) {
1885
+ const args = ["ips", command];
1886
+ if (command === "allocate-v4") {
1887
+ args.push("--shared");
1888
+ }
1889
+ args.push(...this.getAppOrConfigArgs(options));
1890
+ if (command === "allocate-v4") {
1891
+ args.push("--yes");
1892
+ }
1893
+ await this.execFly(args);
1894
+ }
1895
+ async fetchAppIps(onError, options) {
1896
+ const args = ["ips", "list"];
1897
+ args.push(...this.getAppOrConfigArgs(options));
1898
+ args.push("--json");
1899
+ try {
1900
+ return await IpsListTransformedResponseSchema.parseAsync(
1901
+ await this.execFly(args)
1902
+ );
1903
+ } catch (error) {
1904
+ if (onError === "throwOnError") {
1905
+ throw error;
1906
+ }
1907
+ return null;
1908
+ }
1909
+ }
1077
1910
  /**
1078
1911
  * @private
1079
1912
  * @returns The name of the application
@@ -1087,6 +1920,102 @@ ${error}`);
1087
1920
  await this.execFly(args);
1088
1921
  return NameSchema.parse(status.name);
1089
1922
  }
1923
+ /**
1924
+ * @private
1925
+ * Deploy secrets previously staged for an application
1926
+ * @throws An error if the staged secrets cannot be deployed
1927
+ */
1928
+ async deployStagedSecrets(app) {
1929
+ const args = ["secrets", "deploy", "--app", app];
1930
+ await this.execFly(args);
1931
+ }
1932
+ /**
1933
+ * @private
1934
+ * Execute a command inside a running machine
1935
+ * @returns The command output
1936
+ * @throws An error if the command fails
1937
+ */
1938
+ async sshExec(app, command) {
1939
+ const args = ["ssh", "console", "--app", app, "--command", command];
1940
+ return await this.execFly(args);
1941
+ }
1942
+ /**
1943
+ * @private
1944
+ * Start a machine
1945
+ * @throws An error if the machine cannot be started
1946
+ */
1947
+ async startMachine(app, machineId) {
1948
+ const args = ["machine", "start", machineId, "--app", app];
1949
+ await this.execFly(args);
1950
+ }
1951
+ /**
1952
+ * @private
1953
+ * Stop a machine
1954
+ * @throws An error if the machine cannot be stopped
1955
+ */
1956
+ async stopMachine(app, machineId) {
1957
+ const args = ["machine", "stop", machineId, "--app", app];
1958
+ await this.execFly(args);
1959
+ }
1960
+ /**
1961
+ * @private
1962
+ * Restart a machine by stopping then starting it, waiting on the state Fly
1963
+ * reports rather than a fixed delay: the start is only issued once the
1964
+ * machine is stopped (or suspended), and the restart is done once it is
1965
+ * started again.
1966
+ * @throws An error saying the machine was left stopped when anything after
1967
+ * the stop fails
1968
+ */
1969
+ async restartMachine(app, machineId) {
1970
+ await this.stopMachine(app, machineId);
1971
+ try {
1972
+ await this.waitForMachineState(app, machineId, ["stopped", "suspended"]);
1973
+ await this.startMachine(app, machineId);
1974
+ await this.waitForMachineState(app, machineId, ["started"]);
1975
+ } catch (error) {
1976
+ const reason = error instanceof Error ? error.message : String(error);
1977
+ throw new Error(
1978
+ `Machine '${machineId}' in app '${app}' was stopped but did not start again: ${reason}`,
1979
+ { cause: error }
1980
+ );
1981
+ }
1982
+ }
1983
+ /**
1984
+ * @private
1985
+ * Poll the app status until the machine reports one of the given states
1986
+ * @throws An error if the machine does not reach a state in time
1987
+ */
1988
+ async waitForMachineState(app, machineId, states) {
1989
+ const deadline = Date.now() + MACHINE_STATE_TIMEOUT_MS;
1990
+ while (Date.now() < deadline) {
1991
+ const status = await this.fetchAppStatus("nullOnError", { app });
1992
+ const machine = status?.machines.find(({ id }) => id === machineId);
1993
+ if (machine && states.includes(machine.state)) {
1994
+ return;
1995
+ }
1996
+ await new Promise(
1997
+ (resolve) => setTimeout(resolve, MACHINE_STATE_INTERVAL_MS)
1998
+ );
1999
+ }
2000
+ throw new Error(
2001
+ `Machine '${machineId}' in app '${app}' did not reach ${states.join("/")} in time`
2002
+ );
2003
+ }
2004
+ /**
2005
+ * @private
2006
+ * Update a machine's per-machine config (env vars, etc.).
2007
+ * Creates a new machine version so the machine cold-starts from the updated config,
2008
+ * bypassing any suspended memory snapshot.
2009
+ * @throws An error if the machine cannot be updated
2010
+ */
2011
+ async updateMachine(app, machineId, options) {
2012
+ const args = ["machine", "update", machineId, "--app", app];
2013
+ for (const [key, value] of Object.entries(options.env || {})) {
2014
+ args.push("--env", `${key}=${this.safeArg(value)}`);
2015
+ }
2016
+ args.push("--yes");
2017
+ await this.execFly(args);
2018
+ }
1090
2019
  async fetchAllApps(onError) {
1091
2020
  const args = ["apps", "list", "--json"];
1092
2021
  try {
@@ -1166,7 +2095,7 @@ ${error}`);
1166
2095
  if (onError === "throwOnError") {
1167
2096
  throw error;
1168
2097
  }
1169
- if (error instanceof import_zod30.ZodError) {
2098
+ if (error instanceof import_zod38.ZodError) {
1170
2099
  this.logger.info(`Failed to parse response:
1171
2100
  ${error.message}`);
1172
2101
  this.logger.info(`Raw response:
@@ -1241,9 +2170,23 @@ ${JSON.stringify(response, null, 2)}`);
1241
2170
  * @private
1242
2171
  * Save remote config to a local file
1243
2172
  *
2173
+ * Two things flyctl expects that a first-time caller would not: the output
2174
+ * format is no longer sniffed from the path's extension — `--json`/`--yaml`
2175
+ * has to be passed, TOML being what is left over when neither is — and the
2176
+ * destination must already exist as a parseable file of that format, or
2177
+ * `flyctl` refuses to write to it at all, mistaking "does not exist yet"
2178
+ * for "path is wrong". A fresh, empty seed of the right shape satisfies
2179
+ * that read without affecting what gets written back over it.
2180
+ *
1244
2181
  * @throws An error if the config cannot be saved
1245
2182
  */
1246
2183
  async saveConfig(options) {
2184
+ const isJson = options.config.endsWith(".json");
2185
+ const isYaml = /\.ya?ml$/.test(options.config);
2186
+ if (!(0, import_fs.existsSync)(options.config)) {
2187
+ (0, import_fs.mkdirSync)((0, import_path.dirname)(options.config), { recursive: true });
2188
+ (0, import_fs.writeFileSync)(options.config, isJson ? "{}" : "");
2189
+ }
1247
2190
  const args = [
1248
2191
  "config",
1249
2192
  "save",
@@ -1251,6 +2194,7 @@ ${JSON.stringify(response, null, 2)}`);
1251
2194
  options.app,
1252
2195
  "--config",
1253
2196
  options.config,
2197
+ ...isJson ? ["--json"] : isYaml ? ["--yaml"] : [],
1254
2198
  "--yes"
1255
2199
  ];
1256
2200
  await this.execFly(args);
@@ -1262,8 +2206,7 @@ ${JSON.stringify(response, null, 2)}`);
1262
2206
  * @throws An error if Fly CLI is not installed or not authenticated
1263
2207
  */
1264
2208
  async ensureInitialized() {
1265
- if (this.initialized)
1266
- return;
2209
+ if (this.initialized) return;
1267
2210
  try {
1268
2211
  if (!await this.isInstalled()) {
1269
2212
  throw new Error("Fly CLI must be installed to use this library");
@@ -1280,6 +2223,12 @@ ${JSON.stringify(response, null, 2)}`);
1280
2223
  }
1281
2224
  async execFly(command, options, onError = "throwOnError") {
1282
2225
  const args = Array.isArray(command) ? command : command.split(" ");
2226
+ if (this.logger.verbose) {
2227
+ args.push("--verbose");
2228
+ }
2229
+ if (this.logger.debug) {
2230
+ args.push("--debug");
2231
+ }
1283
2232
  const flyCmd = "flyctl";
1284
2233
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
1285
2234
  let output = "";
@@ -1289,11 +2238,17 @@ ${JSON.stringify(response, null, 2)}`);
1289
2238
  output = await spawnPty(flyCmd, args, { prompt: options.prompt });
1290
2239
  this.traceCLI("RESULT", output);
1291
2240
  } else {
1292
- const result = await spawn(flyCmd, args, options);
1293
- output = result.stdout.trim();
2241
+ const { streamStrategy = "stdout", ...spawnOpts } = options ?? {};
2242
+ const result = await spawn(flyCmd, args, {
2243
+ ...spawnOpts,
2244
+ streamToConsole: this.logger.streamToConsole
2245
+ });
2246
+ const stdout = result.stdout.trim();
1294
2247
  const stderr = result.stderr.trim();
1295
- this.traceCLI("RESULT", `${output}${stderr ? `
2248
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
1296
2249
  ${stderr}` : ""}`);
2250
+ output = streamStrategy === "combined" ? `${stdout}
2251
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
1297
2252
  }
1298
2253
  } catch (error) {
1299
2254
  const errorMsg = error.message;
@@ -1464,5 +2419,13 @@ ${errorMsg}`);
1464
2419
  };
1465
2420
  // Annotate the CommonJS export names for ESM import in node:
1466
2421
  0 && (module.exports = {
1467
- Fly
2422
+ CertificateApiResponseSchema,
2423
+ CertificateListApiResponseSchema,
2424
+ DnsInstructionsSchema,
2425
+ Fly,
2426
+ FlyApi,
2427
+ FlyApiError,
2428
+ HostnameCheckApiResponseSchema,
2429
+ MachineApiResponseSchema,
2430
+ MachineListApiResponseSchema
1468
2431
  });