@cdwr/fly-node 0.2.3 → 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_zod28 = 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,87 +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(),
212
- organization: import_zod5.z.object({
213
- id: import_zod5.z.string(),
214
- name: import_zod5.z.string()
215
- })
704
+ import_zod10.z.object({
705
+ id: import_zod10.z.string(),
706
+ name: import_zod10.z.string()
216
707
  })
217
708
  );
218
709
 
219
710
  // packages/fly-node/src/lib/schemas/apps-list.schema.ts
220
- var import_zod7 = require("zod");
221
- var AppsListTransformedResponseSchema = import_zod7.z.array(
711
+ var import_zod12 = require("zod");
712
+ var AppsListTransformedResponseSchema = import_zod12.z.array(
222
713
  withCamelCase(
223
- import_zod7.z.object({
224
- id: import_zod7.z.string(),
225
- name: import_zod7.z.string(),
226
- status: import_zod7.z.string(),
227
- deployed: import_zod7.z.boolean(),
228
- hostname: import_zod7.z.string(),
229
- organization: import_zod7.z.object({
230
- name: import_zod7.z.string(),
231
- 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()
232
723
  }),
233
- currentRelease: import_zod7.z.nullable(
234
- import_zod7.z.object({
235
- status: import_zod7.z.string(),
236
- 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()
237
728
  })
238
729
  )
239
730
  })
240
731
  )
241
732
  );
242
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
+
243
741
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
244
- var import_zod11 = require("zod");
742
+ var import_zod17 = require("zod");
245
743
 
246
744
  // packages/fly-node/src/lib/schemas/certs-list.schema.ts
247
- var import_zod9 = require("zod");
248
- var CertsListFlyResponseElementSchema = import_zod9.z.object({
249
- createdAt: import_zod9.z.string().datetime(),
250
- hostname: import_zod9.z.string(),
251
- 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()
252
750
  });
253
- var CertsListTransformedResponseSchema = import_zod9.z.array(
751
+ var CertsListTransformedResponseSchema = import_zod15.z.array(
254
752
  withCamelCase(CertsListFlyResponseElementSchema)
255
753
  );
256
754
 
257
755
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
258
- var CertsListWithAppTransformedResponseSchema = import_zod11.z.array(
756
+ var CertsListWithAppTransformedResponseSchema = import_zod17.z.array(
259
757
  withCamelCase(
260
758
  CertsListFlyResponseElementSchema.extend({
261
- app: import_zod11.z.string()
759
+ app: import_zod17.z.string()
262
760
  })
263
761
  )
264
762
  );
265
763
 
266
764
  // packages/fly-node/src/lib/schemas/config-show.schema.ts
267
- var import_zod13 = require("zod");
765
+ var import_zod19 = require("zod");
268
766
  var ConfigShowResponseSchema = withCamelCase(
269
- import_zod13.z.object({
270
- app: import_zod13.z.string(),
271
- primaryRegion: import_zod13.z.string().optional(),
272
- build: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any()).optional().or(
273
- import_zod13.z.object({
274
- args: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.string()).optional(),
275
- dockerfile: import_zod13.z.string().optional(),
276
- 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()
277
775
  })
278
776
  ),
279
- 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() })),
280
- env: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.string()).optional(),
281
- httpService: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any()).optional(),
282
- mounts: import_zod13.z.record(import_zod13.z.string(), import_zod13.z.any()).optional(),
283
- 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()
284
782
  }),
285
783
  {
286
784
  preserve: ["build.args", "env"]
@@ -288,120 +786,135 @@ var ConfigShowResponseSchema = withCamelCase(
288
786
  );
289
787
 
290
788
  // packages/fly-node/src/lib/schemas/deploy.schema.ts
291
- var import_zod14 = require("zod");
292
- var DeployResponseSchema = import_zod14.z.object({
293
- app: import_zod14.z.string(),
294
- hostname: import_zod14.z.string(),
295
- 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()
296
794
  });
297
795
 
298
796
  // packages/fly-node/src/lib/schemas/helper-schemas.ts
299
- var import_zod15 = require("zod");
300
- var AllowEmptyUrlSchema = import_zod15.z.string().url().or(import_zod15.z.literal(""));
301
- 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-]+$/);
302
800
 
303
801
  // packages/fly-node/src/lib/schemas/postgres-list.ts
304
- var import_zod17 = require("zod");
305
- var PostgresListTransformedResponseSchema = import_zod17.z.array(
802
+ var import_zod23 = require("zod");
803
+ var PostgresListTransformedResponseSchema = import_zod23.z.array(
306
804
  withCamelCase(
307
- import_zod17.z.object({
308
- deployed: import_zod17.z.boolean(),
309
- hostname: import_zod17.z.string(),
310
- id: import_zod17.z.string(),
311
- name: import_zod17.z.string(),
312
- organization: import_zod17.z.object({ id: import_zod17.z.string(), slug: import_zod17.z.string() }),
313
- status: import_zod17.z.string(),
314
- 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()
315
813
  })
316
814
  )
317
- );
815
+ ).or(import_zod23.z.string());
318
816
 
319
817
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
320
- var import_zod19 = require("zod");
321
- var PostgresUsersListTransformedResponseSchema = import_zod19.z.array(
818
+ var import_zod25 = require("zod");
819
+ var PostgresUsersListTransformedResponseSchema = import_zod25.z.array(
322
820
  withCamelCase(
323
- import_zod19.z.object({
324
- username: import_zod19.z.string(),
325
- superuser: import_zod19.z.boolean(),
326
- 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())
327
825
  })
328
826
  )
329
827
  );
330
828
 
331
829
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
332
- var import_zod23 = require("zod");
830
+ var import_zod29 = require("zod");
333
831
 
334
832
  // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
335
- var import_zod21 = require("zod");
336
- var SecretsListFlyResponseElementSchema = import_zod21.z.object({
337
- name: import_zod21.z.string(),
338
- digest: import_zod21.z.string(),
339
- createdAt: import_zod21.z.string().datetime()
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()
340
837
  });
341
- var SecretsListTransformedResponseSchema = import_zod21.z.array(
838
+ var SecretsListTransformedResponseSchema = import_zod27.z.array(
342
839
  withCamelCase(SecretsListFlyResponseElementSchema)
343
840
  );
344
841
 
345
842
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
346
- var SecretsListWithAppTransformedResponseSchema = import_zod23.z.array(
843
+ var SecretsListWithAppTransformedResponseSchema = import_zod29.z.array(
347
844
  withCamelCase(
348
845
  SecretsListFlyResponseElementSchema.extend({
349
- app: import_zod23.z.string()
846
+ app: import_zod29.z.string()
350
847
  })
351
848
  )
352
849
  );
353
850
 
354
851
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
355
- var import_zod27 = require("zod");
852
+ var import_zod33 = require("zod");
356
853
 
357
854
  // packages/fly-node/src/lib/schemas/status.schema.ts
358
- var import_zod25 = require("zod");
359
- var statusFlyResponseSchema = import_zod25.z.object({
360
- deployed: import_zod25.z.boolean(),
361
- hostname: import_zod25.z.string(),
362
- id: import_zod25.z.string(),
363
- machines: import_zod25.z.array(
364
- import_zod25.z.object({
365
- id: import_zod25.z.string(),
366
- name: import_zod25.z.string(),
367
- state: import_zod25.z.string(),
368
- region: import_zod25.z.string(),
369
- createdAt: import_zod25.z.string().datetime(),
370
- updatedAt: import_zod25.z.string().datetime(),
371
- config: import_zod25.z.object({
372
- env: import_zod25.z.record(import_zod25.z.string()),
373
- 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()
374
872
  }),
375
- events: import_zod25.z.array(
376
- import_zod25.z.object({
377
- type: import_zod25.z.string(),
378
- status: import_zod25.z.string(),
379
- timestamp: import_zod25.z.number()
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()
883
+ }),
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()
380
889
  })
381
890
  ),
382
- checks: import_zod25.z.array(
383
- import_zod25.z.object({
384
- name: import_zod25.z.string(),
385
- status: import_zod25.z.string(),
386
- output: import_zod25.z.string(),
387
- 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()
388
897
  })
389
898
  ).optional(),
390
- hostStatus: import_zod25.z.string()
899
+ hostStatus: import_zod31.z.string()
391
900
  })
392
901
  ),
393
- name: import_zod25.z.string(),
394
- organization: import_zod25.z.object({
395
- id: import_zod25.z.string(),
396
- 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()
397
906
  }),
398
- status: import_zod25.z.string(),
399
- version: import_zod25.z.number()
907
+ status: import_zod31.z.string(),
908
+ version: import_zod31.z.number()
400
909
  });
401
910
  var StatusTransformedResponseSchema = withCamelCase(
402
911
  statusFlyResponseSchema,
403
912
  {
404
- preserve: ["machines.config.env", "machines.config.metadata"],
913
+ preserve: [
914
+ "machines.config.env",
915
+ "machines.config.metadata",
916
+ "machines.config.guest"
917
+ ],
405
918
  specialCases: { AppURL: "appUrl" }
406
919
  }
407
920
  );
@@ -409,23 +922,37 @@ var StatusTransformedResponseSchema = withCamelCase(
409
922
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
410
923
  var StatusExtendedTransformedResponseSchema = withCamelCase(
411
924
  statusFlyResponseSchema.extend({
412
- domains: import_zod27.z.array(import_zod27.z.object({ hostname: import_zod27.z.string() })),
413
- 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() }))
414
927
  }),
415
928
  {
416
- preserve: ["machines.config.env", "machines.config.metadata"]
929
+ preserve: [
930
+ "machines.config.env",
931
+ "machines.config.metadata",
932
+ "machines.config.guest"
933
+ ]
417
934
  }
418
935
  );
419
936
 
937
+ // packages/fly-node/src/lib/schemas/version.schema.ts
938
+ var import_zod35 = require("zod");
939
+ var VersionTransformedResponseSchema = withCamelCase(
940
+ import_zod35.z.object({
941
+ name: import_zod35.z.string(),
942
+ version: import_zod35.z.string(),
943
+ commit: import_zod35.z.string(),
944
+ branchName: import_zod35.z.string(),
945
+ buildDate: import_zod35.z.string().datetime(),
946
+ os: import_zod35.z.string(),
947
+ architecture: import_zod35.z.string(),
948
+ environment: import_zod35.z.string()
949
+ })
950
+ );
951
+
420
952
  // packages/fly-node/src/lib/fly.class.ts
421
953
  var Fly = class {
422
954
  /** Use underscore to avoid conflict with public `config` property */
423
955
  _config;
424
- /**
425
- * Whether a user is authenticated via local login.
426
- * In this case a token is not needed, though it can still have been provided.
427
- */
428
- authByLogin = false;
429
956
  initialized = false;
430
957
  logger;
431
958
  /**
@@ -451,10 +978,14 @@ var Fly = class {
451
978
  this.logger = {
452
979
  info: config?.logger?.info || console.log,
453
980
  error: config?.logger?.error || console.error,
454
- traceCLI: config?.logger?.traceCLI || false
981
+ traceCLI: config?.logger?.traceCLI ?? false,
982
+ redactSecrets: config?.logger?.redactSecrets ?? true,
983
+ verbose: config?.logger?.verbose ?? false,
984
+ debug: config?.logger?.debug ?? false,
985
+ streamToConsole: config?.logger?.streamToConsole ?? false
455
986
  };
456
- if (!this._config.token) {
457
- this._config.token = process.env["FLY_API_TOKEN"] || "";
987
+ if (this._config.token) {
988
+ process.env["FLY_ACCESS_TOKEN"] = this._config.token;
458
989
  }
459
990
  }
460
991
  /**
@@ -490,7 +1021,21 @@ ${error}`);
490
1021
  *
491
1022
  * @returns `true` if the Fly CLI tool is installed, `false` otherwise
492
1023
  */
493
- isInstalled: async () => await this.isInstalled()
1024
+ isInstalled: async () => await this.isInstalled(),
1025
+ /**
1026
+ * Get version information about the installed Fly CLI
1027
+ *
1028
+ * @returns The installed Fly CLI version information
1029
+ * @throws An error if the version cannot be retrieved
1030
+ */
1031
+ version: async () => {
1032
+ try {
1033
+ return await this.version();
1034
+ } catch (error) {
1035
+ throw new Error(`[version] something broke
1036
+ ${error}`);
1037
+ }
1038
+ }
494
1039
  };
495
1040
  //
496
1041
  // External API following the `flyctl` CLI commands structure
@@ -509,9 +1054,9 @@ ${error}`);
509
1054
  create: async (options) => {
510
1055
  try {
511
1056
  await this.ensureInitialized();
512
- const { name } = await this.createApp(options);
513
- this.logger.info(`Application '${name}' was created`);
514
- return name;
1057
+ const response = await this.createApp(options);
1058
+ this.logger.info(`Application '${response.name}' was created`);
1059
+ return response;
515
1060
  } catch (error) {
516
1061
  throw new Error(
517
1062
  `[create app] something broke, check your apps
@@ -523,10 +1068,9 @@ ${error}`
523
1068
  * Destroy an application and make sure it gets detached from any Postgres clusters
524
1069
  *
525
1070
  * @param app - The name of the app to destroy
526
- * @param options - Options for destroying an application
527
1071
  * @throws An error if the app cannot be destroyed
528
1072
  */
529
- destroy: async (app, options) => {
1073
+ destroy: async (app) => {
530
1074
  try {
531
1075
  await this.ensureInitialized();
532
1076
  const attachedClusters = await this.getAttachedPostgresClusters(app);
@@ -537,7 +1081,7 @@ ${error}`
537
1081
  const output = await this.detachPostgres(cluster, app);
538
1082
  this.logger.info(output);
539
1083
  }
540
- await this.destroyApp(app, options?.force);
1084
+ await this.destroyApp(app);
541
1085
  this.logger.info(`Application '${app}' was destroyed`);
542
1086
  } catch (error) {
543
1087
  throw new Error(
@@ -629,6 +1173,27 @@ ${error}`
629
1173
  * Manage an app's configuration
630
1174
  */
631
1175
  config = {
1176
+ /**
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.
1181
+ *
1182
+ * @param options - Options for saving an application's configuration
1183
+ * @throws An error if the configuration cannot be saved
1184
+ */
1185
+ save: async (options) => {
1186
+ try {
1187
+ await this.ensureInitialized();
1188
+ await this.saveConfig(options);
1189
+ this.logger.info(
1190
+ `Configuration for '${options.app}' was saved to '${options.config}'`
1191
+ );
1192
+ } catch (error) {
1193
+ throw new Error(`[save config] something broke
1194
+ ${error}`);
1195
+ }
1196
+ },
632
1197
  /**
633
1198
  * Show an application's configuration.
634
1199
  *
@@ -647,7 +1212,12 @@ ${error}`);
647
1212
  }
648
1213
  };
649
1214
  /**
650
- * 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.
651
1221
  *
652
1222
  * A valid config file is required but the app doesn't have to exist,
653
1223
  * since it gets created if needed.
@@ -657,15 +1227,28 @@ ${error}`);
657
1227
  * 2. Instance app name
658
1228
  * 3. App name from the provided config file
659
1229
  *
660
- * Existing secrets are preserved.
661
- *
662
- * @param options - Options for deploying an application
663
- * @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
664
1233
  */
665
1234
  deploy = async (options) => {
1235
+ const isBuildOnly = options?.buildOnly === true;
666
1236
  try {
667
1237
  await this.ensureInitialized();
668
- 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);
669
1252
  this.logger.info(`Application '${appName}' was deployed`);
670
1253
  const status = await this.fetchAppStatus("throwOnError", {
671
1254
  app: appName
@@ -677,16 +1260,124 @@ ${error}`);
677
1260
  });
678
1261
  } catch (error) {
679
1262
  throw new Error(
680
- `[deploy] something broke, check your deployments
1263
+ `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
681
1264
  ${error}`
682
1265
  );
683
1266
  }
684
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
+ };
685
1347
  postgres = {
686
1348
  detach: async (cluster, app) => {
687
1349
  await this.detachPostgres(cluster, app);
688
1350
  }
689
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
+ };
690
1381
  /**
691
1382
  * Manage application secrets
692
1383
  */
@@ -714,7 +1405,29 @@ ${error}`
714
1405
  }
715
1406
  },
716
1407
  /**
717
- * List secrets for an application
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
+ },
1429
+ /**
1430
+ * List secrets for an application or all secrets when options is 'all'
718
1431
  *
719
1432
  * @param options - List secrets for an application or all secrets
720
1433
  * @returns A list of secrets
@@ -773,6 +1486,22 @@ ${error}`);
773
1486
  return null;
774
1487
  }
775
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 });
776
1505
  /**
777
1506
  * Get the extended details of an application
778
1507
  *
@@ -819,14 +1548,15 @@ ${error}`);
819
1548
  }
820
1549
  /**
821
1550
  * @private
822
- * @returns The name of the deployed application
1551
+ * @returns The app name and optional image reference (only set when buildOnly is true)
823
1552
  * @throws An error if the deployment fails
824
1553
  */
825
1554
  async deployApp(options) {
826
1555
  let appName = "";
827
1556
  let appSecrets = [];
1557
+ let deployConfig = options?.config || this.instanceConfig;
828
1558
  let lookupApp = options?.app || this.instanceApp;
829
- const lookupConfig = options?.config || this.instanceConfig;
1559
+ const lookupConfig = deployConfig;
830
1560
  if (!lookupConfig) {
831
1561
  throw new Error(
832
1562
  "Fly config file must be provided to options or class instance, unable to deploy"
@@ -859,6 +1589,26 @@ ${error}`);
859
1589
  );
860
1590
  }
861
1591
  }
1592
+ if (options?.preferRemoteConfig && appName) {
1593
+ const remoteConfigPath = (0, import_path.join)(
1594
+ (0, import_path.dirname)(lookupConfig),
1595
+ `fly.${appName}.toml`
1596
+ );
1597
+ try {
1598
+ await this.saveConfig({
1599
+ app: appName,
1600
+ config: remoteConfigPath
1601
+ });
1602
+ deployConfig = remoteConfigPath;
1603
+ this.logger.info(
1604
+ `Using remote config for existing app '${appName}' (saved to ${remoteConfigPath})`
1605
+ );
1606
+ } catch (error) {
1607
+ this.logger.info(
1608
+ `Failed to save remote config, will use local config: ${error}`
1609
+ );
1610
+ }
1611
+ }
862
1612
  if (!appName) {
863
1613
  this.logger.info("Creating a new application...");
864
1614
  const { name } = await this.createApp({
@@ -872,7 +1622,7 @@ ${error}`);
872
1622
  this.logger.info(`Updating existing application '${appName}'`);
873
1623
  }
874
1624
  NameSchema.parse(appName);
875
- if (options?.secrets) {
1625
+ if (!options?.buildOnly && options?.secrets) {
876
1626
  const existingSecrets = new Set(appSecrets.map(({ name }) => name));
877
1627
  const newSecrets = {};
878
1628
  for (const [key, value] of Object.entries(options.secrets)) {
@@ -899,7 +1649,7 @@ ${error}`);
899
1649
  );
900
1650
  appName = options.app;
901
1651
  }
902
- if (options?.postgres) {
1652
+ if (!options?.buildOnly && options?.postgres) {
903
1653
  const users = await this.fetchPostgresUsers(
904
1654
  options.postgres,
905
1655
  "nullOnError"
@@ -914,12 +1664,16 @@ ${error}`);
914
1664
  );
915
1665
  } else {
916
1666
  this.logger.info(
917
- `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
918
1673
  );
919
- await this.attachPostgres(options.postgres, appName);
920
1674
  }
921
1675
  }
922
- const args = ["deploy", "--app", appName, "--config", lookupConfig];
1676
+ const args = ["deploy", "--app", appName, "--config", deployConfig];
923
1677
  if (options?.region) {
924
1678
  args.push("--region", options.region);
925
1679
  }
@@ -929,30 +1683,47 @@ ${error}`);
929
1683
  for (const [key, value] of Object.entries(options?.env || {})) {
930
1684
  args.push("--env", `${key}=${this.safeArg(value)}`);
931
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
+ }
932
1695
  if (options?.optOutDepotBuilder) {
933
1696
  args.push("--depot=false");
934
1697
  }
935
1698
  args.push("--yes");
936
- this.logger.info(`Deploying '${appName}'...`);
937
- await this.execFly(args);
938
- 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 };
939
1708
  }
940
1709
  /**
941
1710
  * @private
942
1711
  * @throws An error if the Postgres database cannot be attached
943
1712
  */
944
- async attachPostgres(postgres, app) {
945
- 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");
946
1719
  await this.execFly(args);
947
1720
  }
948
1721
  /**
949
1722
  * @private
950
1723
  * @throws An error if the app cannot be destroyed
951
1724
  */
952
- async destroyApp(app, force) {
1725
+ async destroyApp(app) {
953
1726
  const args = ["apps", "destroy", app, "--yes"];
954
- if (force)
955
- args.push("--force");
956
1727
  await this.execFly(args);
957
1728
  }
958
1729
  /**
@@ -1031,6 +1802,68 @@ ${error}`);
1031
1802
  await this.execFly(args);
1032
1803
  return NameSchema.parse(status.name);
1033
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
+ }
1034
1867
  async fetchAllApps(onError) {
1035
1868
  const args = ["apps", "list", "--json"];
1036
1869
  try {
@@ -1066,7 +1899,11 @@ ${error}`);
1066
1899
  const args = ["postgres", "list", "--json"];
1067
1900
  try {
1068
1901
  const response = await this.execFly(args);
1069
- return PostgresListTransformedResponseSchema.parse(response);
1902
+ const parsed = PostgresListTransformedResponseSchema.safeParse(response);
1903
+ if (parsed.success) {
1904
+ return Array.isArray(parsed.data) ? parsed.data : [];
1905
+ }
1906
+ throw parsed.error;
1070
1907
  } catch (error) {
1071
1908
  if (onError === "throwOnError") {
1072
1909
  throw error;
@@ -1106,7 +1943,7 @@ ${error}`);
1106
1943
  if (onError === "throwOnError") {
1107
1944
  throw error;
1108
1945
  }
1109
- if (error instanceof import_zod28.ZodError) {
1946
+ if (error instanceof import_zod36.ZodError) {
1110
1947
  this.logger.info(`Failed to parse response:
1111
1948
  ${error.message}`);
1112
1949
  this.logger.info(`Raw response:
@@ -1177,11 +2014,44 @@ ${JSON.stringify(response, null, 2)}`);
1177
2014
  return null;
1178
2015
  }
1179
2016
  }
2017
+ /**
2018
+ * @private
2019
+ * Save remote config to a local file
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
+ *
2029
+ * @throws An error if the config cannot be saved
2030
+ */
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
+ }
2038
+ const args = [
2039
+ "config",
2040
+ "save",
2041
+ "--app",
2042
+ options.app,
2043
+ "--config",
2044
+ options.config,
2045
+ ...isJson ? ["--json"] : isYaml ? ["--yaml"] : [],
2046
+ "--yes"
2047
+ ];
2048
+ await this.execFly(args);
2049
+ }
1180
2050
  /**
1181
2051
  * @private
1182
2052
  * Ensure Fly CLI is installed and authenticated
1183
2053
  *
1184
- * @throws An error if Fly CLI is not installed or authentication fails
2054
+ * @throws An error if Fly CLI is not installed or not authenticated
1185
2055
  */
1186
2056
  async ensureInitialized() {
1187
2057
  if (this.initialized)
@@ -1190,31 +2060,23 @@ ${JSON.stringify(response, null, 2)}`);
1190
2060
  if (!await this.isInstalled()) {
1191
2061
  throw new Error("Fly CLI must be installed to use this library");
1192
2062
  }
1193
- this.logger.info("Authenticating with Fly.io...");
1194
- let user = await this.execFly(
1195
- ["auth", "whoami"],
1196
- void 0,
1197
- "nullOnError",
1198
- true
1199
- // won't use token
1200
- );
1201
- if (user) {
1202
- this.logger.info(`Detected logged in user '${user}'`);
1203
- this.authByLogin = true;
1204
- } else {
1205
- user = await this.execFly(["auth", "whoami"]);
1206
- this.logger.info(`Authenticated by token as '${user}'`);
1207
- }
2063
+ const { version } = await this.version();
2064
+ this.logger.info(`Fly CLI ${version} is installed`);
2065
+ const user = await this.execFly(["auth", "whoami"]);
2066
+ this.logger.info(`Authenticated as '${user}'`);
1208
2067
  this.initialized = true;
1209
2068
  } catch (error) {
1210
2069
  this.logger.error("Failed to initialize Fly");
1211
2070
  throw error;
1212
2071
  }
1213
2072
  }
1214
- async execFly(command, options, onError = "throwOnError", skipToken) {
2073
+ async execFly(command, options, onError = "throwOnError") {
1215
2074
  const args = Array.isArray(command) ? command : command.split(" ");
1216
- if (!skipToken && !this.authByLogin && this._config.token) {
1217
- args.push("--access-token", this._config.token);
2075
+ if (this.logger.verbose) {
2076
+ args.push("--verbose");
2077
+ }
2078
+ if (this.logger.debug) {
2079
+ args.push("--debug");
1218
2080
  }
1219
2081
  const flyCmd = "flyctl";
1220
2082
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
@@ -1225,11 +2087,17 @@ ${JSON.stringify(response, null, 2)}`);
1225
2087
  output = await spawnPty(flyCmd, args, { prompt: options.prompt });
1226
2088
  this.traceCLI("RESULT", output);
1227
2089
  } else {
1228
- const result = await spawn(flyCmd, args, options);
1229
- 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();
1230
2096
  const stderr = result.stderr.trim();
1231
- this.traceCLI("RESULT", `${output}${stderr ? `
2097
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
1232
2098
  ${stderr}` : ""}`);
2099
+ output = streamStrategy === "combined" ? `${stdout}
2100
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
1233
2101
  }
1234
2102
  } catch (error) {
1235
2103
  const errorMsg = error.message;
@@ -1319,6 +2187,18 @@ ${errorMsg}`);
1319
2187
  async isInstalled() {
1320
2188
  return await this.execFly("version", void 0, "nullOnError") !== null;
1321
2189
  }
2190
+ /**
2191
+ * @private
2192
+ * Get the installed Fly CLI version
2193
+ *
2194
+ * @returns The installed Fly CLI version information
2195
+ * @throws An error if the version cannot be retrieved
2196
+ */
2197
+ async version() {
2198
+ return VersionTransformedResponseSchema.parse(
2199
+ await this.execFly(["version", "--json"])
2200
+ );
2201
+ }
1322
2202
  /**
1323
2203
  * @private
1324
2204
  * Normalize the options matching `AppOrConfig` type.
@@ -1345,21 +2225,56 @@ ${errorMsg}`);
1345
2225
  safeArg(arg) {
1346
2226
  return arg.replace(/\\/g, "\\\\").replace(/ /g, "\\ ");
1347
2227
  }
2228
+ /**
2229
+ * @private
2230
+ * Redact sensitive values from text.
2231
+ *
2232
+ * Identifies and redacts:
2233
+ * - Secret values provided with `secrets set KEY1=VALUE1 KEY2=VALUE2 ...`
2234
+ *
2235
+ * @param text - The text to redact
2236
+ * @returns The redacted text
2237
+ */
2238
+ redactSensitiveData(text) {
2239
+ const maskValue = (value) => value.length > 10 ? `${value.slice(0, 3)}[REDACTED]${value.slice(-3)}` : "[REDACTED]";
2240
+ const valuePattern = "((?:\\\\ |\\S)+)";
2241
+ return text.replace(
2242
+ new RegExp(
2243
+ `(secrets\\s+set\\s+.*?)([A-Z_][A-Z0-9_]*)=${valuePattern}`,
2244
+ "g"
2245
+ ),
2246
+ (_, prefix, key, value) => `${prefix}${key}=${maskValue(value)}`
2247
+ );
2248
+ }
1348
2249
  /**
1349
2250
  * @private
1350
2251
  * Trace the CLI calls, mocks and results
1351
2252
  *
2253
+ * Redacts sensitive data from CALL messages when enabled in logger config.
2254
+ *
1352
2255
  * @param type - The type of trace
1353
2256
  * @param msg - The message to trace
1354
2257
  */
1355
2258
  traceCLI(type, msg) {
1356
2259
  if (this.logger.traceCLI) {
1357
2260
  const typeLabel = type === "CALL" ? " CALL " : type === "MOCK" ? " MOCK " : "RESULT";
1358
- this.logger.info(`[${typeLabel}] ${msg}`);
2261
+ let message = msg;
2262
+ if (type === "CALL" && this.logger.redactSecrets && msg) {
2263
+ message = this.redactSensitiveData(msg);
2264
+ }
2265
+ this.logger.info(`[${typeLabel}] ${message}`);
1359
2266
  }
1360
2267
  }
1361
2268
  };
1362
2269
  // Annotate the CommonJS export names for ESM import in node:
1363
2270
  0 && (module.exports = {
1364
- Fly
2271
+ CertificateApiResponseSchema,
2272
+ CertificateListApiResponseSchema,
2273
+ DnsInstructionsSchema,
2274
+ Fly,
2275
+ FlyApi,
2276
+ FlyApiError,
2277
+ HostnameCheckApiResponseSchema,
2278
+ MachineApiResponseSchema,
2279
+ MachineListApiResponseSchema
1365
2280
  });