@cdwr/fly-node 0.1.0

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 ADDED
@@ -0,0 +1,1244 @@
1
+ // packages/fly-node/src/lib/fly.class.ts
2
+ import { existsSync } from "fs";
3
+ import { join } from "path";
4
+ import { cwd } from "process";
5
+
6
+ // packages/core/src/lib/utils/docker-build.ts
7
+ import { dockerCommand } from "docker-cli-js";
8
+ import invariant from "tiny-invariant";
9
+
10
+ // packages/core/src/lib/utils/log-utils.ts
11
+ import chalk from "chalk";
12
+
13
+ // packages/core/src/lib/utils/get-package-version.ts
14
+ import { execFile } from "child_process";
15
+ import { promisify } from "util";
16
+ var execAsync = promisify(execFile);
17
+
18
+ // packages/core/src/lib/utils/kill-port.ts
19
+ import kill from "kill-port";
20
+ import { check as portCheck } from "tcp-port-used";
21
+
22
+ // packages/core/src/lib/utils/kill-process-tree.ts
23
+ import { promisify as promisify2 } from "util";
24
+ import treeKill from "tree-kill";
25
+ var killProcessTree = promisify2(treeKill);
26
+
27
+ // packages/core/src/lib/utils/promisified-exec.ts
28
+ import { exec as cpExec } from "child_process";
29
+ import { promisify as promisify3 } from "util";
30
+ var exec = promisify3(cpExec);
31
+
32
+ // packages/core/src/lib/utils/run-command.ts
33
+ import { tmpProjPath } from "@nx/plugin/testing";
34
+
35
+ // packages/core/src/lib/utils/whoami.ts
36
+ import npmWhoami from "npm-whoami";
37
+
38
+ // packages/fly-node/src/lib/fly.class.ts
39
+ import { ZodError } from "zod";
40
+
41
+ // packages/core/src/lib/zod/json.schema.ts
42
+ import { z } from "zod";
43
+ var LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
44
+ var JsonSchema = z.lazy(
45
+ () => z.union([LiteralSchema, z.array(JsonSchema), z.record(JsonSchema)])
46
+ );
47
+
48
+ // packages/core/src/lib/zod/with-camel-case.preprocess.ts
49
+ import { z as z2 } from "zod";
50
+ var toCamelCase = (str, specialCases = {}) => {
51
+ if (specialCases[str]) {
52
+ return specialCases[str];
53
+ }
54
+ if (str.includes("_")) {
55
+ return str.toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
56
+ }
57
+ if (str === str.toUpperCase()) {
58
+ return str.toLowerCase();
59
+ }
60
+ return str.charAt(0).toLowerCase() + str.slice(1);
61
+ };
62
+ var transformKeys = (options) => {
63
+ const { currentPath, data, preserve, specialCases } = options;
64
+ if (Array.isArray(data)) {
65
+ return data.map(
66
+ (item) => transformKeys({
67
+ currentPath,
68
+ data: item,
69
+ preserve,
70
+ specialCases
71
+ })
72
+ );
73
+ }
74
+ if (data && typeof data === "object" && data !== null) {
75
+ return Object.entries(data).reduce((acc, [key, value]) => {
76
+ const shouldPreserveValue = preserve.some(
77
+ (path) => [...currentPath, key].join(".").match(new RegExp(`^${path}.`))
78
+ );
79
+ const newKey = shouldPreserveValue ? key : toCamelCase(key, specialCases);
80
+ const newPath = [...currentPath, newKey];
81
+ return {
82
+ ...acc,
83
+ [newKey]: transformKeys({
84
+ currentPath: newPath,
85
+ data: value,
86
+ preserve,
87
+ specialCases
88
+ })
89
+ };
90
+ }, {});
91
+ }
92
+ return data;
93
+ };
94
+ var withCamelCase = (schema, options = {}) => {
95
+ const { preserve = [], specialCases = {} } = options;
96
+ return z2.preprocess(
97
+ (data) => transformKeys({
98
+ currentPath: [],
99
+ data,
100
+ preserve,
101
+ specialCases
102
+ }),
103
+ schema
104
+ );
105
+ };
106
+
107
+ // packages/core/src/lib/zod/with-env-vars.preprocess.ts
108
+ import { z as z3 } from "zod";
109
+
110
+ // packages/core/src/lib/zod/with-replace-all.preprocess.ts
111
+ import { z as z4 } from "zod";
112
+
113
+ // packages/fly-node/src/lib/schemas/apps-create.schema.ts
114
+ import { z as z5 } from "zod";
115
+ var AppsCreateTransformedResponseSchema = withCamelCase(
116
+ z5.object({
117
+ id: z5.string(),
118
+ name: z5.string(),
119
+ organization: z5.object({
120
+ id: z5.string(),
121
+ name: z5.string()
122
+ })
123
+ })
124
+ );
125
+
126
+ // packages/fly-node/src/lib/schemas/apps-list.schema.ts
127
+ import { z as z6 } from "zod";
128
+ var AppsListTransformedResponseSchema = z6.array(
129
+ withCamelCase(
130
+ z6.object({
131
+ id: z6.string(),
132
+ name: z6.string(),
133
+ status: z6.string(),
134
+ deployed: z6.boolean(),
135
+ hostname: z6.string(),
136
+ organization: z6.object({
137
+ name: z6.string(),
138
+ slug: z6.string()
139
+ }),
140
+ currentRelease: z6.nullable(
141
+ z6.object({
142
+ status: z6.string(),
143
+ createdAt: z6.string().datetime()
144
+ })
145
+ )
146
+ })
147
+ )
148
+ );
149
+
150
+ // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
151
+ import { z as z8 } from "zod";
152
+
153
+ // packages/fly-node/src/lib/schemas/certs-list.schema.ts
154
+ import { z as z7 } from "zod";
155
+ var CertsListFlyResponseElementSchema = z7.object({
156
+ createdAt: z7.string().datetime(),
157
+ hostname: z7.string(),
158
+ clientStatus: z7.string()
159
+ });
160
+ var CertsListTransformedResponseSchema = z7.array(
161
+ withCamelCase(CertsListFlyResponseElementSchema)
162
+ );
163
+
164
+ // packages/fly-node/src/lib/schemas/certs-list-with-app.schema.ts
165
+ var CertsListWithAppTransformedResponseSchema = z8.array(
166
+ withCamelCase(
167
+ CertsListFlyResponseElementSchema.extend({
168
+ app: z8.string()
169
+ })
170
+ )
171
+ );
172
+
173
+ // packages/fly-node/src/lib/schemas/config-show.schema.ts
174
+ import { z as z9 } from "zod";
175
+ var ConfigShowResponseSchema = withCamelCase(
176
+ z9.object({
177
+ app: z9.string(),
178
+ primaryRegion: z9.string().optional(),
179
+ build: z9.record(z9.string(), z9.any()).optional().or(
180
+ z9.object({
181
+ args: z9.record(z9.string(), z9.string()).optional(),
182
+ dockerfile: z9.string().optional(),
183
+ image: z9.string().optional()
184
+ })
185
+ ),
186
+ deploy: z9.record(z9.string(), z9.any()).optional().or(z9.object({ strategy: z9.string().optional() })),
187
+ env: z9.record(z9.string(), z9.string()).optional(),
188
+ httpService: z9.record(z9.string(), z9.any()).optional(),
189
+ mounts: z9.record(z9.string(), z9.any()).optional(),
190
+ services: z9.array(z9.record(z9.string(), z9.any())).optional()
191
+ }),
192
+ {
193
+ preserve: ["build.args", "env"]
194
+ }
195
+ );
196
+
197
+ // packages/fly-node/src/lib/schemas/deploy.schema.ts
198
+ import { z as z10 } from "zod";
199
+ var DeployResponseSchema = z10.object({
200
+ app: z10.string(),
201
+ hostname: z10.string(),
202
+ url: z10.string().url()
203
+ });
204
+
205
+ // packages/fly-node/src/lib/schemas/helper-schemas.ts
206
+ import { z as z11 } from "zod";
207
+ var AllowEmptyUrlSchema = z11.string().url().or(z11.literal(""));
208
+ var NameSchema = z11.string({ message: "App name must be a valid slug" }).regex(/^[a-z0-9-]+$/);
209
+
210
+ // packages/fly-node/src/lib/schemas/postgres-list.ts
211
+ import { z as z12 } from "zod";
212
+ var PostgresListTransformedResponseSchema = z12.array(
213
+ withCamelCase(
214
+ z12.object({
215
+ deployed: z12.boolean(),
216
+ hostname: z12.string(),
217
+ id: z12.string(),
218
+ name: z12.string(),
219
+ organization: z12.object({ id: z12.string(), slug: z12.string() }),
220
+ status: z12.string(),
221
+ version: z12.number()
222
+ })
223
+ )
224
+ );
225
+
226
+ // packages/fly-node/src/lib/schemas/postgres-users-list.ts
227
+ import { z as z13 } from "zod";
228
+ var PostgresUsersListTransformedResponseSchema = z13.array(
229
+ withCamelCase(
230
+ z13.object({
231
+ username: z13.string(),
232
+ superuser: z13.boolean(),
233
+ databases: z13.array(z13.string())
234
+ })
235
+ )
236
+ );
237
+
238
+ // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
239
+ import { z as z15 } from "zod";
240
+
241
+ // packages/fly-node/src/lib/schemas/secrets-list.schema.ts
242
+ import { z as z14 } from "zod";
243
+ var SecretsListFlyResponseElementSchema = z14.object({
244
+ name: z14.string(),
245
+ digest: z14.string(),
246
+ createdAt: z14.string().datetime()
247
+ });
248
+ var SecretsListTransformedResponseSchema = z14.array(
249
+ withCamelCase(SecretsListFlyResponseElementSchema)
250
+ );
251
+
252
+ // packages/fly-node/src/lib/schemas/secrets-list-with-app.schema.ts
253
+ var SecretsListWithAppTransformedResponseSchema = z15.array(
254
+ withCamelCase(
255
+ SecretsListFlyResponseElementSchema.extend({
256
+ app: z15.string()
257
+ })
258
+ )
259
+ );
260
+
261
+ // packages/fly-node/src/lib/schemas/status-extended.schema.ts
262
+ import { z as z17 } from "zod";
263
+
264
+ // packages/fly-node/src/lib/schemas/status.schema.ts
265
+ import { z as z16 } from "zod";
266
+ var statusFlyResponseSchema = z16.object({
267
+ deployed: z16.boolean(),
268
+ hostname: z16.string(),
269
+ id: z16.string(),
270
+ machines: z16.array(
271
+ z16.object({
272
+ id: z16.string(),
273
+ name: z16.string(),
274
+ state: z16.string(),
275
+ region: z16.string(),
276
+ createdAt: z16.string().datetime(),
277
+ updatedAt: z16.string().datetime(),
278
+ config: z16.object({
279
+ env: z16.record(z16.string()),
280
+ metadata: z16.record(z16.string())
281
+ }),
282
+ events: z16.array(
283
+ z16.object({
284
+ type: z16.string(),
285
+ status: z16.string(),
286
+ timestamp: z16.number()
287
+ })
288
+ ),
289
+ checks: z16.array(
290
+ z16.object({
291
+ name: z16.string(),
292
+ status: z16.string(),
293
+ output: z16.string(),
294
+ updatedAt: z16.string().datetime()
295
+ })
296
+ ).optional(),
297
+ hostStatus: z16.string()
298
+ })
299
+ ),
300
+ name: z16.string(),
301
+ organization: z16.object({
302
+ id: z16.string(),
303
+ slug: z16.string()
304
+ }),
305
+ status: z16.string(),
306
+ version: z16.number()
307
+ });
308
+ var StatusTransformedResponseSchema = withCamelCase(
309
+ statusFlyResponseSchema,
310
+ {
311
+ preserve: ["machines.config.env", "machines.config.metadata"],
312
+ specialCases: { AppURL: "appUrl" }
313
+ }
314
+ );
315
+
316
+ // packages/fly-node/src/lib/schemas/status-extended.schema.ts
317
+ var StatusExtendedTransformedResponseSchema = withCamelCase(
318
+ statusFlyResponseSchema.extend({
319
+ domains: z17.array(z17.object({ hostname: z17.string() })),
320
+ secrets: z17.array(z17.object({ name: z17.string() }))
321
+ }),
322
+ {
323
+ preserve: ["machines.config.env", "machines.config.metadata"]
324
+ }
325
+ );
326
+
327
+ // packages/fly-node/src/lib/fly.class.ts
328
+ var Fly = class {
329
+ /** Use underscore to avoid conflict with public `config` property */
330
+ _config;
331
+ /**
332
+ * Whether a user is authenticated via local login.
333
+ * In this case a token is not needed, though it can still have been provided.
334
+ */
335
+ authByLogin = false;
336
+ initialized = false;
337
+ logger;
338
+ /**
339
+ * Get the app name from the instance config
340
+ */
341
+ get instanceApp() {
342
+ if ("app" in this._config) {
343
+ return this._config.app ?? "";
344
+ }
345
+ return "";
346
+ }
347
+ /**
348
+ * Get the config file path from the instance config
349
+ */
350
+ get instanceConfig() {
351
+ if ("config" in this._config) {
352
+ return this._config.config ?? "";
353
+ }
354
+ return "";
355
+ }
356
+ constructor(config) {
357
+ this._config = config || {};
358
+ this.logger = {
359
+ info: config?.logger?.info || console.log,
360
+ error: config?.logger?.error || console.error,
361
+ traceCLI: config?.logger?.traceCLI || false
362
+ };
363
+ if (!this._config.token) {
364
+ this._config.token = process.env["FLY_API_TOKEN"] || "";
365
+ }
366
+ }
367
+ /**
368
+ * Verify that the Fly client is ready to use.
369
+ *
370
+ * This means that the Fly CLI is installed and authenticated to Fly.io.
371
+ *
372
+ * Use as ad-hoc check when needed instead of waiting for the first Fly command to run.
373
+ *
374
+ * @param mode - Whether to use assertion mode instead of returning `false`
375
+ * @returns `true` if the Fly client is ready, `false` otherwise
376
+ * @throws An error in assertion mode if the Fly client is not ready
377
+ */
378
+ async isReady(mode) {
379
+ try {
380
+ await this.ensureInitialized();
381
+ return true;
382
+ } catch (error) {
383
+ if (mode === "assert") {
384
+ throw error;
385
+ }
386
+ this.logger.info(`Fly client is not ready
387
+ ${error}`);
388
+ return false;
389
+ }
390
+ }
391
+ /**
392
+ * Manage the Fly CLI tool
393
+ */
394
+ cli = {
395
+ /**
396
+ * Check if the Fly CLI tool is installed
397
+ *
398
+ * @returns `true` if the Fly CLI tool is installed, `false` otherwise
399
+ */
400
+ isInstalled: async () => await this.isInstalled()
401
+ };
402
+ //
403
+ // External API following the `flyctl` CLI commands structure
404
+ //
405
+ /**
406
+ * Manage apps
407
+ */
408
+ apps = {
409
+ /**
410
+ * Create a new application with a generated name when not provided.
411
+ *
412
+ * @param options - Options for creating an application
413
+ * @returns The name of the created application
414
+ * @throws An error if the application cannot be created
415
+ */
416
+ create: async (options) => {
417
+ try {
418
+ await this.ensureInitialized();
419
+ const { name } = await this.createApp(options);
420
+ this.logger.info(`Application '${name}' was created`);
421
+ return name;
422
+ } catch (error) {
423
+ throw new Error(
424
+ `[create app] something broke, check your apps
425
+ ${error}`
426
+ );
427
+ }
428
+ },
429
+ /**
430
+ * Destroy an application and make sure it gets detached from any Postgres clusters
431
+ *
432
+ * @param app - The name of the app to destroy
433
+ * @param options - Options for destroying an application
434
+ * @throws An error if the app cannot be destroyed
435
+ */
436
+ destroy: async (app, options) => {
437
+ try {
438
+ await this.ensureInitialized();
439
+ const attachedClusters = await this.getAttachedPostgresClusters(app);
440
+ for (const cluster of attachedClusters) {
441
+ this.logger.info(
442
+ `Detaching Postgres cluster '${cluster}' from application '${app}'`
443
+ );
444
+ await this.detachPostgres(cluster, app);
445
+ }
446
+ await this.destroyApp(app, options?.force);
447
+ this.logger.info(`Application '${app}' was destroyed`);
448
+ } catch (error) {
449
+ throw new Error(
450
+ `[destroy app] something broke, check your apps
451
+ ${error}`
452
+ );
453
+ }
454
+ },
455
+ /**
456
+ * List all applications
457
+ *
458
+ * @returns A list of applications
459
+ * @throws An error if listing applications fails
460
+ */
461
+ list: async () => {
462
+ try {
463
+ return await this.fetchAllApps("throwOnError");
464
+ } catch (error) {
465
+ throw new Error(`[list] something broke
466
+ ${error}`);
467
+ }
468
+ }
469
+ };
470
+ /**
471
+ * Manage certificates
472
+ */
473
+ certs = {
474
+ /**
475
+ * Add a certificate for a domain to an application
476
+ *
477
+ * @param hostname - The hostname to add a certificate for
478
+ * @param options - Options for adding a certificate
479
+ * @throws An error if the certificate cannot be added
480
+ */
481
+ add: async (hostname, options) => {
482
+ try {
483
+ await this.ensureInitialized();
484
+ const appName = await this.addAppCertificate(hostname, options);
485
+ this.logger.info(
486
+ `Certificate for domain '${hostname}' was added to '${appName}'`
487
+ );
488
+ } catch (error) {
489
+ throw new Error(
490
+ `[add certificate] something broke, check your app certificates
491
+ ${error}`
492
+ );
493
+ }
494
+ },
495
+ /**
496
+ * List certificates for an application
497
+ *
498
+ * @param options - List certificates for an application or all certificates
499
+ * @returns A list of certificates
500
+ * @throws An error if listing certificates fails
501
+ */
502
+ list: async (options) => {
503
+ try {
504
+ await this.ensureInitialized();
505
+ const result = options === "all" ? await this.fetchAllCerts("throwOnError") : await this.fetchAppCerts("throwOnError", options);
506
+ return result;
507
+ } catch (error) {
508
+ throw new Error(`[list certificates] something broke
509
+ ${error}`);
510
+ }
511
+ },
512
+ /**
513
+ * Remove a certificate for a domain from an application
514
+ *
515
+ * @param hostname - The hostname to remove a certificate for
516
+ * @param options - Options for removing a certificate
517
+ * @throws An error if the certificate cannot be removed
518
+ */
519
+ remove: async (hostname, options) => {
520
+ try {
521
+ await this.ensureInitialized();
522
+ const appName = await this.removeAppCertificate(hostname, options);
523
+ this.logger.info(
524
+ `Certificate for domain '${hostname}' was removed from '${appName}'`
525
+ );
526
+ } catch (error) {
527
+ throw new Error(
528
+ `[remove certificate] something broke, check your app certificates
529
+ ${error}`
530
+ );
531
+ }
532
+ }
533
+ };
534
+ /**
535
+ * Manage an app's configuration
536
+ */
537
+ config = {
538
+ /**
539
+ * Show an application's configuration.
540
+ *
541
+ * @param options - Options for showing an application's configuration
542
+ * @returns The application's JSON configuration
543
+ * @throws An error if the configuration cannot be found or parsed
544
+ */
545
+ show: async (options) => {
546
+ try {
547
+ await this.ensureInitialized();
548
+ return await this.showConfig("throwOnError", options);
549
+ } catch (error) {
550
+ throw new Error(`[show config] something broke
551
+ ${error}`);
552
+ }
553
+ }
554
+ };
555
+ /**
556
+ * Deploy an application.
557
+ *
558
+ * A valid config file is required but the app doesn't have to exist,
559
+ * since it gets created if needed.
560
+ *
561
+ * The app name is selected from:
562
+ * 1. Provided app name
563
+ * 2. Instance app name
564
+ * 3. App name from the provided config file
565
+ *
566
+ * Existing secrets are preserved.
567
+ *
568
+ * @param options - Options for deploying an application
569
+ * @throws An error if the deployment fails
570
+ */
571
+ deploy = async (options) => {
572
+ try {
573
+ await this.ensureInitialized();
574
+ const appName = await this.deployApp(options);
575
+ this.logger.info(`Application '${appName}' was deployed`);
576
+ const status = await this.fetchAppStatus("throwOnError", {
577
+ app: appName
578
+ });
579
+ return DeployResponseSchema.parse({
580
+ app: status.name,
581
+ hostname: status.hostname,
582
+ url: `https://${status.hostname}`
583
+ });
584
+ } catch (error) {
585
+ throw new Error(
586
+ `[deploy] something broke, check your deployments
587
+ ${error}`
588
+ );
589
+ }
590
+ };
591
+ /**
592
+ * Manage application secrets
593
+ */
594
+ secrets = {
595
+ /**
596
+ * Set secrets for an application
597
+ *
598
+ * @param secrets - The secrets to set
599
+ * @param options - Options for setting secrets
600
+ * @throws An error if the secrets cannot be set
601
+ */
602
+ set: async (secrets, options) => {
603
+ try {
604
+ await this.ensureInitialized();
605
+ const appName = await this.setAppSecrets(secrets, options);
606
+ const keys = Object.keys(secrets);
607
+ this.logger.info(
608
+ `Secrets were set for '${appName}': ${keys.join(", ")}`
609
+ );
610
+ } catch (error) {
611
+ throw new Error(
612
+ `[set secrets] something broke, check your app secrets
613
+ ${error}`
614
+ );
615
+ }
616
+ },
617
+ /**
618
+ * List secrets for an application
619
+ *
620
+ * @param options - List secrets for an application or all secrets
621
+ * @returns A list of secrets
622
+ * @throws An error if listing secrets fails
623
+ */
624
+ list: async (options) => {
625
+ try {
626
+ await this.ensureInitialized();
627
+ const result = options === "all" ? await this.fetchAllSecrets("throwOnError") : await this.fetchAppSecrets("throwOnError", options);
628
+ return result;
629
+ } catch (error) {
630
+ throw new Error(`[list secrets] something broke
631
+ ${error}`);
632
+ }
633
+ },
634
+ /**
635
+ * Unset secrets for an application
636
+ *
637
+ * @param keys - The keys to unset
638
+ * @param options - Options for unsetting secrets
639
+ * @throws An error if the secrets cannot be unset
640
+ */
641
+ unset: async (keys, options) => {
642
+ try {
643
+ await this.ensureInitialized();
644
+ const keysArray = Array.isArray(keys) ? keys : [keys];
645
+ const appName = await this.unsetAppSecrets(keysArray, options);
646
+ this.logger.info(
647
+ `Secrets were unset for '${appName}': ${keysArray.join(", ")}`
648
+ );
649
+ } catch (error) {
650
+ throw new Error(
651
+ `[unset secrets] something broke, check your app secrets
652
+ ${error}`
653
+ );
654
+ }
655
+ }
656
+ };
657
+ /**
658
+ * Get the status details of an application
659
+ *
660
+ * @param options - Options for getting app status
661
+ * @returns The app status, or `null` if an app could not be found
662
+ */
663
+ status = async (options) => {
664
+ try {
665
+ await this.ensureInitialized();
666
+ const status = await this.fetchAppStatus("nullOnError", options);
667
+ if (status === null) {
668
+ return null;
669
+ }
670
+ return status;
671
+ } catch (error) {
672
+ this.logger.info(`[status] something broke
673
+ ${error}`);
674
+ return null;
675
+ }
676
+ };
677
+ /**
678
+ * Get the extended details of an application
679
+ *
680
+ * @param options - Options for getting app details
681
+ * @returns The app details, or `null` if an app could not be found
682
+ */
683
+ statusExtended = async (options) => {
684
+ try {
685
+ await this.ensureInitialized();
686
+ const status = await this.fetchAppStatus("nullOnError", options);
687
+ if (status === null) {
688
+ return null;
689
+ }
690
+ const certs = await this.fetchAppCerts("nullOnError", options) || [];
691
+ const secrets = await this.fetchAppSecrets("nullOnError", options) || [];
692
+ return StatusExtendedTransformedResponseSchema.parse({
693
+ ...status,
694
+ domains: certs.map(({ hostname }) => ({ hostname })),
695
+ secrets: secrets.map(({ name }) => ({ name }))
696
+ });
697
+ } catch (error) {
698
+ this.logger.info(`[status extended] something broke
699
+ ${error}`);
700
+ return null;
701
+ }
702
+ };
703
+ //
704
+ // Private methods
705
+ //
706
+ /**
707
+ * @private
708
+ * A name will be generated when not provided.
709
+ * @returns The name of the created application
710
+ * @throws An error if the application cannot be created
711
+ */
712
+ async createApp(options) {
713
+ const args = ["apps", "create"];
714
+ args.push(options?.app || "--generate-name");
715
+ args.push("--org", options?.org || this._config.org || "personal");
716
+ args.push("--json");
717
+ return AppsCreateTransformedResponseSchema.parseAsync(
718
+ await this.execFly(args)
719
+ );
720
+ }
721
+ /**
722
+ * @private
723
+ * @returns The name of the deployed application
724
+ * @throws An error if the deployment fails
725
+ */
726
+ async deployApp(options) {
727
+ let appName = "";
728
+ let appSecrets = [];
729
+ let lookupApp = options?.app || this.instanceApp;
730
+ const lookupConfig = options?.config || this.instanceConfig;
731
+ if (!lookupConfig) {
732
+ throw new Error(
733
+ "Fly config file must be provided to options or class instance, unable to deploy"
734
+ );
735
+ }
736
+ const appConfig = await this.showConfig("nullOnError", {
737
+ config: lookupConfig,
738
+ local: true
739
+ });
740
+ if (!appConfig) {
741
+ throw new Error(
742
+ `Fly config file '${lookupConfig}' does not exist, unable to deploy`
743
+ );
744
+ }
745
+ if (!lookupApp) {
746
+ lookupApp = appConfig.app;
747
+ }
748
+ if (lookupApp) {
749
+ const status = await this.fetchAppStatus("nullOnError", {
750
+ app: lookupApp
751
+ });
752
+ if (status) {
753
+ this.logger.info(
754
+ `Found existing application '${lookupApp}' as target for deployment`
755
+ );
756
+ appName = status.name;
757
+ } else {
758
+ this.logger.info(
759
+ `Application '${lookupApp}' not found, try to create a new one with this name`
760
+ );
761
+ }
762
+ }
763
+ if (!appName) {
764
+ this.logger.info("Creating a new application...");
765
+ const { name } = await this.createApp({
766
+ app: lookupApp,
767
+ org: options?.org
768
+ });
769
+ appName = name;
770
+ this.logger.info(`Application '${appName}' was created`);
771
+ } else {
772
+ appSecrets = await this.fetchAppSecrets("throwOnError", { app: appName });
773
+ this.logger.info(`Updating existing application '${appName}'`);
774
+ }
775
+ NameSchema.parse(appName);
776
+ if (options?.secrets) {
777
+ const existingSecrets = new Set(appSecrets.map(({ name }) => name));
778
+ const newSecrets = {};
779
+ for (const [key, value] of Object.entries(options.secrets)) {
780
+ if (!existingSecrets.has(key)) {
781
+ newSecrets[key] = value;
782
+ } else {
783
+ this.logger.info(
784
+ `Secret '${key}' already exists for '${appName}', skipping`
785
+ );
786
+ }
787
+ }
788
+ const keys = Object.keys(newSecrets);
789
+ if (keys.length > 0) {
790
+ this.logger.info(`Adding secrets to '${appName}': ${keys.join(", ")}`);
791
+ await this.setAppSecrets(newSecrets, {
792
+ app: appName,
793
+ stage: true
794
+ });
795
+ }
796
+ }
797
+ if (options?.app && options.app !== appName) {
798
+ this.logger.info(
799
+ `Using provided app name '${options.app}' instead of '${appName}'`
800
+ );
801
+ appName = options.app;
802
+ }
803
+ if (options?.postgres) {
804
+ const users = await this.fetchPostgresUsers(
805
+ options.postgres,
806
+ "nullOnError"
807
+ );
808
+ if (!users) {
809
+ this.logger.error(
810
+ `Failed to fetch users for Postgres cluster '${options.postgres}', unable to attach '${appName}'`
811
+ );
812
+ } else if (users.find((user) => user.username === appName.replace(/-/g, "_"))) {
813
+ this.logger.info(
814
+ `Postgres cluster '${options.postgres}' already attached to '${appName}', skipping`
815
+ );
816
+ } else {
817
+ this.logger.info(
818
+ `Attach Postgres cluster '${options.postgres}' to '${appName}'`
819
+ );
820
+ await this.attachPostgres(options.postgres, appName);
821
+ }
822
+ }
823
+ const args = ["deploy", "--app", appName, "--config", lookupConfig];
824
+ if (options?.region) {
825
+ args.push("--region", options.region);
826
+ }
827
+ if (options?.environment) {
828
+ args.push("--env", `DEPLOY_ENV=${options.environment}`);
829
+ }
830
+ for (const [key, value] of Object.entries(options?.env || {})) {
831
+ args.push("--env", `${key}=${this.safeArg(value)}`);
832
+ }
833
+ args.push("--yes");
834
+ this.logger.info(`Deploying '${appName}'...`);
835
+ await this.execFly(args);
836
+ return appName;
837
+ }
838
+ /**
839
+ * @private
840
+ * @throws An error if the Postgres database cannot be attached
841
+ */
842
+ async attachPostgres(postgres, app) {
843
+ const args = ["postgres", "attach", postgres, "--app", app, "--yes"];
844
+ await this.execFly(args);
845
+ }
846
+ /**
847
+ * @private
848
+ * @throws An error if the app cannot be destroyed
849
+ */
850
+ async destroyApp(app, force) {
851
+ const args = ["apps", "destroy", app, "--yes"];
852
+ if (force)
853
+ args.push("--force");
854
+ await this.execFly(args);
855
+ }
856
+ /**
857
+ * @private
858
+ * @throws An error if the Postgres database cannot be detached from an app
859
+ */
860
+ async detachPostgres(postgres, app) {
861
+ const args = ["postgres", "detach", postgres, "--app", app];
862
+ await this.execFly(args);
863
+ }
864
+ /**
865
+ * @private
866
+ * @returns The name of the application
867
+ * @throws An error if the secrets cannot be set
868
+ */
869
+ async setAppSecrets(secrets, options) {
870
+ const status = await this.fetchAppStatus("throwOnError", options);
871
+ const args = ["secrets", "set"];
872
+ args.push(...this.getAppOrConfigArgs(options));
873
+ if (options?.stage) {
874
+ args.push("--stage");
875
+ }
876
+ for (const [key, value] of Object.entries(secrets)) {
877
+ args.push(`${key}=${this.safeArg(value)}`);
878
+ }
879
+ await this.execFly(args);
880
+ return NameSchema.parse(status.name);
881
+ }
882
+ /**
883
+ * @private
884
+ * @returns The name of the application
885
+ * @throws An error if the secrets cannot be unset
886
+ */
887
+ async unsetAppSecrets(keys, options) {
888
+ const status = await this.fetchAppStatus("throwOnError", options);
889
+ const args = ["secrets", "unset"];
890
+ args.push(...this.getAppOrConfigArgs(options));
891
+ if (options?.stage) {
892
+ args.push("--stage");
893
+ }
894
+ args.push(...keys);
895
+ await this.execFly(args);
896
+ return NameSchema.parse(status.name);
897
+ }
898
+ /**
899
+ * @private
900
+ * @returns The name of the application
901
+ * @throws An error if the domain cannot be added
902
+ */
903
+ async addAppCertificate(hostname, options) {
904
+ const status = await this.fetchAppStatus("throwOnError", options);
905
+ const args = ["certs", "add", hostname];
906
+ args.push(...this.getAppOrConfigArgs(options));
907
+ args.push("--json");
908
+ await this.execFly(args);
909
+ return NameSchema.parse(status.name);
910
+ }
911
+ /**
912
+ * @private
913
+ * @returns The name of the application
914
+ * @throws An error if the domain cannot be removed
915
+ */
916
+ async removeAppCertificate(hostname, options) {
917
+ const status = await this.fetchAppStatus("throwOnError", options);
918
+ const args = ["certs", "remove", hostname];
919
+ args.push(...this.getAppOrConfigArgs(options));
920
+ args.push("--yes");
921
+ await this.execFly(args);
922
+ return NameSchema.parse(status.name);
923
+ }
924
+ async fetchAllApps(onError) {
925
+ const args = ["apps", "list", "--json"];
926
+ try {
927
+ return AppsListTransformedResponseSchema.parseAsync(
928
+ await this.execFly(args)
929
+ );
930
+ } catch (error) {
931
+ if (onError === "throwOnError") {
932
+ throw error;
933
+ }
934
+ return null;
935
+ }
936
+ }
937
+ async fetchAllCerts(onError) {
938
+ try {
939
+ const certs = [];
940
+ const apps = await this.fetchAllApps("throwOnError");
941
+ for (const app of apps) {
942
+ const appCerts = await this.fetchAppCerts("throwOnError", {
943
+ app: app.name
944
+ });
945
+ certs.push(...appCerts.map((cert) => ({ ...cert, app: app.name })));
946
+ }
947
+ return CertsListWithAppTransformedResponseSchema.parse(certs);
948
+ } catch (error) {
949
+ if (onError === "throwOnError") {
950
+ throw error;
951
+ }
952
+ return null;
953
+ }
954
+ }
955
+ async fetchAllPostgres(onError) {
956
+ const args = ["postgres", "list", "--json"];
957
+ try {
958
+ const response = await this.execFly(args);
959
+ return PostgresListTransformedResponseSchema.parse(response);
960
+ } catch (error) {
961
+ if (onError === "throwOnError") {
962
+ throw error;
963
+ }
964
+ return null;
965
+ }
966
+ }
967
+ async fetchAllSecrets(onError) {
968
+ try {
969
+ const secrets = [];
970
+ const apps = await this.fetchAllApps("throwOnError");
971
+ for (const app of apps) {
972
+ const appSecrets = await this.fetchAppSecrets("throwOnError", {
973
+ app: app.name
974
+ });
975
+ secrets.push(
976
+ ...appSecrets.map((secret) => ({ ...secret, app: app.name }))
977
+ );
978
+ }
979
+ return SecretsListWithAppTransformedResponseSchema.parse(secrets);
980
+ } catch (error) {
981
+ if (onError === "throwOnError") {
982
+ throw error;
983
+ }
984
+ return null;
985
+ }
986
+ }
987
+ async fetchAppStatus(onError, options) {
988
+ const args = ["status"];
989
+ args.push(...this.getAppOrConfigArgs(options));
990
+ args.push("--json");
991
+ let response = null;
992
+ try {
993
+ response = await this.execFly(args);
994
+ return StatusTransformedResponseSchema.parse(response);
995
+ } catch (error) {
996
+ if (onError === "throwOnError") {
997
+ throw error;
998
+ }
999
+ if (error instanceof ZodError) {
1000
+ this.logger.info(`Failed to parse response:
1001
+ ${error.message}`);
1002
+ this.logger.info(`Raw response:
1003
+ ${JSON.stringify(response, null, 2)}`);
1004
+ }
1005
+ return null;
1006
+ }
1007
+ }
1008
+ async fetchAppCerts(onError, options) {
1009
+ const args = ["certs", "list"];
1010
+ args.push(...this.getAppOrConfigArgs(options));
1011
+ args.push("--json");
1012
+ try {
1013
+ return CertsListTransformedResponseSchema.parseAsync(
1014
+ await this.execFly(args)
1015
+ );
1016
+ } catch (error) {
1017
+ if (onError === "throwOnError") {
1018
+ throw error;
1019
+ }
1020
+ return null;
1021
+ }
1022
+ }
1023
+ async fetchAppSecrets(onError, options) {
1024
+ const args = ["secrets", "list"];
1025
+ args.push(...this.getAppOrConfigArgs(options));
1026
+ args.push("--json");
1027
+ try {
1028
+ return SecretsListTransformedResponseSchema.parseAsync(
1029
+ await this.execFly(args)
1030
+ );
1031
+ } catch (error) {
1032
+ if (onError === "throwOnError") {
1033
+ throw error;
1034
+ }
1035
+ return null;
1036
+ }
1037
+ }
1038
+ async fetchPostgresUsers(postgresApp, onError) {
1039
+ const args = ["postgres", "users", "list", "--app", postgresApp, "--json"];
1040
+ try {
1041
+ const users = await this.execFly(args);
1042
+ return PostgresUsersListTransformedResponseSchema.parse(users);
1043
+ } catch (error) {
1044
+ if (onError === "throwOnError") {
1045
+ throw error;
1046
+ }
1047
+ return null;
1048
+ }
1049
+ }
1050
+ async showConfig(onError, options) {
1051
+ const normalized = this.normalizeOptions(options);
1052
+ const config = normalized.config || this.instanceConfig;
1053
+ if (config && !existsSync(join(cwd(), config))) {
1054
+ throw new Error(`Config file '${config}' does not exist`);
1055
+ }
1056
+ const args = ["config", "show"];
1057
+ args.push(...this.getAppOrConfigArgs(options));
1058
+ if (options && "local" in options && options.local) {
1059
+ args.push("--local");
1060
+ }
1061
+ try {
1062
+ return ConfigShowResponseSchema.parse(await this.execFly(args));
1063
+ } catch (error) {
1064
+ if (onError === "throwOnError") {
1065
+ throw error;
1066
+ }
1067
+ return null;
1068
+ }
1069
+ }
1070
+ /**
1071
+ * @private
1072
+ * Ensure Fly CLI is installed and authenticated
1073
+ *
1074
+ * @throws An error if Fly CLI is not installed or authentication fails
1075
+ */
1076
+ async ensureInitialized() {
1077
+ if (this.initialized)
1078
+ return;
1079
+ try {
1080
+ if (!await this.isInstalled()) {
1081
+ throw new Error("Fly CLI must be installed to use this library");
1082
+ }
1083
+ this.logger.info("Authenticating with Fly.io...");
1084
+ let user = await this.execFly(
1085
+ ["auth", "whoami"],
1086
+ "nullOnError",
1087
+ true
1088
+ // won't use token
1089
+ );
1090
+ if (user) {
1091
+ this.logger.info(`Detected logged in user '${user}'`);
1092
+ this.authByLogin = true;
1093
+ } else {
1094
+ user = await this.execFly(["auth", "whoami"]);
1095
+ this.logger.info(`Authenticated by token as '${user}'`);
1096
+ }
1097
+ this.initialized = true;
1098
+ } catch (error) {
1099
+ this.logger.error("Failed to initialize Fly");
1100
+ throw error;
1101
+ }
1102
+ }
1103
+ async execFly(command, onError = "throwOnError", skipToken) {
1104
+ const cmdArr = Array.isArray(command) ? command : [command];
1105
+ if (!skipToken && !this.authByLogin && this._config.token) {
1106
+ cmdArr.push("--access-token", this._config.token);
1107
+ }
1108
+ const flyCmd = `flyctl ${cmdArr.filter(Boolean).join(" ")}`;
1109
+ let stdout = "";
1110
+ try {
1111
+ this.traceCLI("CALL", flyCmd);
1112
+ const result = await exec(flyCmd);
1113
+ stdout = result.stdout.trim();
1114
+ this.traceCLI("RESULT", stdout);
1115
+ } catch (error) {
1116
+ this.traceCLI("RESULT", error);
1117
+ if (onError === "throwOnError") {
1118
+ throw new Error(`Command failed: ${flyCmd}
1119
+ ${error}`);
1120
+ }
1121
+ return null;
1122
+ }
1123
+ try {
1124
+ return JSON.parse(stdout);
1125
+ } catch {
1126
+ if (stdout) {
1127
+ if (this.logger.traceCLI) {
1128
+ this.logger.info(`Failed to parse as JSON, returning raw output`);
1129
+ }
1130
+ return stdout;
1131
+ }
1132
+ }
1133
+ return void 0;
1134
+ }
1135
+ /**
1136
+ * @private
1137
+ * Get the arguments for `AppOrConfig` options
1138
+ * where either the application or configuration can be provided
1139
+ * but not both.
1140
+ *
1141
+ * First check `options` and then the class configuration.
1142
+ *
1143
+ * Should be used in Fly commands with optional flags
1144
+ * - `--app`
1145
+ * - `--config`
1146
+ *
1147
+ * @param options - Options to get the arguments for
1148
+ * @returns The arguments to use in a fly command
1149
+ */
1150
+ getAppOrConfigArgs(options) {
1151
+ const normalized = this.normalizeOptions(options);
1152
+ const app = normalized.app || this.instanceApp;
1153
+ const config = normalized.config || this.instanceConfig;
1154
+ const args = [];
1155
+ if (app) {
1156
+ args.push("--app", app);
1157
+ }
1158
+ if (config) {
1159
+ args.push("--config", config);
1160
+ }
1161
+ if (app && config) {
1162
+ this.logger.info(
1163
+ `Both app '${app}' and config '${config}' were provided, check your implementation!`
1164
+ );
1165
+ }
1166
+ return args;
1167
+ }
1168
+ /**
1169
+ * @private
1170
+ * Get the Postgres clusters attached to an app
1171
+ *
1172
+ * @param app - The app to get the attached Postgres clusters for
1173
+ * @returns The attached Postgres clusters
1174
+ * @throws An error if the Postgres clusters cannot be retrieved
1175
+ */
1176
+ async getAttachedPostgresClusters(app) {
1177
+ const attached = /* @__PURE__ */ new Set();
1178
+ const postgres = await this.fetchAllPostgres("throwOnError");
1179
+ for (const { name } of postgres) {
1180
+ const users = await this.fetchPostgresUsers(name, "nullOnError");
1181
+ if (!users) {
1182
+ this.logger.info(
1183
+ `Failed to fetch users for Postgres cluster '${name}', ignoring`
1184
+ );
1185
+ continue;
1186
+ }
1187
+ if (users.some((user) => user.username === app.replace(/-/g, "_"))) {
1188
+ attached.add(name);
1189
+ }
1190
+ }
1191
+ return Array.from(attached);
1192
+ }
1193
+ /**
1194
+ * @private
1195
+ * Check if the Fly CLI is installed
1196
+ *
1197
+ * @returns `true` if the Fly CLI is installed, `false` otherwise
1198
+ */
1199
+ async isInstalled() {
1200
+ return await this.execFly("version", "nullOnError") !== null;
1201
+ }
1202
+ /**
1203
+ * @private
1204
+ * Normalize the options matching `AppOrConfig` type.
1205
+ *
1206
+ * A missing value gets an empty string.
1207
+ *
1208
+ * @param options - The options to normalize
1209
+ * @returns The normalized options
1210
+ */
1211
+ normalizeOptions(options) {
1212
+ if (!options) {
1213
+ return { app: "", config: "" };
1214
+ }
1215
+ const app = "app" in options && options.app ? options.app : "";
1216
+ const config = "config" in options && options.config ? options.config : "";
1217
+ return { app, config };
1218
+ }
1219
+ /**
1220
+ * Escape an argument for Fly cli
1221
+ *
1222
+ * @param arg - The argument to escape
1223
+ * @returns The escaped argument
1224
+ */
1225
+ safeArg(arg) {
1226
+ return arg.replace(/\\/g, "\\\\").replace(/ /g, "\\ ");
1227
+ }
1228
+ /**
1229
+ * @private
1230
+ * Trace the CLI calls, mocks and results
1231
+ *
1232
+ * @param type - The type of trace
1233
+ * @param msg - The message to trace
1234
+ */
1235
+ traceCLI(type, msg) {
1236
+ if (this.logger.traceCLI) {
1237
+ const typeLabel = type === "CALL" ? " CALL " : type === "MOCK" ? " MOCK " : "RESULT";
1238
+ this.logger.info(`[${typeLabel}] ${msg}`);
1239
+ }
1240
+ }
1241
+ };
1242
+ export {
1243
+ Fly
1244
+ };