@cdwr/fly-node 0.3.0 → 0.3.1

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
@@ -30,52 +30,541 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // packages/fly-node/src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- Fly: () => Fly
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
43
  module.exports = __toCommonJS(src_exports);
36
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
+ `;
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_zod36 = 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,135 @@ 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-]+$/);
298
800
 
299
801
  // packages/fly-node/src/lib/schemas/postgres-list.ts
300
- var import_zod17 = require("zod");
301
- var PostgresListTransformedResponseSchema = import_zod17.z.array(
802
+ var import_zod23 = require("zod");
803
+ var PostgresListTransformedResponseSchema = import_zod23.z.array(
302
804
  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()
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()
311
813
  })
312
814
  )
313
- ).or(import_zod17.z.string());
815
+ ).or(import_zod23.z.string());
314
816
 
315
817
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
316
- var import_zod19 = require("zod");
317
- var PostgresUsersListTransformedResponseSchema = import_zod19.z.array(
818
+ var import_zod25 = require("zod");
819
+ var PostgresUsersListTransformedResponseSchema = import_zod25.z.array(
318
820
  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())
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())
323
825
  })
324
826
  )
325
827
  );
326
828
 
327
829
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
328
- var import_zod23 = require("zod");
830
+ var import_zod29 = require("zod");
329
831
 
330
832
  // 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()
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()
335
837
  });
336
- var SecretsListTransformedResponseSchema = import_zod21.z.array(
838
+ var SecretsListTransformedResponseSchema = import_zod27.z.array(
337
839
  withCamelCase(SecretsListFlyResponseElementSchema)
338
840
  );
339
841
 
340
842
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
341
- var SecretsListWithAppTransformedResponseSchema = import_zod23.z.array(
843
+ var SecretsListWithAppTransformedResponseSchema = import_zod29.z.array(
342
844
  withCamelCase(
343
845
  SecretsListFlyResponseElementSchema.extend({
344
- app: import_zod23.z.string()
846
+ app: import_zod29.z.string()
345
847
  })
346
848
  )
347
849
  );
348
850
 
349
851
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
350
- var import_zod27 = require("zod");
852
+ var import_zod33 = require("zod");
351
853
 
352
854
  // 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())
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()
872
+ }),
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()
882
+ }).optional()
369
883
  }),
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()
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()
375
889
  })
376
890
  ),
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()
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()
383
897
  })
384
898
  ).optional(),
385
- hostStatus: import_zod25.z.string()
899
+ hostStatus: import_zod31.z.string()
386
900
  })
387
901
  ),
388
- name: import_zod25.z.string(),
389
- organization: import_zod25.z.object({
390
- id: import_zod25.z.string(),
391
- slug: import_zod25.z.string()
902
+ name: import_zod31.z.string(),
903
+ organization: import_zod31.z.object({
904
+ id: import_zod31.z.string(),
905
+ slug: import_zod31.z.string()
392
906
  }),
393
- status: import_zod25.z.string(),
394
- version: import_zod25.z.number()
907
+ status: import_zod31.z.string(),
908
+ version: import_zod31.z.number()
395
909
  });
396
910
  var StatusTransformedResponseSchema = withCamelCase(
397
911
  statusFlyResponseSchema,
398
912
  {
399
- preserve: ["machines.config.env", "machines.config.metadata"],
913
+ preserve: [
914
+ "machines.config.env",
915
+ "machines.config.metadata",
916
+ "machines.config.guest"
917
+ ],
400
918
  specialCases: { AppURL: "appUrl" }
401
919
  }
402
920
  );
@@ -404,26 +922,30 @@ var StatusTransformedResponseSchema = withCamelCase(
404
922
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
405
923
  var StatusExtendedTransformedResponseSchema = withCamelCase(
406
924
  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() }))
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() }))
409
927
  }),
410
928
  {
411
- preserve: ["machines.config.env", "machines.config.metadata"]
929
+ preserve: [
930
+ "machines.config.env",
931
+ "machines.config.metadata",
932
+ "machines.config.guest"
933
+ ]
412
934
  }
413
935
  );
414
936
 
415
937
  // packages/fly-node/src/lib/schemas/version.schema.ts
416
- var import_zod29 = require("zod");
938
+ var import_zod35 = require("zod");
417
939
  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()
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()
427
949
  })
428
950
  );
429
951
 
@@ -457,7 +979,10 @@ var Fly = class {
457
979
  info: config?.logger?.info || console.log,
458
980
  error: config?.logger?.error || console.error,
459
981
  traceCLI: config?.logger?.traceCLI ?? false,
460
- redactSecrets: config?.logger?.redactSecrets ?? true
982
+ redactSecrets: config?.logger?.redactSecrets ?? true,
983
+ verbose: config?.logger?.verbose ?? false,
984
+ debug: config?.logger?.debug ?? false,
985
+ streamToConsole: config?.logger?.streamToConsole ?? false
461
986
  };
462
987
  if (this._config.token) {
463
988
  process.env["FLY_ACCESS_TOKEN"] = this._config.token;
@@ -649,7 +1174,10 @@ ${error}`
649
1174
  */
650
1175
  config = {
651
1176
  /**
652
- * Save an application's remote configuration locally as TOML file.
1177
+ * Save an application's remote configuration locally.
1178
+ *
1179
+ * TOML by default; name the path `.json` or `.yaml`/`.yml` for either of
1180
+ * those instead.
653
1181
  *
654
1182
  * @param options - Options for saving an application's configuration
655
1183
  * @throws An error if the configuration cannot be saved
@@ -684,7 +1212,12 @@ ${error}`);
684
1212
  }
685
1213
  };
686
1214
  /**
687
- * Deploy an application.
1215
+ * Deploy an application, or just build its Docker image without deploying when
1216
+ * `buildOnly` is set (equivalent to using `build(options)`).
1217
+ *
1218
+ * Pre-building is useful to ensure the image can be built successfully and exists
1219
+ * before running a deploy that depends on it, and also to get the image reference for use in
1220
+ * subsequent operations.
688
1221
  *
689
1222
  * A valid config file is required but the app doesn't have to exist,
690
1223
  * since it gets created if needed.
@@ -694,15 +1227,28 @@ ${error}`);
694
1227
  * 2. Instance app name
695
1228
  * 3. App name from the provided config file
696
1229
  *
697
- * Existing secrets are preserved.
698
- *
699
- * @param options - Options for deploying an application
700
- * @throws An error if the deployment fails
1230
+ * @param options - Deployment or build options
1231
+ * @returns Build or deploy response depending on `buildOnly` option
1232
+ * @throws An error if the operation fails
701
1233
  */
702
1234
  deploy = async (options) => {
1235
+ const isBuildOnly = options?.buildOnly === true;
703
1236
  try {
704
1237
  await this.ensureInitialized();
705
- const appName = await this.deployApp(options);
1238
+ if (isBuildOnly) {
1239
+ const { appName: appName2, imageRef } = await this.deployApp({
1240
+ ...options,
1241
+ buildOnly: true
1242
+ });
1243
+ if (!imageRef) {
1244
+ throw new Error(
1245
+ "Build completed but image reference not found in output"
1246
+ );
1247
+ }
1248
+ this.logger.info(`Image for '${appName2}' built: ${imageRef}`);
1249
+ return BuildResponseSchema.parse({ appName: appName2, imageRef });
1250
+ }
1251
+ const { appName } = await this.deployApp(options);
706
1252
  this.logger.info(`Application '${appName}' was deployed`);
707
1253
  const status = await this.fetchAppStatus("throwOnError", {
708
1254
  app: appName
@@ -714,16 +1260,124 @@ ${error}`);
714
1260
  });
715
1261
  } catch (error) {
716
1262
  throw new Error(
717
- `[deploy] something broke, check your deployments
1263
+ `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
718
1264
  ${error}`
719
1265
  );
720
1266
  }
721
1267
  };
1268
+ /**
1269
+ * Manage machines
1270
+ */
1271
+ machines = {
1272
+ /**
1273
+ * Start a machine
1274
+ *
1275
+ * @param app - The name of the application
1276
+ * @param machineId - The machine ID to start
1277
+ * @throws An error if the machine cannot be started
1278
+ */
1279
+ start: async (app, machineId) => {
1280
+ try {
1281
+ await this.ensureInitialized();
1282
+ await this.startMachine(app, machineId);
1283
+ this.logger.info(`Machine '${machineId}' in app '${app}' was started`);
1284
+ } catch (error) {
1285
+ throw new Error(`[start machine] something broke
1286
+ ${error}`);
1287
+ }
1288
+ },
1289
+ /**
1290
+ * Stop a machine
1291
+ *
1292
+ * @param app - The name of the application
1293
+ * @param machineId - The machine ID to stop
1294
+ * @throws An error if the machine cannot be stopped
1295
+ */
1296
+ stop: async (app, machineId) => {
1297
+ try {
1298
+ await this.ensureInitialized();
1299
+ await this.stopMachine(app, machineId);
1300
+ this.logger.info(`Machine '${machineId}' in app '${app}' was stopped`);
1301
+ } catch (error) {
1302
+ throw new Error(`[stop machine] something broke
1303
+ ${error}`);
1304
+ }
1305
+ },
1306
+ /**
1307
+ * Restart a machine by stopping then starting it
1308
+ *
1309
+ * @param app - The name of the application
1310
+ * @param machineId - The machine ID to restart
1311
+ * @throws An error if the machine cannot be restarted
1312
+ */
1313
+ restart: async (app, machineId) => {
1314
+ try {
1315
+ await this.ensureInitialized();
1316
+ await this.restartMachine(app, machineId);
1317
+ this.logger.info(
1318
+ `Machine '${machineId}' in app '${app}' was restarted`
1319
+ );
1320
+ } catch (error) {
1321
+ throw new Error(`[restart machine] something broke
1322
+ ${error}`);
1323
+ }
1324
+ },
1325
+ /**
1326
+ * Update a machine's per-machine configuration (env vars, etc.).
1327
+ *
1328
+ * Unlike `restart`, this creates a new machine version from the updated config
1329
+ * and forces a cold start — it does NOT resume from a suspended memory snapshot.
1330
+ *
1331
+ * @param app - The name of the application
1332
+ * @param machineId - The machine ID to update
1333
+ * @param options - Fields to update; env values set to `''` clear that var
1334
+ * @throws An error if the machine cannot be updated
1335
+ */
1336
+ update: async (app, machineId, options) => {
1337
+ try {
1338
+ await this.ensureInitialized();
1339
+ await this.updateMachine(app, machineId, options);
1340
+ this.logger.info(`Machine '${machineId}' in app '${app}' was updated`);
1341
+ } catch (error) {
1342
+ throw new Error(`[update machine] something broke
1343
+ ${error}`);
1344
+ }
1345
+ }
1346
+ };
722
1347
  postgres = {
723
1348
  detach: async (cluster, app) => {
724
1349
  await this.detachPostgres(cluster, app);
725
1350
  }
726
1351
  };
1352
+ /**
1353
+ * Run commands inside a running machine
1354
+ */
1355
+ ssh = {
1356
+ /**
1357
+ * Execute a command in a running machine and return its output.
1358
+ *
1359
+ * Requires a started machine - Fly cannot connect to a stopped or
1360
+ * suspended one. Use `machines.start` first when the app may be idle.
1361
+ *
1362
+ * The output is returned to the caller and not logged unless CLI tracing
1363
+ * is enabled, so it can be used to read values that are otherwise
1364
+ * write-only, such as secrets injected at deploy time.
1365
+ *
1366
+ * @param app - The name of the application
1367
+ * @param command - The command to run inside the machine
1368
+ * @returns The command output
1369
+ * @throws An error if there is no started machine or the command fails
1370
+ */
1371
+ exec: async (app, command) => {
1372
+ try {
1373
+ await this.ensureInitialized();
1374
+ return await this.sshExec(app, command);
1375
+ } catch (error) {
1376
+ throw new Error(`[ssh exec] something broke
1377
+ ${error}`);
1378
+ }
1379
+ }
1380
+ };
727
1381
  /**
728
1382
  * Manage application secrets
729
1383
  */
@@ -750,6 +1404,28 @@ ${error}`
750
1404
  );
751
1405
  }
752
1406
  },
1407
+ /**
1408
+ * Apply secrets that were staged with `set({ stage: true })`.
1409
+ *
1410
+ * Staging first and deploying afterwards lets a set of apps take a new
1411
+ * value together, instead of each restarting as its own secret is written.
1412
+ *
1413
+ * Fly needs a started machine to update, so an app whose machines are all
1414
+ * stopped or suspended has to be started before this will do anything.
1415
+ *
1416
+ * @param app - The name of the application
1417
+ * @throws An error if the staged secrets cannot be deployed
1418
+ */
1419
+ deploy: async (app) => {
1420
+ try {
1421
+ await this.ensureInitialized();
1422
+ await this.deployStagedSecrets(app);
1423
+ this.logger.info(`Staged secrets were deployed for '${app}'`);
1424
+ } catch (error) {
1425
+ throw new Error(`[deploy secrets] something broke
1426
+ ${error}`);
1427
+ }
1428
+ },
753
1429
  /**
754
1430
  * List secrets for an application or all secrets when options is 'all'
755
1431
  *
@@ -810,6 +1486,22 @@ ${error}`);
810
1486
  return null;
811
1487
  }
812
1488
  };
1489
+ //
1490
+ // DX friendly methods outside what Fly CLI provides
1491
+ //
1492
+ /**
1493
+ * Build a Docker image for an application and push it to the Fly registry
1494
+ * without deploying.
1495
+ *
1496
+ * The image reference is returned for use in a subsequent `deploy` that depends on it.
1497
+ *
1498
+ * Shorthand for `deploy({ ...options, buildOnly: true })`.
1499
+ *
1500
+ * @param options - Build options
1501
+ * @returns The app name and image reference for use in a subsequent `deploy`
1502
+ * @throws An error if the build fails or the image reference cannot be parsed
1503
+ */
1504
+ build = (options) => this.deploy({ ...options, buildOnly: true });
813
1505
  /**
814
1506
  * Get the extended details of an application
815
1507
  *
@@ -856,7 +1548,7 @@ ${error}`);
856
1548
  }
857
1549
  /**
858
1550
  * @private
859
- * @returns The name of the deployed application
1551
+ * @returns The app name and optional image reference (only set when buildOnly is true)
860
1552
  * @throws An error if the deployment fails
861
1553
  */
862
1554
  async deployApp(options) {
@@ -930,7 +1622,7 @@ ${error}`);
930
1622
  this.logger.info(`Updating existing application '${appName}'`);
931
1623
  }
932
1624
  NameSchema.parse(appName);
933
- if (options?.secrets) {
1625
+ if (!options?.buildOnly && options?.secrets) {
934
1626
  const existingSecrets = new Set(appSecrets.map(({ name }) => name));
935
1627
  const newSecrets = {};
936
1628
  for (const [key, value] of Object.entries(options.secrets)) {
@@ -957,7 +1649,7 @@ ${error}`);
957
1649
  );
958
1650
  appName = options.app;
959
1651
  }
960
- if (options?.postgres) {
1652
+ if (!options?.buildOnly && options?.postgres) {
961
1653
  const users = await this.fetchPostgresUsers(
962
1654
  options.postgres,
963
1655
  "nullOnError"
@@ -972,9 +1664,13 @@ ${error}`);
972
1664
  );
973
1665
  } else {
974
1666
  this.logger.info(
975
- `Attach Postgres cluster '${options.postgres}' to '${appName}'`
1667
+ `Attach Postgres cluster '${options.postgres}' to '${appName}'${options.databaseName ? ` with database '${options.databaseName}'` : ""}`
1668
+ );
1669
+ await this.attachPostgres(
1670
+ options.postgres,
1671
+ appName,
1672
+ options.databaseName
976
1673
  );
977
- await this.attachPostgres(options.postgres, appName);
978
1674
  }
979
1675
  }
980
1676
  const args = ["deploy", "--app", appName, "--config", deployConfig];
@@ -987,20 +1683,39 @@ ${error}`);
987
1683
  for (const [key, value] of Object.entries(options?.env || {})) {
988
1684
  args.push("--env", `${key}=${this.safeArg(value)}`);
989
1685
  }
1686
+ for (const [key, value] of Object.entries(options?.buildArgs || {})) {
1687
+ args.push("--build-arg", `${key}=${this.safeArg(value)}`);
1688
+ }
1689
+ if (options?.image) {
1690
+ args.push("--image", options.image);
1691
+ }
1692
+ if (options?.buildOnly) {
1693
+ args.push("--build-only", "--push");
1694
+ }
990
1695
  if (options?.optOutDepotBuilder) {
991
1696
  args.push("--depot=false");
992
1697
  }
993
1698
  args.push("--yes");
994
- this.logger.info(`Deploying '${appName}'...`);
995
- await this.execFly(args);
996
- return appName;
1699
+ this.logger.info(
1700
+ options?.buildOnly ? `Building image for '${appName}'...` : `Deploying '${appName}'...`
1701
+ );
1702
+ const output = await this.execFly(
1703
+ args,
1704
+ options?.buildOnly ? { streamStrategy: "combined" } : void 0
1705
+ );
1706
+ const imageRef = options?.buildOnly ? output?.match(/registry\.fly\.io\/\S+/)?.[0] : void 0;
1707
+ return { appName, imageRef };
997
1708
  }
998
1709
  /**
999
1710
  * @private
1000
1711
  * @throws An error if the Postgres database cannot be attached
1001
1712
  */
1002
- async attachPostgres(postgres, app) {
1003
- const args = ["postgres", "attach", postgres, "--app", app, "--yes"];
1713
+ async attachPostgres(postgres, app, databaseName) {
1714
+ const args = ["postgres", "attach", postgres, "--app", app];
1715
+ if (databaseName) {
1716
+ args.push("--database-name", databaseName);
1717
+ }
1718
+ args.push("--yes");
1004
1719
  await this.execFly(args);
1005
1720
  }
1006
1721
  /**
@@ -1087,6 +1802,68 @@ ${error}`);
1087
1802
  await this.execFly(args);
1088
1803
  return NameSchema.parse(status.name);
1089
1804
  }
1805
+ /**
1806
+ * @private
1807
+ * Deploy secrets previously staged for an application
1808
+ * @throws An error if the staged secrets cannot be deployed
1809
+ */
1810
+ async deployStagedSecrets(app) {
1811
+ const args = ["secrets", "deploy", "--app", app];
1812
+ await this.execFly(args);
1813
+ }
1814
+ /**
1815
+ * @private
1816
+ * Execute a command inside a running machine
1817
+ * @returns The command output
1818
+ * @throws An error if the command fails
1819
+ */
1820
+ async sshExec(app, command) {
1821
+ const args = ["ssh", "console", "--app", app, "--command", command];
1822
+ return await this.execFly(args);
1823
+ }
1824
+ /**
1825
+ * @private
1826
+ * Start a machine
1827
+ * @throws An error if the machine cannot be started
1828
+ */
1829
+ async startMachine(app, machineId) {
1830
+ const args = ["machine", "start", machineId, "--app", app];
1831
+ await this.execFly(args);
1832
+ }
1833
+ /**
1834
+ * @private
1835
+ * Stop a machine
1836
+ * @throws An error if the machine cannot be stopped
1837
+ */
1838
+ async stopMachine(app, machineId) {
1839
+ const args = ["machine", "stop", machineId, "--app", app];
1840
+ await this.execFly(args);
1841
+ }
1842
+ /**
1843
+ * @private
1844
+ * Restart a machine by stopping then starting it
1845
+ * @throws An error if the machine cannot be restarted
1846
+ */
1847
+ async restartMachine(app, machineId) {
1848
+ await this.stopMachine(app, machineId);
1849
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
1850
+ await this.startMachine(app, machineId);
1851
+ }
1852
+ /**
1853
+ * @private
1854
+ * Update a machine's per-machine config (env vars, etc.).
1855
+ * Creates a new machine version so the machine cold-starts from the updated config,
1856
+ * bypassing any suspended memory snapshot.
1857
+ * @throws An error if the machine cannot be updated
1858
+ */
1859
+ async updateMachine(app, machineId, options) {
1860
+ const args = ["machine", "update", machineId, "--app", app];
1861
+ for (const [key, value] of Object.entries(options.env || {})) {
1862
+ args.push("--env", `${key}=${this.safeArg(value)}`);
1863
+ }
1864
+ args.push("--yes");
1865
+ await this.execFly(args);
1866
+ }
1090
1867
  async fetchAllApps(onError) {
1091
1868
  const args = ["apps", "list", "--json"];
1092
1869
  try {
@@ -1166,7 +1943,7 @@ ${error}`);
1166
1943
  if (onError === "throwOnError") {
1167
1944
  throw error;
1168
1945
  }
1169
- if (error instanceof import_zod30.ZodError) {
1946
+ if (error instanceof import_zod36.ZodError) {
1170
1947
  this.logger.info(`Failed to parse response:
1171
1948
  ${error.message}`);
1172
1949
  this.logger.info(`Raw response:
@@ -1241,9 +2018,23 @@ ${JSON.stringify(response, null, 2)}`);
1241
2018
  * @private
1242
2019
  * Save remote config to a local file
1243
2020
  *
2021
+ * Two things flyctl expects that a first-time caller would not: the output
2022
+ * format is no longer sniffed from the path's extension — `--json`/`--yaml`
2023
+ * has to be passed, TOML being what is left over when neither is — and the
2024
+ * destination must already exist as a parseable file of that format, or
2025
+ * `flyctl` refuses to write to it at all, mistaking "does not exist yet"
2026
+ * for "path is wrong". A fresh, empty seed of the right shape satisfies
2027
+ * that read without affecting what gets written back over it.
2028
+ *
1244
2029
  * @throws An error if the config cannot be saved
1245
2030
  */
1246
2031
  async saveConfig(options) {
2032
+ const isJson = options.config.endsWith(".json");
2033
+ const isYaml = /\.ya?ml$/.test(options.config);
2034
+ if (!(0, import_fs.existsSync)(options.config)) {
2035
+ (0, import_fs.mkdirSync)((0, import_path.dirname)(options.config), { recursive: true });
2036
+ (0, import_fs.writeFileSync)(options.config, isJson ? "{}" : "");
2037
+ }
1247
2038
  const args = [
1248
2039
  "config",
1249
2040
  "save",
@@ -1251,6 +2042,7 @@ ${JSON.stringify(response, null, 2)}`);
1251
2042
  options.app,
1252
2043
  "--config",
1253
2044
  options.config,
2045
+ ...isJson ? ["--json"] : isYaml ? ["--yaml"] : [],
1254
2046
  "--yes"
1255
2047
  ];
1256
2048
  await this.execFly(args);
@@ -1280,6 +2072,12 @@ ${JSON.stringify(response, null, 2)}`);
1280
2072
  }
1281
2073
  async execFly(command, options, onError = "throwOnError") {
1282
2074
  const args = Array.isArray(command) ? command : command.split(" ");
2075
+ if (this.logger.verbose) {
2076
+ args.push("--verbose");
2077
+ }
2078
+ if (this.logger.debug) {
2079
+ args.push("--debug");
2080
+ }
1283
2081
  const flyCmd = "flyctl";
1284
2082
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
1285
2083
  let output = "";
@@ -1289,11 +2087,17 @@ ${JSON.stringify(response, null, 2)}`);
1289
2087
  output = await spawnPty(flyCmd, args, { prompt: options.prompt });
1290
2088
  this.traceCLI("RESULT", output);
1291
2089
  } else {
1292
- const result = await spawn(flyCmd, args, options);
1293
- output = result.stdout.trim();
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();
1294
2096
  const stderr = result.stderr.trim();
1295
- this.traceCLI("RESULT", `${output}${stderr ? `
2097
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
1296
2098
  ${stderr}` : ""}`);
2099
+ output = streamStrategy === "combined" ? `${stdout}
2100
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
1297
2101
  }
1298
2102
  } catch (error) {
1299
2103
  const errorMsg = error.message;
@@ -1464,5 +2268,13 @@ ${errorMsg}`);
1464
2268
  };
1465
2269
  // Annotate the CommonJS export names for ESM import in node:
1466
2270
  0 && (module.exports = {
1467
- Fly
2271
+ CertificateApiResponseSchema,
2272
+ CertificateListApiResponseSchema,
2273
+ DnsInstructionsSchema,
2274
+ Fly,
2275
+ FlyApi,
2276
+ FlyApiError,
2277
+ HostnameCheckApiResponseSchema,
2278
+ MachineApiResponseSchema,
2279
+ MachineListApiResponseSchema
1468
2280
  });