@basaltkit/deploy 0.2.1 → 0.3.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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { defineDeploy, secret, ask, pm2, compose, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, } from './config.js';
1
+ export { defineDeploy, secret, ask, pm2, compose, apache, caddy, none, external, bucketName, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, } from './config.js';
2
2
  export { main, loadConfig, createContext, USAGE } from './cli.js';
3
3
  export { nodeHost, consoleOutput } from './host.js';
4
4
  export { DeployError, INSTALL_COMMAND, RUN_COMMAND } from './context.js';
package/dist/infra.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { DockerInfra } from './config.js';
2
- import type { DeployContext, Finding } from './context.js';
2
+ import { type DeployContext, type Finding } from './context.js';
3
3
  import type { EnvChange } from './dotenv.js';
4
+ import { type PostgresHandle } from './services.js';
4
5
  /**
5
6
  * Dedicated containers, adopted or created (RFC 0006 §6.3).
6
7
  *
@@ -32,6 +33,8 @@ export interface InfraPlan {
32
33
  findings: Finding[];
33
34
  /** Values compose interpolates (`${BASALT_PG_PASSWORD}`); passed in its environment only. */
34
35
  secrets: Record<string, string>;
36
+ /** The dedicated Postgres's owner URL, as the `.env` will hold it (the app role's is derived from it). */
37
+ ownerUrl?: string;
35
38
  }
36
39
  export declare function planInfra(ctx: DeployContext, values: Map<string, string>): Promise<InfraPlan>;
37
40
  /** The compose file, with no secret in it: compose interpolates them from its environment. */
@@ -39,4 +42,12 @@ export declare function renderCompose(app: string, infra: DockerInfra, plan: Inf
39
42
  export declare const composeFile: (ctx: DeployContext) => string;
40
43
  /** Starts (or reconciles) the containers, waits for health, proves the credentials, creates the buckets. */
41
44
  export declare function applyInfra(ctx: DeployContext, plan: InfraPlan): Promise<Finding[]>;
45
+ /** The dedicated Postgres as its owner, over TCP — the credentials the `.env` holds. */
46
+ export declare function dockerPostgres(plan: InfraPlan): PostgresHandle | undefined;
47
+ /**
48
+ * After the containers are up (dedicated) or found running (external): the
49
+ * app role and the buckets (RFC 0007 §4.1–4.2). Returns what it did, one line
50
+ * per service; throws on what it could not do — before anything is built.
51
+ */
52
+ export declare function maintainServices(ctx: DeployContext, plan: InfraPlan, values: Map<string, string>): Promise<string[]>;
42
53
  export declare function describeInfra(plan: InfraPlan): string[];
package/dist/infra.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { join } from 'node:path';
2
+ import { DeployError } from './context.js';
2
3
  import { freePort } from './ports.js';
4
+ import { appRoleEnv, appRoleOf, ensureAppRole, ensureBuckets, externalFindings, externalOf, externalPostgres, minioHandle } from './services.js';
3
5
  async function inspect(ctx, container) {
4
6
  const result = await ctx.host.exec('docker', ['inspect', container, '--format', '{{json .Config.Env}}\t{{json .HostConfig.PortBindings}}']);
5
7
  if (result.code !== 0)
@@ -41,15 +43,22 @@ function urlParts(value) {
41
43
  return undefined;
42
44
  }
43
45
  }
44
- const names = (app, service) => {
46
+ const names = (app, service, container) => {
45
47
  const suffix = service === 'postgres' ? 'pg' : service;
46
48
  // Compose prefixes volumes with the project name — the app — so this is
47
49
  // what an older compose file with the same project name already created.
48
- return { container: `${app}-${suffix}`, volumeKey: `${app}-${suffix}-data`, volume: `${app}_${app}-${suffix}-data` };
50
+ return { container: container ?? `${app}-${suffix}`, volumeKey: `${app}-${suffix}-data`, volume: `${app}_${app}-${suffix}-data` };
49
51
  };
50
52
  export async function planInfra(ctx, values) {
51
53
  const infra = ctx.config.infra;
52
54
  const plan = { services: [], env: [], findings: [], secrets: {} };
55
+ if (infra?.kind === 'external') {
56
+ plan.findings.push(...await externalFindings(ctx));
57
+ const pg = infra.postgres;
58
+ if (pg)
59
+ plan.env.push(...appRoleEnv(ctx, values, values.get(pg.urlKey ?? 'DATABASE_URL')));
60
+ return plan;
61
+ }
53
62
  if (infra?.kind !== 'docker')
54
63
  return plan;
55
64
  const { app } = ctx.config;
@@ -71,7 +80,7 @@ export async function planInfra(ctx, values) {
71
80
  });
72
81
  if (infra.postgres) {
73
82
  const pg = infra.postgres;
74
- const { container, volume } = names(app, 'postgres');
83
+ const { container, volume } = names(app, 'postgres', pg.container);
75
84
  const running = await inspect(ctx, container);
76
85
  const fromEnv = urlParts(values.get(pg.urlKey));
77
86
  let password = running?.env.get('POSTGRES_PASSWORD');
@@ -90,13 +99,15 @@ export async function planInfra(ctx, values) {
90
99
  const database = running?.env.get('POSTGRES_DB') ?? fromEnv?.database ?? pg.database;
91
100
  const port = await pick(pg.port, running?.ports.get('5432/tcp') ?? fromEnv?.port, 5433);
92
101
  const params = new URLSearchParams(pg.urlParams).toString();
93
- setEnv(pg.urlKey, `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@127.0.0.1:${port}/${database}${params ? `?${params}` : ''}`, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new database' : 'port or parameters');
102
+ plan.ownerUrl = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@127.0.0.1:${port}/${database}${params ? `?${params}` : ''}`;
103
+ setEnv(pg.urlKey, plan.ownerUrl, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new database' : 'port or parameters');
104
+ plan.env.push(...appRoleEnv(ctx, values, plan.ownerUrl));
94
105
  plan.secrets['BASALT_PG_PASSWORD'] = password;
95
106
  plan.services.push({ service: 'postgres', container, volume, action: running ? 'adopt' : 'create', port, user, database, source });
96
107
  }
97
108
  if (infra.redis) {
98
109
  const redis = infra.redis;
99
- const { container, volume } = names(app, 'redis');
110
+ const { container, volume } = names(app, 'redis', redis.container);
100
111
  const running = await inspect(ctx, container);
101
112
  const fromEnv = urlParts(values.get(redis.urlKey));
102
113
  let password = running?.env.get('REDIS_PASSWORD');
@@ -117,7 +128,7 @@ export async function planInfra(ctx, values) {
117
128
  }
118
129
  if (infra.minio) {
119
130
  const minio = infra.minio;
120
- const { container, volume } = names(app, 'minio');
131
+ const { container, volume } = names(app, 'minio', minio.container);
121
132
  const running = await inspect(ctx, container);
122
133
  let user = running?.env.get('MINIO_ROOT_USER');
123
134
  let password = running?.env.get('MINIO_ROOT_PASSWORD');
@@ -224,15 +235,42 @@ export async function applyInfra(ctx, plan) {
224
235
  if (!check.stdout.includes('PONG'))
225
236
  findings.push({ id: 'C7', level: 'error', message: `redis refuses the password in ${ctx.config.env.file ?? '.env'}` });
226
237
  }
227
- if (service.service === 'minio' && infra.minio && infra.minio.buckets.length > 0) {
228
- const alias = `http://${encodeURIComponent(plan.secrets['BASALT_MINIO_USER'] ?? '')}:${encodeURIComponent(plan.secrets['BASALT_MINIO_PASSWORD'] ?? '')}@127.0.0.1:9000`;
229
- const made = await host.exec('docker', ['exec', '-e', 'MC_HOST_local', service.container, 'mc', 'mb', '-p', ...infra.minio.buckets.map((b) => `local/${b}`)], { env: { MC_HOST_local: alias } });
230
- if (made.code !== 0)
231
- findings.push({ id: 'C7', level: 'error', message: `minio refused to create the buckets: ${made.stderr.trim().split('\n')[0] ?? ''}` });
232
- }
233
238
  }
234
239
  return findings;
235
240
  }
241
+ /** The dedicated Postgres as its owner, over TCP — the credentials the `.env` holds. */
242
+ export function dockerPostgres(plan) {
243
+ const pg = plan.services.find((s) => s.service === 'postgres');
244
+ if (!pg)
245
+ return undefined;
246
+ return { container: pg.container, user: pg.user ?? '', database: pg.database ?? '', password: plan.secrets['BASALT_PG_PASSWORD'] ?? '', tcp: true, url: plan.ownerUrl };
247
+ }
248
+ /**
249
+ * After the containers are up (dedicated) or found running (external): the
250
+ * app role and the buckets (RFC 0007 §4.1–4.2). Returns what it did, one line
251
+ * per service; throws on what it could not do — before anything is built.
252
+ */
253
+ export async function maintainServices(ctx, plan, values) {
254
+ const lines = [];
255
+ const role = appRoleOf(ctx.config);
256
+ const pg = ctx.config.infra?.kind === 'docker' ? dockerPostgres(plan) : externalPostgres(ctx, values);
257
+ if (role) {
258
+ if (!pg)
259
+ throw new DeployError(`appRole ${role.name}: no Postgres declared to create it in`);
260
+ lines.push(await ensureAppRole(ctx, pg, role, values));
261
+ }
262
+ const infra = ctx.config.infra;
263
+ if (infra?.kind === 'docker' && infra.minio?.buckets.length) {
264
+ const minio = plan.services.find((s) => s.service === 'minio');
265
+ if (minio) {
266
+ lines.push(await ensureBuckets(ctx, { container: minio.container, user: plan.secrets['BASALT_MINIO_USER'] ?? '', password: plan.secrets['BASALT_MINIO_PASSWORD'] ?? '' }, infra.minio.buckets));
267
+ }
268
+ }
269
+ const external = externalOf(ctx.config)?.minio;
270
+ if (external?.buckets?.length)
271
+ lines.push(await ensureBuckets(ctx, await minioHandle(ctx, external.container), external.buckets));
272
+ return lines;
273
+ }
236
274
  export function describeInfra(plan) {
237
275
  return plan.services.map((s) => {
238
276
  const ports = s.consolePort === undefined ? `127.0.0.1:${s.port}` : `127.0.0.1:${s.port} (console ${s.consolePort})`;
package/dist/init.d.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type { Host } from './host.js';
2
+ /**
3
+ * `basalt-deploy init` — writes `deploy.config.ts` from what the project and,
4
+ * with `--server`, this server already say (RFC 0007 §3). It asks only what
5
+ * nothing can tell it: the domain, the tenancy, the branch.
6
+ *
7
+ * Detection reads files; it never imports the app. `src/env.ts` is parsed as
8
+ * text: the keys of its `defineEnv({ … })`, which are secrets, which have a
9
+ * default. The output is a complete config — `check` runs on it before `init`
10
+ * returns.
11
+ */
12
+ export interface EnvKeyFact {
13
+ name: string;
14
+ /** Declared with `secret(…)`: generated on the server. */
15
+ secret: boolean;
16
+ /** `.default(…)`, `.optional()` or `.catch(…)`: the app runs without it. */
17
+ optional: boolean;
18
+ }
19
+ export interface ComposeImageFact {
20
+ tag: string;
21
+ dockerfile: string;
22
+ context: string;
23
+ env: string;
24
+ }
25
+ export interface ComposeFact {
26
+ file: string;
27
+ images: ComposeImageFact[];
28
+ upstream: {
29
+ service: string;
30
+ port: number;
31
+ } | undefined;
32
+ /** Compose interpolation the upstream port came from, e.g. `{ API_HOST_PORT: '3001' }`. */
33
+ env: Record<string, string>;
34
+ }
35
+ export interface ProjectFacts {
36
+ app: string;
37
+ env: {
38
+ schema: string;
39
+ exportName: string;
40
+ keys: EnvKeyFact[];
41
+ } | undefined;
42
+ prisma: string[];
43
+ /** `prisma/tenants/…`: schema-per-tenant migrations. */
44
+ tenants: boolean;
45
+ /** A `db:deploy` script that is not plain `prisma migrate deploy`. */
46
+ migrateScript: string | undefined;
47
+ /** `build`, when `start` runs compiled output (`node dist/…`). */
48
+ buildScript: string | undefined;
49
+ web: string | undefined;
50
+ compose: ComposeFact | undefined;
51
+ server: {
52
+ vhosts: string[];
53
+ busyPorts: number[];
54
+ } | undefined;
55
+ /** `/readyz` when the app declares one (readiness: database and dependencies), else `/health`. */
56
+ health: '/readyz' | '/health';
57
+ }
58
+ export interface InitAnswers {
59
+ domain: string;
60
+ tenants: 'subdomain' | 'none';
61
+ branch: string;
62
+ proxy: 'apache' | 'caddy' | 'none';
63
+ }
64
+ export declare function detectProject(host: Host, dir: string, options?: {
65
+ server?: string | undefined;
66
+ }): Promise<ProjectFacts>;
67
+ /** `@acme/My App` → `my-app`, within C4's `[a-z][a-z0-9-]{1,30}`. */
68
+ export declare function appName(name: string): string;
69
+ /** The keys of the first `defineEnv({ … })` in `source`, read as text. */
70
+ export declare function parseEnvSchema(source: string): {
71
+ exportName: string;
72
+ keys: EnvKeyFact[];
73
+ } | undefined;
74
+ export declare function renderConfig(facts: ProjectFacts, answers: InitAnswers): string;
75
+ export declare function init(host: Host, dir: string, flags: Map<string, string>, switches: Set<string>): Promise<number>;
76
+ export declare function describeFacts(facts: ProjectFacts): string[];