@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.js CHANGED
@@ -1,47 +1,528 @@
1
+ // packages/fly-node/src/lib/schemas/certificate.schema.ts
2
+ import { z } from "zod";
3
+ var CertificateApiResponseSchema = z.object({
4
+ hostname: z.string(),
5
+ /** Issued and serving. This is what decides whether a domain is usable */
6
+ isConfigured: z.boolean(),
7
+ id: z.string().optional(),
8
+ /** The apex or a subdomain — apex domains cannot use a CNAME */
9
+ isApex: z.boolean().optional(),
10
+ isWildcard: z.boolean().optional(),
11
+ /** Which ACME challenge has been satisfied, if any */
12
+ isAcmeDnsConfigured: z.boolean().optional(),
13
+ isAcmeAlpnConfigured: z.boolean().optional(),
14
+ isAcmeHttpConfigured: z.boolean().optional(),
15
+ certificateAuthority: z.string().nullish(),
16
+ certificateRequestedAt: z.string().nullish(),
17
+ createdAt: z.string().nullish(),
18
+ domain: z.string().nullish(),
19
+ dnsProvider: z.string().nullish(),
20
+ /** Hostname the validation record must be created on */
21
+ dnsValidationHostname: z.string().nullish(),
22
+ /** Value that record must contain */
23
+ dnsValidationTarget: z.string().nullish(),
24
+ /** Fly's own prose describing the records to create */
25
+ dnsValidationInstructions: z.string().nullish(),
26
+ /** Fly's summary of where issuance has got to */
27
+ clientStatus: z.string().nullish(),
28
+ /**
29
+ * Set when Let's Encrypt has rate-limited further attempts for this domain.
30
+ *
31
+ * Worth surfacing rather than swallowing: it is the one failure a customer
32
+ * cannot fix by correcting DNS, and retrying only makes it worse.
33
+ */
34
+ rateLimitedUntil: z.string().nullish(),
35
+ source: z.string().nullish(),
36
+ /**
37
+ * Fly's own prose for a failed issuance attempt — what the dashboard shows,
38
+ * unlike `HostnameCheck.errors`, which is SCREAMING_SNAKE_CASE codes
39
+ */
40
+ validationErrors: z.array(
41
+ z.object({
42
+ message: z.string(),
43
+ timestamp: z.string()
44
+ })
45
+ ).nullish(),
46
+ /**
47
+ * The certificates actually issued for this hostname, once any have been.
48
+ *
49
+ * A connection rather than a list because that is how Fly models it. Two
50
+ * nodes is the normal count — one RSA and one ECDSA — sharing an expiry,
51
+ * which is why a caller usually wants the expiry rather than the rows.
52
+ */
53
+ issued: z.object({
54
+ nodes: z.array(
55
+ z.object({
56
+ id: z.string().nullish(),
57
+ /** Key type, e.g. `RSA` or `ECDSA` */
58
+ type: z.string().nullish(),
59
+ hostname: z.string().nullish(),
60
+ expiresAt: z.string().nullish()
61
+ })
62
+ ).nullish()
63
+ }).nullish()
64
+ });
65
+ var HostnameCheckApiResponseSchema = z.object({
66
+ aRecords: z.array(z.string()).nullish(),
67
+ aaaaRecords: z.array(z.string()).nullish(),
68
+ cnameRecords: z.array(z.string()).nullish(),
69
+ caaRecords: z.array(z.string()).nullish(),
70
+ soa: z.string().nullish(),
71
+ dnsProvider: z.string().nullish(),
72
+ dnsVerificationRecord: z.string().nullish(),
73
+ dnsConfigured: z.boolean().nullish(),
74
+ acmeDnsConfigured: z.boolean().nullish(),
75
+ resolvedAddresses: z.array(z.string()).nullish(),
76
+ isProxied: z.boolean().nullish(),
77
+ errors: z.array(z.string()).nullish()
78
+ });
79
+ var DnsInstructionsSchema = z.object({
80
+ hostname: z.string().nullish(),
81
+ target: z.string().nullish(),
82
+ instructions: z.string().nullish(),
83
+ isApex: z.boolean().optional()
84
+ });
85
+ var CertificateListApiResponseSchema = z.array(
86
+ CertificateApiResponseSchema
87
+ );
88
+
89
+ // packages/fly-node/src/lib/schemas/machine.schema.ts
90
+ import { z as z2 } from "zod";
91
+ var MachineApiResponseSchema = z2.object({
92
+ id: z2.string(),
93
+ name: z2.string().nullish(),
94
+ /** `started`, `stopped`, `suspended`, … — Fly owns this vocabulary */
95
+ state: z2.string().nullish(),
96
+ region: z2.string().nullish()
97
+ });
98
+ var MachineListApiResponseSchema = z2.array(MachineApiResponseSchema);
99
+
100
+ // packages/fly-node/src/lib/fly-api.class.ts
101
+ var FLY_API_URL = "https://api.fly.io/graphql";
102
+ var FLY_MACHINES_URL = "https://api.machines.dev/v1";
103
+ var FlyApiError = class extends Error {
104
+ errors;
105
+ constructor(message, errors) {
106
+ super(message);
107
+ this.name = "FlyApiError";
108
+ this.errors = errors;
109
+ }
110
+ /** Whether every error is Fly saying the thing simply does not exist */
111
+ get isNotFound() {
112
+ return this.errors.length > 0 && this.errors.every((error) => error.extensions?.code === "NOT_FOUND");
113
+ }
114
+ /**
115
+ * Whether every error is Fly refusing a hostname that already has a
116
+ * certificate on the app.
117
+ *
118
+ * No `extensions.code` comes with this one — Fly's own dashboard and
119
+ * `flyctl` hit the same message, and both work around it the same way this
120
+ * class does, by re-reading rather than retrying the mutation.
121
+ */
122
+ get isAlreadyExists() {
123
+ return this.errors.length > 0 && this.errors.every((error) => /already exists/i.test(error.message));
124
+ }
125
+ };
126
+ var FlyApi = class {
127
+ token;
128
+ apiUrl;
129
+ machinesUrl;
130
+ log;
131
+ constructor(config) {
132
+ if (!config.token) {
133
+ throw new Error("[fly-api] A Fly API token is required");
134
+ }
135
+ this.token = config.token;
136
+ this.apiUrl = config.apiUrl ?? FLY_API_URL;
137
+ this.machinesUrl = config.machinesUrl ?? FLY_MACHINES_URL;
138
+ this.log = config.log ?? (() => void 0);
139
+ }
140
+ /**
141
+ * Manage certificates for an app.
142
+ *
143
+ * Every method takes the app name explicitly: this client is used by a
144
+ * process acting on *other* apps — the cms managing a tenant's web app — so
145
+ * there is no ambient "current app" to default to.
146
+ */
147
+ certs = {
148
+ /**
149
+ * Request a certificate for a hostname.
150
+ *
151
+ * Safe to call when one already exists: Fly's own mutation is not
152
+ * idempotent — a hostname it already has a certificate for on this app is
153
+ * a fault, not a no-op, so this re-reads the existing certificate itself
154
+ * rather than surfacing that as an error a caller has to know to expect.
155
+ *
156
+ * Requesting before DNS is in place is normal and expected — the
157
+ * certificate stays pending until the records resolve, and the returned
158
+ * validation fields are what you show the customer meanwhile.
159
+ *
160
+ * @param app - Fly app name the domain should serve from
161
+ * @param hostname - Domain without a scheme, e.g. `tours.example.com`
162
+ * @returns The certificate, plus what Fly resolves for that hostname now
163
+ */
164
+ add: async (app, hostname) => {
165
+ try {
166
+ const data = await this.request(
167
+ `mutation AddCertificate($appId: ID!, $hostname: String!) {
168
+ addCertificate(appId: $appId, hostname: $hostname) {
169
+ certificate { ${CERTIFICATE_FIELDS} }
170
+ check { ${HOSTNAME_CHECK_FIELDS} }
171
+ }
172
+ }`,
173
+ { appId: app, hostname }
174
+ );
175
+ return {
176
+ certificate: CertificateApiResponseSchema.parse(
177
+ data.addCertificate.certificate
178
+ ),
179
+ // Live resolution, and it comes back with the mutation for free —
180
+ // the customer has usually just edited DNS and wants to know if it
181
+ // took
182
+ check: data.addCertificate.check ? HostnameCheckApiResponseSchema.parse(data.addCertificate.check) : null
183
+ };
184
+ } catch (error) {
185
+ if (error instanceof FlyApiError && error.isAlreadyExists) {
186
+ const certificate = await this.certs.get(app, hostname);
187
+ if (certificate) {
188
+ return { certificate, check: null };
189
+ }
190
+ }
191
+ throw error;
192
+ }
193
+ },
194
+ /**
195
+ * Read one certificate, or `null` when the app has none for that hostname.
196
+ *
197
+ * This is the call behind a "check" button: it re-reads issuance state from
198
+ * Fly rather than trusting anything stored locally.
199
+ *
200
+ * Fly reports an absent certificate as a `NOT_FOUND` *error* rather than a
201
+ * null field, so that case is translated here — asking about a domain
202
+ * nobody has added yet is an ordinary question with an ordinary answer.
203
+ */
204
+ get: async (app, hostname) => {
205
+ let data;
206
+ try {
207
+ data = await this.request(
208
+ `query AppCertificate($appName: String!, $hostname: String!) {
209
+ app(name: $appName) {
210
+ certificate(hostname: $hostname) { ${CERTIFICATE_FIELDS} }
211
+ }
212
+ }`,
213
+ { appName: app, hostname }
214
+ );
215
+ } catch (error) {
216
+ if (error instanceof FlyApiError && error.isNotFound) {
217
+ return null;
218
+ }
219
+ throw error;
220
+ }
221
+ const certificate = data.app?.certificate;
222
+ return certificate ? CertificateApiResponseSchema.parse(certificate) : null;
223
+ },
224
+ /**
225
+ * What Fly resolves for a hostname right now, and what it objects to.
226
+ *
227
+ * A mutation on Fly's side despite reading rather than writing anything —
228
+ * `AppCertificate.check` is a plain boolean flag, and `HostnameCheck` is
229
+ * only ever returned by `addCertificate` and this, `checkCertificate`.
230
+ * Separate from `get` rather than folded into it: triggering a live dns
231
+ * resolution on every read would cost a caller that only wants issuance
232
+ * state. Pair the two when a person has just edited their records and
233
+ * wants to know whether it took.
234
+ *
235
+ * `errors` is the useful half — it is what Fly's own dashboard prints as
236
+ * "validation issues", already phrased for whoever owns the domain.
237
+ *
238
+ * @returns `null` when the app has no certificate for that hostname
239
+ */
240
+ check: async (app, hostname) => {
241
+ let data;
242
+ try {
243
+ data = await this.request(
244
+ `mutation CheckCertificate($appId: ID!, $hostname: String!) {
245
+ checkCertificate(input: { appId: $appId, hostname: $hostname }) {
246
+ check { ${HOSTNAME_CHECK_FIELDS} }
247
+ }
248
+ }`,
249
+ { appId: app, hostname }
250
+ );
251
+ } catch (error) {
252
+ if (error instanceof FlyApiError && error.isNotFound) {
253
+ return null;
254
+ }
255
+ throw error;
256
+ }
257
+ const check = data.checkCertificate?.check;
258
+ return check ? HostnameCheckApiResponseSchema.parse(check) : null;
259
+ },
260
+ /** Every certificate on an app */
261
+ list: async (app) => {
262
+ const data = await this.request(
263
+ `query AppCertificates($appName: String!) {
264
+ app(name: $appName) {
265
+ certificates { nodes { ${CERTIFICATE_FIELDS} } }
266
+ }
267
+ }`,
268
+ { appName: app }
269
+ );
270
+ return CertificateListApiResponseSchema.parse(
271
+ data.app?.certificates?.nodes ?? []
272
+ );
273
+ },
274
+ /**
275
+ * Remove a certificate.
276
+ *
277
+ * The hostname keeps resolving until its DNS is changed — this only stops
278
+ * Fly serving TLS for it.
279
+ */
280
+ remove: async (app, hostname) => {
281
+ await this.request(
282
+ `mutation DeleteCertificate($appId: ID!, $hostname: String!) {
283
+ deleteCertificate(appId: $appId, hostname: $hostname) {
284
+ certificate { hostname }
285
+ }
286
+ }`,
287
+ { appId: app, hostname }
288
+ );
289
+ }
290
+ };
291
+ /**
292
+ * Operate an app's machines.
293
+ *
294
+ * Over Fly's REST Machines API rather than GraphQL, which has no current
295
+ * equivalent — the GraphQL mutations date from the Nomad platform and no
296
+ * longer apply.
297
+ */
298
+ machines = {
299
+ /** Every machine on an app */
300
+ list: async (app) => {
301
+ const data = await this.machinesRequest(
302
+ "GET",
303
+ `/apps/${encodeURIComponent(app)}/machines`
304
+ );
305
+ return MachineListApiResponseSchema.parse(data ?? []);
306
+ },
307
+ /**
308
+ * Restart an app's machines.
309
+ *
310
+ * One at a time on purpose: a settings change that only takes effect at
311
+ * boot should not cost the app its availability to apply. Restarting them
312
+ * together would drop every machine at once, while sequentially leaves the
313
+ * others serving. The trade is that a large app takes longer.
314
+ *
315
+ * A machine that fails to restart stops the run rather than being skipped —
316
+ * a half-restarted app is running two configurations at the same time, and
317
+ * silently returning "some of them" invites calling that done.
318
+ *
319
+ * @param app - Fly app name
320
+ * @param machineId - Restart only this machine, instead of all of them
321
+ * @returns Ids of the machines that were restarted, in the order they were
322
+ */
323
+ restart: async (app, machineId) => {
324
+ const ids = machineId ? [machineId] : (await this.machines.list(app)).map((machine) => machine.id);
325
+ const restarted = [];
326
+ for (const id of ids) {
327
+ await this.machinesRequest(
328
+ "POST",
329
+ `/apps/${encodeURIComponent(app)}/machines/${encodeURIComponent(id)}/restart`
330
+ );
331
+ restarted.push(id);
332
+ }
333
+ return restarted;
334
+ }
335
+ };
336
+ /**
337
+ * The DNS records a customer must create for a certificate to validate.
338
+ *
339
+ * Pulled out of the certificate rather than fetched, so a caller that
340
+ * already has one does not pay for a second round trip.
341
+ */
342
+ static dnsInstructions(certificate) {
343
+ return {
344
+ hostname: certificate.dnsValidationHostname,
345
+ target: certificate.dnsValidationTarget,
346
+ instructions: certificate.dnsValidationInstructions,
347
+ isApex: certificate.isApex
348
+ };
349
+ }
350
+ /**
351
+ * @private
352
+ * One GraphQL round trip.
353
+ *
354
+ * Fly answers a failed query with HTTP 200 and an `errors` array, so a
355
+ * response is only successful when both are checked — trusting the status
356
+ * alone would turn "permission denied" into a parse error further down.
357
+ */
358
+ async request(query, variables) {
359
+ const operation = /(?:query|mutation)\s+(\w+)/.exec(query)?.[1] ?? "query";
360
+ this.log(`[fly-api] ${operation} ${JSON.stringify(variables)}`);
361
+ let response;
362
+ try {
363
+ response = await fetch(this.apiUrl, {
364
+ method: "POST",
365
+ headers: {
366
+ Authorization: `Bearer ${this.token}`,
367
+ "Content-Type": "application/json"
368
+ },
369
+ body: JSON.stringify({ query, variables })
370
+ });
371
+ } catch (error) {
372
+ throw new Error(`[fly-api] ${operation} could not reach Fly: ${error}`);
373
+ }
374
+ if (!response.ok) {
375
+ throw new Error(
376
+ `[fly-api] ${operation} failed: ${response.status} ${response.statusText}`
377
+ );
378
+ }
379
+ const body = await response.json();
380
+ if (body.errors?.length) {
381
+ throw new FlyApiError(
382
+ `[fly-api] ${operation} failed: ${body.errors.map((error) => error.message).join("; ")}`,
383
+ body.errors
384
+ );
385
+ }
386
+ if (!body.data) {
387
+ throw new Error(`[fly-api] ${operation} returned no data`);
388
+ }
389
+ return body.data;
390
+ }
391
+ /**
392
+ * @private
393
+ * One call to the Machines REST API.
394
+ *
395
+ * Unlike GraphQL this one reports failure through the status code, and puts
396
+ * its reason in an `error` field. Worth reading rather than reporting the
397
+ * status alone: "machine not found" and "unauthorized" are different problems
398
+ * with different fixes.
399
+ */
400
+ async machinesRequest(method, path) {
401
+ this.log(`[fly-api] ${method} ${path}`);
402
+ let response;
403
+ try {
404
+ response = await fetch(`${this.machinesUrl}${path}`, {
405
+ method,
406
+ headers: {
407
+ Authorization: `Bearer ${this.token}`,
408
+ "Content-Type": "application/json"
409
+ }
410
+ });
411
+ } catch (error) {
412
+ throw new Error(
413
+ `[fly-api] ${method} ${path} could not reach Fly: ${error}`
414
+ );
415
+ }
416
+ const body = await response.json().catch(() => null);
417
+ if (!response.ok) {
418
+ throw new Error(
419
+ `[fly-api] ${method} ${path} failed: ${response.status} ${body?.error ?? response.statusText}`
420
+ );
421
+ }
422
+ return body;
423
+ }
424
+ };
425
+ var CERTIFICATE_FIELDS = `
426
+ id
427
+ hostname
428
+ isConfigured
429
+ isApex
430
+ isWildcard
431
+ isAcmeDnsConfigured
432
+ isAcmeAlpnConfigured
433
+ isAcmeHttpConfigured
434
+ certificateAuthority
435
+ certificateRequestedAt
436
+ createdAt
437
+ domain
438
+ dnsProvider
439
+ dnsValidationHostname
440
+ dnsValidationTarget
441
+ dnsValidationInstructions
442
+ clientStatus
443
+ rateLimitedUntil
444
+ source
445
+ validationErrors {
446
+ message
447
+ timestamp
448
+ }
449
+ # Fly issues one certificate per key type (RSA and ECDSA), so a hostname
450
+ # with a single expiry date still comes back as two rows
451
+ issued(first: 10) {
452
+ nodes {
453
+ id
454
+ type
455
+ hostname
456
+ expiresAt
457
+ }
458
+ }
459
+ `;
460
+ var HOSTNAME_CHECK_FIELDS = `
461
+ aRecords
462
+ aaaaRecords
463
+ cnameRecords
464
+ caaRecords
465
+ soa
466
+ dnsProvider
467
+ dnsVerificationRecord
468
+ dnsConfigured
469
+ acmeDnsConfigured
470
+ resolvedAddresses
471
+ isProxied
472
+ errors
473
+ `;
474
+
1
475
  // packages/fly-node/src/lib/fly.class.ts
2
- import { existsSync } from "fs";
476
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
3
477
  import { dirname, join } from "path";
4
478
  import { cwd } from "process";
5
479
 
6
- // packages/core/src/lib/utils/docker-build.ts
480
+ // libs/shared/util/misc/src/lib/docker-build.ts
7
481
  import { dockerCommand } from "docker-cli-js";
8
482
  import invariant from "tiny-invariant";
9
483
 
10
- // packages/core/src/lib/utils/log-utils.ts
484
+ // libs/shared/util/misc/src/lib/log-utils.ts
11
485
  import chalk from "chalk";
12
486
 
13
- // packages/core/src/lib/utils/promisified-exec.ts
487
+ // libs/shared/util/misc/src/lib/promisified-exec.ts
14
488
  import { exec as cpExec, execFile as cpExecFile } from "child_process";
15
489
  import { promisify } from "util";
16
490
  var exec = promisify(cpExec);
17
491
  var execFile = promisify(cpExecFile);
18
492
 
19
- // packages/core/src/lib/utils/kill-port.ts
493
+ // libs/shared/util/misc/src/lib/kill-port.ts
20
494
  import kill from "kill-port";
21
495
  import { check as portCheck } from "tcp-port-used";
22
496
 
23
- // packages/core/src/lib/utils/kill-process-tree.ts
497
+ // libs/shared/util/misc/src/lib/kill-process-tree.ts
24
498
  import { promisify as promisify2 } from "util";
25
499
  import treeKill from "tree-kill";
26
500
  var killProcessTree = promisify2(treeKill);
27
501
 
28
- // packages/core/src/lib/utils/promisified-spawn.ts
502
+ // libs/shared/util/misc/src/lib/promisified-spawn.ts
29
503
  import {
30
504
  spawn as cpSpawn
31
505
  } from "child_process";
32
506
  function spawn(command, args, options) {
33
507
  return new Promise((resolve, reject) => {
508
+ const { streamToConsole, ...spawnOptions } = options || {};
34
509
  const process2 = cpSpawn(command, args, {
35
- ...options,
510
+ ...spawnOptions,
36
511
  stdio: "pipe"
37
512
  });
38
513
  const stdoutChunks = [];
39
514
  const stderrChunks = [];
40
515
  process2.stdout.on("data", (data) => {
41
516
  stdoutChunks.push(Buffer.from(data));
517
+ if (streamToConsole) {
518
+ global.process.stdout.write(data);
519
+ }
42
520
  });
43
521
  process2.stderr.on("data", (data) => {
44
522
  stderrChunks.push(Buffer.from(data));
523
+ if (streamToConsole) {
524
+ global.process.stderr.write(data);
525
+ }
45
526
  });
46
527
  process2.on("close", (code) => {
47
528
  const stdout = Buffer.concat(stdoutChunks).toString();
@@ -57,10 +538,7 @@ Error: ${stderr}`));
57
538
  });
58
539
  }
59
540
 
60
- // packages/core/src/lib/utils/run-command.ts
61
- import { tmpProjPath } from "@nx/plugin/testing";
62
-
63
- // packages/core/src/lib/utils/spawn-pty.ts
541
+ // libs/shared/util/misc/src/lib/spawn-pty.ts
64
542
  import { spawn as spawn2 } from "@homebridge/node-pty-prebuilt-multiarch";
65
543
  function spawnPty(command, args, options) {
66
544
  return new Promise((resolve, reject) => {
@@ -94,21 +572,24 @@ Output: ${output}`)
94
572
  });
95
573
  }
96
574
 
97
- // packages/core/src/lib/utils/whoami.ts
98
- import npmWhoami from "npm-whoami";
99
-
100
575
  // packages/fly-node/src/lib/fly.class.ts
101
576
  import { ZodError } from "zod";
102
577
 
103
- // packages/core/src/lib/zod/json.schema.ts
104
- import { z } from "zod";
105
- var LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
106
- var JsonSchema = z.lazy(
107
- () => z.union([LiteralSchema, z.array(JsonSchema), z.record(JsonSchema)])
578
+ // libs/shared/util/zod/src/lib/coerce-boolean.ts
579
+ import { z as z3 } from "zod";
580
+
581
+ // libs/shared/util/zod/src/lib/create-lowercase-schema.ts
582
+ import { z as z4 } from "zod";
583
+
584
+ // libs/shared/util/zod/src/lib/json.schema.ts
585
+ import { z as z5 } from "zod";
586
+ var LiteralSchema = z5.union([z5.string(), z5.number(), z5.boolean(), z5.null()]);
587
+ var JsonSchema = z5.lazy(
588
+ () => z5.union([LiteralSchema, z5.array(JsonSchema), z5.record(JsonSchema)])
108
589
  );
109
590
 
110
- // packages/core/src/lib/zod/with-camel-case.preprocess.ts
111
- import { z as z2 } from "zod";
591
+ // libs/shared/util/zod/src/lib/with-camel-case.preprocess.ts
592
+ import { z as z6 } from "zod";
112
593
  var toCamelCase = (str, specialCases = {}) => {
113
594
  if (specialCases[str]) {
114
595
  return specialCases[str];
@@ -134,28 +615,31 @@ var transformKeys = (options) => {
134
615
  );
135
616
  }
136
617
  if (data && typeof data === "object" && data !== null) {
137
- return Object.entries(data).reduce((acc, [key, value]) => {
138
- const shouldPreserveValue = preserve.some(
139
- (path) => [...currentPath, key].join(".").match(new RegExp(`^${path}.`))
140
- );
141
- const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
142
- const newPath = [...currentPath, newKey];
143
- return {
144
- ...acc,
145
- [newKey]: transformKeys({
146
- currentPath: newPath,
147
- data: value,
148
- preserve,
149
- specialCases
150
- })
151
- };
152
- }, {});
618
+ return Object.fromEntries(
619
+ Object.entries(data).map(([key, value]) => {
620
+ const fullPath = [...currentPath, key].join(".");
621
+ const shouldPreserveValue = preserve.some(
622
+ (path) => fullPath.startsWith(`${path}.`)
623
+ );
624
+ const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
625
+ const newPath = [...currentPath, newKey];
626
+ return [
627
+ newKey,
628
+ transformKeys({
629
+ currentPath: newPath,
630
+ data: value,
631
+ preserve,
632
+ specialCases
633
+ })
634
+ ];
635
+ })
636
+ );
153
637
  }
154
638
  return data;
155
639
  };
156
640
  var withCamelCase = (schema, options = {}) => {
157
641
  const { preserve = [], specialCases = {} } = options;
158
- return z2.preprocess(
642
+ return z6.preprocess(
159
643
  (data) => transformKeys({
160
644
  currentPath: [],
161
645
  data,
@@ -166,83 +650,93 @@ var withCamelCase = (schema, options = {}) => {
166
650
  );
167
651
  };
168
652
 
169
- // packages/core/src/lib/zod/with-replace-all.preprocess.ts
170
- import { z as z3 } from "zod";
653
+ // libs/shared/util/zod/src/lib/with-env-vars.preprocess.ts
654
+ import { z as z7 } from "zod";
655
+
656
+ // libs/shared/util/zod/src/lib/with-replace-all.preprocess.ts
657
+ import { z as z8 } from "zod";
171
658
 
172
659
  // packages/fly-node/src/lib/schemas/apps-create.schema.ts
173
- import { z as z4 } from "zod";
660
+ import { z as z9 } from "zod";
174
661
  var AppsCreateTransformedResponseSchema = withCamelCase(
175
- z4.object({
176
- id: z4.string(),
177
- name: z4.string()
662
+ z9.object({
663
+ id: z9.string(),
664
+ name: z9.string()
178
665
  })
179
666
  );
180
667
 
181
668
  // packages/fly-node/src/lib/schemas/apps-list.schema.ts
182
- import { z as z5 } from "zod";
183
- var AppsListTransformedResponseSchema = z5.array(
669
+ import { z as z10 } from "zod";
670
+ var AppsListTransformedResponseSchema = z10.array(
184
671
  withCamelCase(
185
- z5.object({
186
- id: z5.string(),
187
- name: z5.string(),
188
- status: z5.string(),
189
- deployed: z5.boolean(),
190
- hostname: z5.string(),
191
- organization: z5.object({
192
- name: z5.string(),
193
- slug: z5.string()
672
+ z10.object({
673
+ id: z10.string(),
674
+ name: z10.string(),
675
+ status: z10.string(),
676
+ deployed: z10.boolean(),
677
+ hostname: z10.string(),
678
+ organization: z10.object({
679
+ name: z10.string(),
680
+ slug: z10.string()
194
681
  }),
195
- currentRelease: z5.nullable(
196
- z5.object({
197
- status: z5.string(),
198
- createdAt: z5.string().datetime()
682
+ currentRelease: z10.nullable(
683
+ z10.object({
684
+ status: z10.string(),
685
+ createdAt: z10.string().datetime()
199
686
  })
200
687
  )
201
688
  })
202
689
  )
203
690
  );
204
691
 
692
+ // packages/fly-node/src/lib/schemas/build-response.schema.ts
693
+ import { z as z11 } from "zod";
694
+ var BuildResponseSchema = z11.object({
695
+ appName: z11.string(),
696
+ imageRef: z11.string()
697
+ });
698
+
205
699
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
206
- import { z as z7 } from "zod";
700
+ import { z as z13 } from "zod";
207
701
 
208
702
  // packages/fly-node/src/lib/schemas/certs-list.schema.ts
209
- import { z as z6 } from "zod";
210
- var CertsListFlyResponseElementSchema = z6.object({
211
- createdAt: z6.string().datetime(),
212
- hostname: z6.string(),
213
- clientStatus: z6.string()
703
+ import { z as z12 } from "zod";
704
+ var CertsListFlyResponseElementSchema = z12.object({
705
+ createdAt: z12.string().datetime(),
706
+ hostname: z12.string(),
707
+ clientStatus: z12.string()
214
708
  });
215
- var CertsListTransformedResponseSchema = z6.array(
709
+ var CertsListTransformedResponseSchema = z12.array(
216
710
  withCamelCase(CertsListFlyResponseElementSchema)
217
711
  );
218
712
 
219
713
  // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
220
- var CertsListWithAppTransformedResponseSchema = z7.array(
714
+ var CertsListWithAppTransformedResponseSchema = z13.array(
221
715
  withCamelCase(
222
716
  CertsListFlyResponseElementSchema.extend({
223
- app: z7.string()
717
+ app: z13.string()
224
718
  })
225
719
  )
226
720
  );
227
721
 
228
722
  // packages/fly-node/src/lib/schemas/config-show.schema.ts
229
- import { z as z8 } from "zod";
723
+ import { z as z14 } from "zod";
230
724
  var ConfigShowResponseSchema = withCamelCase(
231
- z8.object({
232
- app: z8.string(),
233
- primaryRegion: z8.string().optional(),
234
- build: z8.record(z8.string(), z8.any()).optional().or(
235
- z8.object({
236
- args: z8.record(z8.string(), z8.string()).optional(),
237
- dockerfile: z8.string().optional(),
238
- image: z8.string().optional()
725
+ z14.object({
726
+ app: z14.string(),
727
+ primaryRegion: z14.string().optional(),
728
+ build: z14.record(z14.string(), z14.any()).optional().or(
729
+ z14.object({
730
+ args: z14.record(z14.string(), z14.string()).optional(),
731
+ dockerfile: z14.string().optional(),
732
+ image: z14.string().optional()
239
733
  })
240
734
  ),
241
- deploy: z8.record(z8.string(), z8.any()).optional().or(z8.object({ strategy: z8.string().optional() })),
242
- env: z8.record(z8.string(), z8.string()).optional(),
243
- httpService: z8.record(z8.string(), z8.any()).optional(),
244
- mounts: z8.record(z8.string(), z8.any()).optional(),
245
- services: z8.array(z8.record(z8.string(), z8.any())).optional()
735
+ deploy: z14.record(z14.string(), z14.any()).optional().or(z14.object({ strategy: z14.string().optional() })),
736
+ env: z14.record(z14.string(), z14.string()).optional(),
737
+ httpService: z14.record(z14.string(), z14.any()).optional(),
738
+ mounts: z14.record(z14.string(), z14.any()).optional(),
739
+ services: z14.array(z14.record(z14.string(), z14.any())).optional()
246
740
  }),
247
741
  {
248
742
  preserve: ["build.args", "env"]
@@ -250,119 +744,135 @@ var ConfigShowResponseSchema = withCamelCase(
250
744
  );
251
745
 
252
746
  // packages/fly-node/src/lib/schemas/deploy.schema.ts
253
- import { z as z9 } from "zod";
254
- var DeployResponseSchema = z9.object({
255
- app: z9.string(),
256
- hostname: z9.string(),
257
- url: z9.string().url()
747
+ import { z as z15 } from "zod";
748
+ var DeployResponseSchema = z15.object({
749
+ app: z15.string(),
750
+ hostname: z15.string(),
751
+ url: z15.string().url()
258
752
  });
259
753
 
260
754
  // packages/fly-node/src/lib/schemas/helper-schemas.ts
261
- import { z as z10 } from "zod";
262
- var AllowEmptyUrlSchema = z10.string().url().or(z10.literal(""));
263
- var NameSchema = z10.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
755
+ import { z as z16 } from "zod";
756
+ var AllowEmptyUrlSchema = z16.string().url().or(z16.literal(""));
757
+ var NameSchema = z16.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
264
758
 
265
759
  // packages/fly-node/src/lib/schemas/postgres-list.ts
266
- import { z as z11 } from "zod";
267
- var PostgresListTransformedResponseSchema = z11.array(
760
+ import { z as z17 } from "zod";
761
+ var PostgresListTransformedResponseSchema = z17.array(
268
762
  withCamelCase(
269
- z11.object({
270
- deployed: z11.boolean(),
271
- hostname: z11.string(),
272
- id: z11.string(),
273
- name: z11.string(),
274
- organization: z11.object({ id: z11.string(), slug: z11.string() }),
275
- status: z11.string(),
276
- version: z11.number()
763
+ z17.object({
764
+ deployed: z17.boolean(),
765
+ hostname: z17.string(),
766
+ id: z17.string(),
767
+ name: z17.string(),
768
+ organization: z17.object({ id: z17.string(), slug: z17.string() }),
769
+ status: z17.string(),
770
+ version: z17.number()
277
771
  })
278
772
  )
279
- ).or(z11.string());
773
+ ).or(z17.string());
280
774
 
281
775
  // packages/fly-node/src/lib/schemas/postgres-users-list.ts
282
- import { z as z12 } from "zod";
283
- var PostgresUsersListTransformedResponseSchema = z12.array(
776
+ import { z as z18 } from "zod";
777
+ var PostgresUsersListTransformedResponseSchema = z18.array(
284
778
  withCamelCase(
285
- z12.object({
286
- username: z12.string(),
287
- superuser: z12.boolean(),
288
- databases: z12.array(z12.string())
779
+ z18.object({
780
+ username: z18.string(),
781
+ superuser: z18.boolean(),
782
+ databases: z18.array(z18.string())
289
783
  })
290
784
  )
291
785
  );
292
786
 
293
787
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
294
- import { z as z14 } from "zod";
788
+ import { z as z20 } from "zod";
295
789
 
296
790
  // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
297
- import { z as z13 } from "zod";
298
- var SecretsListFlyResponseElementSchema = z13.object({
299
- name: z13.string(),
300
- digest: z13.string()
791
+ import { z as z19 } from "zod";
792
+ var SecretsListFlyResponseElementSchema = z19.object({
793
+ name: z19.string(),
794
+ digest: z19.string()
301
795
  });
302
- var SecretsListTransformedResponseSchema = z13.array(
796
+ var SecretsListTransformedResponseSchema = z19.array(
303
797
  withCamelCase(SecretsListFlyResponseElementSchema)
304
798
  );
305
799
 
306
800
  // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
307
- var SecretsListWithAppTransformedResponseSchema = z14.array(
801
+ var SecretsListWithAppTransformedResponseSchema = z20.array(
308
802
  withCamelCase(
309
803
  SecretsListFlyResponseElementSchema.extend({
310
- app: z14.string()
804
+ app: z20.string()
311
805
  })
312
806
  )
313
807
  );
314
808
 
315
809
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
316
- import { z as z16 } from "zod";
810
+ import { z as z22 } from "zod";
317
811
 
318
812
  // packages/fly-node/src/lib/schemas/status.schema.ts
319
- import { z as z15 } from "zod";
320
- var statusFlyResponseSchema = z15.object({
321
- deployed: z15.boolean(),
322
- hostname: z15.string(),
323
- id: z15.string(),
324
- machines: z15.array(
325
- z15.object({
326
- id: z15.string(),
327
- name: z15.string(),
328
- state: z15.string(),
329
- region: z15.string(),
330
- createdAt: z15.string().datetime(),
331
- updatedAt: z15.string().datetime(),
332
- config: z15.object({
333
- env: z15.record(z15.string()),
334
- metadata: z15.record(z15.string())
813
+ import { z as z21 } from "zod";
814
+ var statusFlyResponseSchema = z21.object({
815
+ deployed: z21.boolean(),
816
+ hostname: z21.string(),
817
+ id: z21.string(),
818
+ machines: z21.array(
819
+ z21.object({
820
+ id: z21.string(),
821
+ name: z21.string(),
822
+ state: z21.string(),
823
+ region: z21.string(),
824
+ imageRef: z21.object({
825
+ registry: z21.string(),
826
+ repository: z21.string(),
827
+ tag: z21.string(),
828
+ digest: z21.string(),
829
+ labels: z21.record(z21.string()).optional()
830
+ }),
831
+ createdAt: z21.string().datetime(),
832
+ updatedAt: z21.string().datetime(),
833
+ config: z21.object({
834
+ env: z21.record(z21.string()),
835
+ metadata: z21.record(z21.string()),
836
+ guest: z21.object({
837
+ cpu_kind: z21.string().optional(),
838
+ cpus: z21.number().optional(),
839
+ memory_mb: z21.number().optional()
840
+ }).optional()
335
841
  }),
336
- events: z15.array(
337
- z15.object({
338
- type: z15.string(),
339
- status: z15.string(),
340
- timestamp: z15.number()
842
+ events: z21.array(
843
+ z21.object({
844
+ type: z21.string(),
845
+ status: z21.string(),
846
+ timestamp: z21.number()
341
847
  })
342
848
  ),
343
- checks: z15.array(
344
- z15.object({
345
- name: z15.string(),
346
- status: z15.string(),
347
- output: z15.string(),
348
- updatedAt: z15.string().datetime()
849
+ checks: z21.array(
850
+ z21.object({
851
+ name: z21.string(),
852
+ status: z21.string(),
853
+ output: z21.string(),
854
+ updatedAt: z21.string().datetime()
349
855
  })
350
856
  ).optional(),
351
- hostStatus: z15.string()
857
+ hostStatus: z21.string()
352
858
  })
353
859
  ),
354
- name: z15.string(),
355
- organization: z15.object({
356
- id: z15.string(),
357
- slug: z15.string()
860
+ name: z21.string(),
861
+ organization: z21.object({
862
+ id: z21.string(),
863
+ slug: z21.string()
358
864
  }),
359
- status: z15.string(),
360
- version: z15.number()
865
+ status: z21.string(),
866
+ version: z21.number()
361
867
  });
362
868
  var StatusTransformedResponseSchema = withCamelCase(
363
869
  statusFlyResponseSchema,
364
870
  {
365
- preserve: ["machines.config.env", "machines.config.metadata"],
871
+ preserve: [
872
+ "machines.config.env",
873
+ "machines.config.metadata",
874
+ "machines.config.guest"
875
+ ],
366
876
  specialCases: { AppURL: "appUrl" }
367
877
  }
368
878
  );
@@ -370,26 +880,30 @@ var StatusTransformedResponseSchema = withCamelCase(
370
880
  // packages/fly-node/src/lib/schemas/status-extended.schema.ts
371
881
  var StatusExtendedTransformedResponseSchema = withCamelCase(
372
882
  statusFlyResponseSchema.extend({
373
- domains: z16.array(z16.object({ hostname: z16.string() })),
374
- secrets: z16.array(z16.object({ name: z16.string() }))
883
+ domains: z22.array(z22.object({ hostname: z22.string() })),
884
+ secrets: z22.array(z22.object({ name: z22.string() }))
375
885
  }),
376
886
  {
377
- preserve: ["machines.config.env", "machines.config.metadata"]
887
+ preserve: [
888
+ "machines.config.env",
889
+ "machines.config.metadata",
890
+ "machines.config.guest"
891
+ ]
378
892
  }
379
893
  );
380
894
 
381
895
  // packages/fly-node/src/lib/schemas/version.schema.ts
382
- import { z as z17 } from "zod";
896
+ import { z as z23 } from "zod";
383
897
  var VersionTransformedResponseSchema = withCamelCase(
384
- z17.object({
385
- name: z17.string(),
386
- version: z17.string(),
387
- commit: z17.string(),
388
- branchName: z17.string(),
389
- buildDate: z17.string().datetime(),
390
- os: z17.string(),
391
- architecture: z17.string(),
392
- environment: z17.string()
898
+ z23.object({
899
+ name: z23.string(),
900
+ version: z23.string(),
901
+ commit: z23.string(),
902
+ branchName: z23.string(),
903
+ buildDate: z23.string().datetime(),
904
+ os: z23.string(),
905
+ architecture: z23.string(),
906
+ environment: z23.string()
393
907
  })
394
908
  );
395
909
 
@@ -423,7 +937,10 @@ var Fly = class {
423
937
  info: config?.logger?.info || console.log,
424
938
  error: config?.logger?.error || console.error,
425
939
  traceCLI: config?.logger?.traceCLI ?? false,
426
- redactSecrets: config?.logger?.redactSecrets ?? true
940
+ redactSecrets: config?.logger?.redactSecrets ?? true,
941
+ verbose: config?.logger?.verbose ?? false,
942
+ debug: config?.logger?.debug ?? false,
943
+ streamToConsole: config?.logger?.streamToConsole ?? false
427
944
  };
428
945
  if (this._config.token) {
429
946
  process.env["FLY_ACCESS_TOKEN"] = this._config.token;
@@ -615,7 +1132,10 @@ ${error}`
615
1132
  */
616
1133
  config = {
617
1134
  /**
618
- * Save an application's remote configuration locally as TOML file.
1135
+ * Save an application's remote configuration locally.
1136
+ *
1137
+ * TOML by default; name the path `.json` or `.yaml`/`.yml` for either of
1138
+ * those instead.
619
1139
  *
620
1140
  * @param options - Options for saving an application's configuration
621
1141
  * @throws An error if the configuration cannot be saved
@@ -650,7 +1170,12 @@ ${error}`);
650
1170
  }
651
1171
  };
652
1172
  /**
653
- * Deploy an application.
1173
+ * Deploy an application, or just build its Docker image without deploying when
1174
+ * `buildOnly` is set (equivalent to using `build(options)`).
1175
+ *
1176
+ * Pre-building is useful to ensure the image can be built successfully and exists
1177
+ * before running a deploy that depends on it, and also to get the image reference for use in
1178
+ * subsequent operations.
654
1179
  *
655
1180
  * A valid config file is required but the app doesn't have to exist,
656
1181
  * since it gets created if needed.
@@ -660,15 +1185,28 @@ ${error}`);
660
1185
  * 2. Instance app name
661
1186
  * 3. App name from the provided config file
662
1187
  *
663
- * Existing secrets are preserved.
664
- *
665
- * @param options - Options for deploying an application
666
- * @throws An error if the deployment fails
1188
+ * @param options - Deployment or build options
1189
+ * @returns Build or deploy response depending on `buildOnly` option
1190
+ * @throws An error if the operation fails
667
1191
  */
668
1192
  deploy = async (options) => {
1193
+ const isBuildOnly = options?.buildOnly === true;
669
1194
  try {
670
1195
  await this.ensureInitialized();
671
- const appName = await this.deployApp(options);
1196
+ if (isBuildOnly) {
1197
+ const { appName: appName2, imageRef } = await this.deployApp({
1198
+ ...options,
1199
+ buildOnly: true
1200
+ });
1201
+ if (!imageRef) {
1202
+ throw new Error(
1203
+ "Build completed but image reference not found in output"
1204
+ );
1205
+ }
1206
+ this.logger.info(`Image for '${appName2}' built: ${imageRef}`);
1207
+ return BuildResponseSchema.parse({ appName: appName2, imageRef });
1208
+ }
1209
+ const { appName } = await this.deployApp(options);
672
1210
  this.logger.info(`Application '${appName}' was deployed`);
673
1211
  const status = await this.fetchAppStatus("throwOnError", {
674
1212
  app: appName
@@ -680,16 +1218,124 @@ ${error}`);
680
1218
  });
681
1219
  } catch (error) {
682
1220
  throw new Error(
683
- `[deploy] something broke, check your deployments
1221
+ `[deploy] something broke, check your ${isBuildOnly ? "builds" : "deployments"}
684
1222
  ${error}`
685
1223
  );
686
1224
  }
687
1225
  };
1226
+ /**
1227
+ * Manage machines
1228
+ */
1229
+ machines = {
1230
+ /**
1231
+ * Start a machine
1232
+ *
1233
+ * @param app - The name of the application
1234
+ * @param machineId - The machine ID to start
1235
+ * @throws An error if the machine cannot be started
1236
+ */
1237
+ start: async (app, machineId) => {
1238
+ try {
1239
+ await this.ensureInitialized();
1240
+ await this.startMachine(app, machineId);
1241
+ this.logger.info(`Machine '${machineId}' in app '${app}' was started`);
1242
+ } catch (error) {
1243
+ throw new Error(`[start machine] something broke
1244
+ ${error}`);
1245
+ }
1246
+ },
1247
+ /**
1248
+ * Stop a machine
1249
+ *
1250
+ * @param app - The name of the application
1251
+ * @param machineId - The machine ID to stop
1252
+ * @throws An error if the machine cannot be stopped
1253
+ */
1254
+ stop: async (app, machineId) => {
1255
+ try {
1256
+ await this.ensureInitialized();
1257
+ await this.stopMachine(app, machineId);
1258
+ this.logger.info(`Machine '${machineId}' in app '${app}' was stopped`);
1259
+ } catch (error) {
1260
+ throw new Error(`[stop machine] something broke
1261
+ ${error}`);
1262
+ }
1263
+ },
1264
+ /**
1265
+ * Restart a machine by stopping then starting it
1266
+ *
1267
+ * @param app - The name of the application
1268
+ * @param machineId - The machine ID to restart
1269
+ * @throws An error if the machine cannot be restarted
1270
+ */
1271
+ restart: async (app, machineId) => {
1272
+ try {
1273
+ await this.ensureInitialized();
1274
+ await this.restartMachine(app, machineId);
1275
+ this.logger.info(
1276
+ `Machine '${machineId}' in app '${app}' was restarted`
1277
+ );
1278
+ } catch (error) {
1279
+ throw new Error(`[restart machine] something broke
1280
+ ${error}`);
1281
+ }
1282
+ },
1283
+ /**
1284
+ * Update a machine's per-machine configuration (env vars, etc.).
1285
+ *
1286
+ * Unlike `restart`, this creates a new machine version from the updated config
1287
+ * and forces a cold start — it does NOT resume from a suspended memory snapshot.
1288
+ *
1289
+ * @param app - The name of the application
1290
+ * @param machineId - The machine ID to update
1291
+ * @param options - Fields to update; env values set to `''` clear that var
1292
+ * @throws An error if the machine cannot be updated
1293
+ */
1294
+ update: async (app, machineId, options) => {
1295
+ try {
1296
+ await this.ensureInitialized();
1297
+ await this.updateMachine(app, machineId, options);
1298
+ this.logger.info(`Machine '${machineId}' in app '${app}' was updated`);
1299
+ } catch (error) {
1300
+ throw new Error(`[update machine] something broke
1301
+ ${error}`);
1302
+ }
1303
+ }
1304
+ };
688
1305
  postgres = {
689
1306
  detach: async (cluster, app) => {
690
1307
  await this.detachPostgres(cluster, app);
691
1308
  }
692
1309
  };
1310
+ /**
1311
+ * Run commands inside a running machine
1312
+ */
1313
+ ssh = {
1314
+ /**
1315
+ * Execute a command in a running machine and return its output.
1316
+ *
1317
+ * Requires a started machine - Fly cannot connect to a stopped or
1318
+ * suspended one. Use `machines.start` first when the app may be idle.
1319
+ *
1320
+ * The output is returned to the caller and not logged unless CLI tracing
1321
+ * is enabled, so it can be used to read values that are otherwise
1322
+ * write-only, such as secrets injected at deploy time.
1323
+ *
1324
+ * @param app - The name of the application
1325
+ * @param command - The command to run inside the machine
1326
+ * @returns The command output
1327
+ * @throws An error if there is no started machine or the command fails
1328
+ */
1329
+ exec: async (app, command) => {
1330
+ try {
1331
+ await this.ensureInitialized();
1332
+ return await this.sshExec(app, command);
1333
+ } catch (error) {
1334
+ throw new Error(`[ssh exec] something broke
1335
+ ${error}`);
1336
+ }
1337
+ }
1338
+ };
693
1339
  /**
694
1340
  * Manage application secrets
695
1341
  */
@@ -716,6 +1362,28 @@ ${error}`
716
1362
  );
717
1363
  }
718
1364
  },
1365
+ /**
1366
+ * Apply secrets that were staged with `set({ stage: true })`.
1367
+ *
1368
+ * Staging first and deploying afterwards lets a set of apps take a new
1369
+ * value together, instead of each restarting as its own secret is written.
1370
+ *
1371
+ * Fly needs a started machine to update, so an app whose machines are all
1372
+ * stopped or suspended has to be started before this will do anything.
1373
+ *
1374
+ * @param app - The name of the application
1375
+ * @throws An error if the staged secrets cannot be deployed
1376
+ */
1377
+ deploy: async (app) => {
1378
+ try {
1379
+ await this.ensureInitialized();
1380
+ await this.deployStagedSecrets(app);
1381
+ this.logger.info(`Staged secrets were deployed for '${app}'`);
1382
+ } catch (error) {
1383
+ throw new Error(`[deploy secrets] something broke
1384
+ ${error}`);
1385
+ }
1386
+ },
719
1387
  /**
720
1388
  * List secrets for an application or all secrets when options is 'all'
721
1389
  *
@@ -776,6 +1444,22 @@ ${error}`);
776
1444
  return null;
777
1445
  }
778
1446
  };
1447
+ //
1448
+ // DX friendly methods outside what Fly CLI provides
1449
+ //
1450
+ /**
1451
+ * Build a Docker image for an application and push it to the Fly registry
1452
+ * without deploying.
1453
+ *
1454
+ * The image reference is returned for use in a subsequent `deploy` that depends on it.
1455
+ *
1456
+ * Shorthand for `deploy({ ...options, buildOnly: true })`.
1457
+ *
1458
+ * @param options - Build options
1459
+ * @returns The app name and image reference for use in a subsequent `deploy`
1460
+ * @throws An error if the build fails or the image reference cannot be parsed
1461
+ */
1462
+ build = (options) => this.deploy({ ...options, buildOnly: true });
779
1463
  /**
780
1464
  * Get the extended details of an application
781
1465
  *
@@ -822,7 +1506,7 @@ ${error}`);
822
1506
  }
823
1507
  /**
824
1508
  * @private
825
- * @returns The name of the deployed application
1509
+ * @returns The app name and optional image reference (only set when buildOnly is true)
826
1510
  * @throws An error if the deployment fails
827
1511
  */
828
1512
  async deployApp(options) {
@@ -896,7 +1580,7 @@ ${error}`);
896
1580
  this.logger.info(`Updating existing application '${appName}'`);
897
1581
  }
898
1582
  NameSchema.parse(appName);
899
- if (options?.secrets) {
1583
+ if (!options?.buildOnly && options?.secrets) {
900
1584
  const existingSecrets = new Set(appSecrets.map(({ name }) => name));
901
1585
  const newSecrets = {};
902
1586
  for (const [key, value] of Object.entries(options.secrets)) {
@@ -923,7 +1607,7 @@ ${error}`);
923
1607
  );
924
1608
  appName = options.app;
925
1609
  }
926
- if (options?.postgres) {
1610
+ if (!options?.buildOnly && options?.postgres) {
927
1611
  const users = await this.fetchPostgresUsers(
928
1612
  options.postgres,
929
1613
  "nullOnError"
@@ -938,9 +1622,13 @@ ${error}`);
938
1622
  );
939
1623
  } else {
940
1624
  this.logger.info(
941
- `Attach Postgres cluster '${options.postgres}' to '${appName}'`
1625
+ `Attach Postgres cluster '${options.postgres}' to '${appName}'${options.databaseName ? ` with database '${options.databaseName}'` : ""}`
1626
+ );
1627
+ await this.attachPostgres(
1628
+ options.postgres,
1629
+ appName,
1630
+ options.databaseName
942
1631
  );
943
- await this.attachPostgres(options.postgres, appName);
944
1632
  }
945
1633
  }
946
1634
  const args = ["deploy", "--app", appName, "--config", deployConfig];
@@ -953,20 +1641,39 @@ ${error}`);
953
1641
  for (const [key, value] of Object.entries(options?.env || {})) {
954
1642
  args.push("--env", `${key}=${this.safeArg(value)}`);
955
1643
  }
1644
+ for (const [key, value] of Object.entries(options?.buildArgs || {})) {
1645
+ args.push("--build-arg", `${key}=${this.safeArg(value)}`);
1646
+ }
1647
+ if (options?.image) {
1648
+ args.push("--image", options.image);
1649
+ }
1650
+ if (options?.buildOnly) {
1651
+ args.push("--build-only", "--push");
1652
+ }
956
1653
  if (options?.optOutDepotBuilder) {
957
1654
  args.push("--depot=false");
958
1655
  }
959
1656
  args.push("--yes");
960
- this.logger.info(`Deploying '${appName}'...`);
961
- await this.execFly(args);
962
- return appName;
1657
+ this.logger.info(
1658
+ options?.buildOnly ? `Building image for '${appName}'...` : `Deploying '${appName}'...`
1659
+ );
1660
+ const output = await this.execFly(
1661
+ args,
1662
+ options?.buildOnly ? { streamStrategy: "combined" } : void 0
1663
+ );
1664
+ const imageRef = options?.buildOnly ? output?.match(/registry\.fly\.io\/\S+/)?.[0] : void 0;
1665
+ return { appName, imageRef };
963
1666
  }
964
1667
  /**
965
1668
  * @private
966
1669
  * @throws An error if the Postgres database cannot be attached
967
1670
  */
968
- async attachPostgres(postgres, app) {
969
- const args = ["postgres", "attach", postgres, "--app", app, "--yes"];
1671
+ async attachPostgres(postgres, app, databaseName) {
1672
+ const args = ["postgres", "attach", postgres, "--app", app];
1673
+ if (databaseName) {
1674
+ args.push("--database-name", databaseName);
1675
+ }
1676
+ args.push("--yes");
970
1677
  await this.execFly(args);
971
1678
  }
972
1679
  /**
@@ -1053,6 +1760,68 @@ ${error}`);
1053
1760
  await this.execFly(args);
1054
1761
  return NameSchema.parse(status.name);
1055
1762
  }
1763
+ /**
1764
+ * @private
1765
+ * Deploy secrets previously staged for an application
1766
+ * @throws An error if the staged secrets cannot be deployed
1767
+ */
1768
+ async deployStagedSecrets(app) {
1769
+ const args = ["secrets", "deploy", "--app", app];
1770
+ await this.execFly(args);
1771
+ }
1772
+ /**
1773
+ * @private
1774
+ * Execute a command inside a running machine
1775
+ * @returns The command output
1776
+ * @throws An error if the command fails
1777
+ */
1778
+ async sshExec(app, command) {
1779
+ const args = ["ssh", "console", "--app", app, "--command", command];
1780
+ return await this.execFly(args);
1781
+ }
1782
+ /**
1783
+ * @private
1784
+ * Start a machine
1785
+ * @throws An error if the machine cannot be started
1786
+ */
1787
+ async startMachine(app, machineId) {
1788
+ const args = ["machine", "start", machineId, "--app", app];
1789
+ await this.execFly(args);
1790
+ }
1791
+ /**
1792
+ * @private
1793
+ * Stop a machine
1794
+ * @throws An error if the machine cannot be stopped
1795
+ */
1796
+ async stopMachine(app, machineId) {
1797
+ const args = ["machine", "stop", machineId, "--app", app];
1798
+ await this.execFly(args);
1799
+ }
1800
+ /**
1801
+ * @private
1802
+ * Restart a machine by stopping then starting it
1803
+ * @throws An error if the machine cannot be restarted
1804
+ */
1805
+ async restartMachine(app, machineId) {
1806
+ await this.stopMachine(app, machineId);
1807
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
1808
+ await this.startMachine(app, machineId);
1809
+ }
1810
+ /**
1811
+ * @private
1812
+ * Update a machine's per-machine config (env vars, etc.).
1813
+ * Creates a new machine version so the machine cold-starts from the updated config,
1814
+ * bypassing any suspended memory snapshot.
1815
+ * @throws An error if the machine cannot be updated
1816
+ */
1817
+ async updateMachine(app, machineId, options) {
1818
+ const args = ["machine", "update", machineId, "--app", app];
1819
+ for (const [key, value] of Object.entries(options.env || {})) {
1820
+ args.push("--env", `${key}=${this.safeArg(value)}`);
1821
+ }
1822
+ args.push("--yes");
1823
+ await this.execFly(args);
1824
+ }
1056
1825
  async fetchAllApps(onError) {
1057
1826
  const args = ["apps", "list", "--json"];
1058
1827
  try {
@@ -1207,9 +1976,23 @@ ${JSON.stringify(response, null, 2)}`);
1207
1976
  * @private
1208
1977
  * Save remote config to a local file
1209
1978
  *
1979
+ * Two things flyctl expects that a first-time caller would not: the output
1980
+ * format is no longer sniffed from the path's extension — `--json`/`--yaml`
1981
+ * has to be passed, TOML being what is left over when neither is — and the
1982
+ * destination must already exist as a parseable file of that format, or
1983
+ * `flyctl` refuses to write to it at all, mistaking "does not exist yet"
1984
+ * for "path is wrong". A fresh, empty seed of the right shape satisfies
1985
+ * that read without affecting what gets written back over it.
1986
+ *
1210
1987
  * @throws An error if the config cannot be saved
1211
1988
  */
1212
1989
  async saveConfig(options) {
1990
+ const isJson = options.config.endsWith(".json");
1991
+ const isYaml = /\.ya?ml$/.test(options.config);
1992
+ if (!existsSync(options.config)) {
1993
+ mkdirSync(dirname(options.config), { recursive: true });
1994
+ writeFileSync(options.config, isJson ? "{}" : "");
1995
+ }
1213
1996
  const args = [
1214
1997
  "config",
1215
1998
  "save",
@@ -1217,6 +2000,7 @@ ${JSON.stringify(response, null, 2)}`);
1217
2000
  options.app,
1218
2001
  "--config",
1219
2002
  options.config,
2003
+ ...isJson ? ["--json"] : isYaml ? ["--yaml"] : [],
1220
2004
  "--yes"
1221
2005
  ];
1222
2006
  await this.execFly(args);
@@ -1246,6 +2030,12 @@ ${JSON.stringify(response, null, 2)}`);
1246
2030
  }
1247
2031
  async execFly(command, options, onError = "throwOnError") {
1248
2032
  const args = Array.isArray(command) ? command : command.split(" ");
2033
+ if (this.logger.verbose) {
2034
+ args.push("--verbose");
2035
+ }
2036
+ if (this.logger.debug) {
2037
+ args.push("--debug");
2038
+ }
1249
2039
  const flyCmd = "flyctl";
1250
2040
  const toLogCmd = `${flyCmd} ${args.join(" ")}`;
1251
2041
  let output = "";
@@ -1255,11 +2045,17 @@ ${JSON.stringify(response, null, 2)}`);
1255
2045
  output = await spawnPty(flyCmd, args, { prompt: options.prompt });
1256
2046
  this.traceCLI("RESULT", output);
1257
2047
  } else {
1258
- const result = await spawn(flyCmd, args, options);
1259
- output = result.stdout.trim();
2048
+ const { streamStrategy = "stdout", ...spawnOpts } = options ?? {};
2049
+ const result = await spawn(flyCmd, args, {
2050
+ ...spawnOpts,
2051
+ streamToConsole: this.logger.streamToConsole
2052
+ });
2053
+ const stdout = result.stdout.trim();
1260
2054
  const stderr = result.stderr.trim();
1261
- this.traceCLI("RESULT", `${output}${stderr ? `
2055
+ this.traceCLI("RESULT", `${stdout}${stderr ? `
1262
2056
  ${stderr}` : ""}`);
2057
+ output = streamStrategy === "combined" ? `${stdout}
2058
+ ${stderr}` : streamStrategy === "stderr" ? stderr : stdout;
1263
2059
  }
1264
2060
  } catch (error) {
1265
2061
  const errorMsg = error.message;
@@ -1429,5 +2225,13 @@ ${errorMsg}`);
1429
2225
  }
1430
2226
  };
1431
2227
  export {
1432
- Fly
2228
+ CertificateApiResponseSchema,
2229
+ CertificateListApiResponseSchema,
2230
+ DnsInstructionsSchema,
2231
+ Fly,
2232
+ FlyApi,
2233
+ FlyApiError,
2234
+ HostnameCheckApiResponseSchema,
2235
+ MachineApiResponseSchema,
2236
+ MachineListApiResponseSchema
1433
2237
  };