poad 2.75.3 → 2.76.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.
@@ -0,0 +1,910 @@
1
+ // poad push / poad pull : tout un projet entre le local et un environnement de poad.io.
2
+ //
3
+ // poad push [--env e] local → poad.io poad pull [--env e] poad.io → local
4
+ // --dry-run : l'aperçu seul ; --only / --skip code,base,auth,s3,refs ; --tables a,b ; --with-secrets ; --json
5
+ //
6
+ // Sens explicite : la cible devient le miroir de la source pour les parties choisies, dans l'ordre
7
+ // code → base + comptes (une transaction) → références → fichiers (S3) → secrets. Toujours un aperçu d'abord,
8
+ // par partie et par table. Vers la production : sauvegarde (project.sh backup), contrôle de place, confirmation
9
+ // forte (taper l'identifiant du projet ; hors terminal : --yes --confirm <id>). Vers le local : sauvegarde
10
+ // pg_dump si la base locale a des lignes.
11
+ //
12
+ // Journaux : une ligne par partie et par table (event=project_push|project_pull, part, table, rows, bytes,
13
+ // duration_ms, outcome) dans le puits local et, par poad.io, dans celui de l'environnement et de poad.io.
14
+ // Jamais une valeur de ligne, jamais un secret. Codes de sortie : 0 fait, 5 une partie en échec, 4
15
+ // confirmation, 3 session, 2 usage, 1 autre erreur.
16
+ 'use strict';
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const { randomUUID } = require('crypto');
20
+
21
+ const SPEC = { values: ['env', 'project', 'only', 'skip', 'tables', 'confirm'], flags: ['dry-run', 'with-secrets', 'allow-destructive', 'accept-data-loss', 'clean'], alias: { n: 'dry-run' } };
22
+
23
+ /** Relance le CLI lui-même (poad deploy, poad migration pull, poad migrate) ; json : sortie analysée */
24
+ function self(args, { json = false, inherit = false } = {}) {
25
+ const { spawn } = require('child_process');
26
+ const poad = path.join(__dirname, '..', '..', 'poad.js');
27
+ return new Promise((resolve) => {
28
+ const child = spawn(process.execPath, [poad, ...args], { cwd: process.cwd(), env: process.env, stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'] });
29
+ let stdout = '';
30
+ let stderr = '';
31
+ if (!inherit) {
32
+ child.stdout.on('data', (d) => (stdout += d));
33
+ child.stderr.on('data', (d) => (stderr = (stderr + d).slice(-4000)));
34
+ }
35
+ child.on('error', (e) => resolve({ code: -1, stdout: '', stderr: e.message, data: null }));
36
+ child.on('close', (code) => {
37
+ let data = null;
38
+ if (json) {
39
+ const i = stdout.indexOf('{');
40
+ try {
41
+ data = JSON.parse(stdout.slice(i));
42
+ } catch {}
43
+ }
44
+ resolve({ code, stdout, stderr, data });
45
+ });
46
+ });
47
+ }
48
+
49
+ /** Empreintes ou comptes de plusieurs tables, en un seul appel par côté : textes dans l'ordre */
50
+ async function batch(pg, container, side, items) {
51
+ if (!items.length) return [];
52
+ const sql = items.map((it, i) => `\\echo @@T ${i}\n${it.sql};`).join('\n');
53
+ const text = await pg.query(container, side, sql, { timeoutMs: 30 * 60 * 1000 });
54
+ const out = items.map(() => '');
55
+ let cur = -1;
56
+ const buf = items.map(() => []);
57
+ for (const l of text.split('\n')) {
58
+ const m = /^@@T (\d+)$/.exec(l);
59
+ if (m) cur = Number(m[1]);
60
+ else if (cur >= 0 && l) buf[cur].push(l);
61
+ }
62
+ buf.forEach((b, i) => (out[i] = b.join('\n')));
63
+ return out;
64
+ }
65
+
66
+ const n = (v) => Number(v || 0).toLocaleString('en-US');
67
+
68
+ function run(direction, raw, deps = {}) {
69
+ return require('../cloud/cli').run(raw, SPEC, async ({ opts, positionals, out }) => {
70
+ const api = require('../cloud/api');
71
+ const cli = require('../cloud/cli');
72
+ const branches = require('../cloud/branches');
73
+ const P = require('./plan');
74
+ const pg = deps.pg || require('./pg');
75
+ const { chalk } = out;
76
+ const push = direction === 'push';
77
+ const event = push ? 'project_push' : 'project_pull';
78
+ const dry = Boolean(opts['dry-run']) || positionals[0] === 'status';
79
+ if (positionals.length && !(positionals.length === 1 && positionals[0] === 'status')) throw api.usageError(`poad ${direction}: unexpected "${positionals[0]}". Usage: poad ${direction} [--env <name>] [--dry-run] [--only code,base,auth,s3,refs] [--skip …] [--tables a,b] [--with-secrets] [--clean] [--yes] [--json]`);
80
+
81
+ let sel;
82
+ try {
83
+ sel = P.parseParts({ only: opts.only, skip: opts.skip, tables: opts.tables, withSecrets: opts['with-secrets'] });
84
+ } catch (e) {
85
+ if (e instanceof P.PlanError) throw api.usageError(e.message);
86
+ throw e;
87
+ }
88
+ const has = (p) => sel.parts.includes(p);
89
+ const root = cli.projectRoot();
90
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one.');
91
+ const poadDir = path.dirname(root);
92
+ const { id } = cli.targetProject(opts);
93
+ const env = await branches.resolve(id, { wanted: opts.env, root });
94
+ const cloudLabel = `poad.io ${id} (${env.branch}${env.production ? ', production' : ''})`;
95
+ const rid = randomUUID();
96
+ const started = Date.now();
97
+ const events = [];
98
+ const note = (line) => events.push({ ...line, duration_ms: Math.max(0, Math.round(line.duration_ms || 0)) });
99
+
100
+ // Engine local : nécessaire à tout, sauf poussée du seul code
101
+ const { readConfig } = require('../config');
102
+ const config = readConfig(root);
103
+ const container = config.project_uuid;
104
+ const needLocal = sel.parts.some((p) => p !== 'code') || !push;
105
+ const localStarted = await (deps.started || ((c) => require('../docker').isDockerExist(c.project_uuid)))(config);
106
+ if (needLocal && !localStarted && sel.parts.some((p) => p !== 'code')) throw new api.CloudError('The local project is not started: run "poad start" (its engine reads and writes the local side).', { code: 'not_started' });
107
+
108
+ const head = `${push ? 'Push' : 'Pull'}${dry ? ' (dry run)' : ''}`;
109
+ const arrow = push ? `local → ${env.production ? chalk.magenta.bold(cloudLabel) : chalk.cyan.bold(cloudLabel)}` : `${env.production ? chalk.magenta.bold(cloudLabel) : chalk.cyan.bold(cloudLabel)} → local`;
110
+ out.log(` ${chalk.bold(head)} ${arrow}${chalk.grey(env.source === 'git' ? ' (git branch)' : env.source === 'default' && env.git ? ` (git branch ${env.git} not on poad.io)` : '')}`);
111
+ const clean = Boolean(opts.clean);
112
+ out.log(chalk.grey(` parts: ${sel.parts.join(', ')}${sel.tables ? ` tables: ${sel.tables.join(', ')}` : ''}${clean ? ' --clean: what is replaced is emptied first' : ''}`));
113
+
114
+ // --- Aperçu (rien ne change) -------------------------------------------------------------------
115
+ const preview = { code: null, base: null, auth: null, refs: null, s3: null, secrets: null, space: null };
116
+ const needDb = has('base') || has('auth') || has('secrets');
117
+ let local = null;
118
+ let cloud = null;
119
+ let src = null;
120
+ let dst = null;
121
+ let inv = null;
122
+ if (needDb) {
123
+ const db = require('../cloud/db');
124
+ const creds = await (deps.credentials || db.credentials)(id, { env, purpose: 'copy' });
125
+ local = pg.localSide(container);
126
+ cloud = pg.cloudSide(creds, { label: cloudLabel });
127
+ [src, dst] = push ? [local, cloud] : [cloud, local];
128
+ inv = await inventories(pg, container, src, dst, P);
129
+ }
130
+
131
+ // Magasin de références : ses tables sont la partie refs, jamais la partie base
132
+ let registry = null;
133
+ if (has('refs') || has('base')) {
134
+ try {
135
+ registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'references' });
136
+ } catch (e) {
137
+ registry = null;
138
+ if (has('refs')) out.log(chalk.yellowBright(` ⚠ reference store not readable (${e.message}): refs left out.`));
139
+ }
140
+ }
141
+ const refTargets = registry && Array.isArray(registry.items) ? registry.items.map((s) => s.target) : [];
142
+
143
+ // Code
144
+ if (has('code')) preview.code = push ? await codePushPreview(env, opts, out) : await codePullPreview(id, env, poadDir, out, deps);
145
+
146
+ // Base et comptes
147
+ if (has('base')) preview.base = await basePlan(pg, P, container, src, dst, inv, { exclude: refTargets, only: sel.tables, code: preview.code, push });
148
+ if (has('auth')) preview.auth = await authPreview(pg, P, container, src, dst, inv);
149
+
150
+ // Références
151
+ if (has('refs') && registry) preview.refs = refsPreview(registry, env, poadDir, push, has('code'));
152
+
153
+ // Fichiers du Stockage
154
+ let storage = null;
155
+ if (has('s3')) {
156
+ storage = await storageSides(env, opts, push, deps);
157
+ preview.s3 = await storagePlan(storage, true);
158
+ }
159
+
160
+ // Secrets : des noms seulement
161
+ if (has('secrets')) preview.secrets = { variables: inv.src.variables, credentials: inv.src.credentials, target_variables: inv.dst.variables, target_credentials: inv.dst.credentials, target_storage: inv.dst.storage_credentials };
162
+
163
+ // Place sur la cible : ce qui sera écrit (base et comptes, fichiers) et ce qui sera libéré
164
+ const amounts = spaceAmounts(preview, { clean });
165
+ if (amounts.need.base + amounts.need.files > 0) preview.space = await spaceCheck(id, env, poadDir, push, amounts, P);
166
+
167
+ printPreview(out, P, preview, { push, env, cloudLabel, sel });
168
+
169
+ const blocking = [];
170
+ if (preview.code && push && (preview.code.error || (preview.code.errors || []).length)) blocking.push(`code: poad deploy would be refused (${preview.code.error || preview.code.errors[0]})`);
171
+ if (preview.base && preview.base.blocked.length && !(preview.code && preview.code.structure)) blocking.push('base: the structure of the target differs (see above)');
172
+ if (preview.space && preview.space.known && !preview.space.ok) blocking.push(`not enough room on the target (${P.size(preview.space.missing)} missing${!clean && spaceAmounts(preview, { clean: true }).freed.base > 0 ? '; --clean would empty the tables to rewrite first' : ''})`);
173
+ if (preview.base && preview.base.unknown.length) blocking.push(`--tables: ${preview.base.unknown.join(', ')} not in the source`);
174
+ const nothing = isNothing(preview, sel);
175
+
176
+ if (dry) {
177
+ out.log(' ');
178
+ out.log(blocking.length ? chalk.yellowBright(` Would stop: ${blocking.join('; ')}.`) : nothing ? `${chalk.greenBright('✔')} Dry run: nothing to copy, the target is already the mirror of the source.` : `${chalk.greenBright('✔')} Dry run: nothing changed. Run "poad ${direction}${opts.env ? ` --env ${env.branch}` : ''}" to copy.`);
179
+ out.log(' ');
180
+ out.result(resultOf({ direction, id, env, sel, dry: true, preview, blocking, events, started }));
181
+ return 0;
182
+ }
183
+ if (blocking.length) {
184
+ out.result(resultOf({ direction, id, env, sel, dry: false, preview, blocking, events, started }));
185
+ throw new api.CloudError(`Nothing copied: ${blocking.join('; ')}.`, { code: 'blocked', exit: api.EXIT.failed });
186
+ }
187
+ if (nothing) {
188
+ out.log(' ');
189
+ out.log(`${chalk.greenBright('✔')} Nothing to copy: the target is already the mirror of the source.`);
190
+ out.log(' ');
191
+ out.result(resultOf({ direction, id, env, sel, dry: false, preview, blocking, events, started }));
192
+ return 0;
193
+ }
194
+
195
+ // --- Confirmations -------------------------------------------------------------------------------
196
+ const target = push ? cloudLabel : 'the local project';
197
+ if (push && env.production) await strongConfirm(id, env, opts, out);
198
+ else await cli.confirm(`Make ${target} the mirror of ${push ? 'the local project' : cloudLabel} for ${sel.parts.filter((p) => p !== 'secrets').join(', ')}? What the target has of its own in these parts is replaced.${clean ? ' --clean: the tables and files to replace are emptied FIRST, outside the transaction (a failure leaves them empty until the next run).' : ''}`, { yes: opts.yes, json: out.json });
199
+ if (has('secrets')) {
200
+ const s = preview.secrets;
201
+ await cli.confirm(`Also copy the values of ${s.variables.length} variable(s) and ${s.credentials.length} credential(s)${s.credentials.length ? ` (${s.credentials.slice(0, 8).join(', ')})` : ''} to ${target}? Values are never shown nor logged.`, { yes: opts.yes, json: out.json });
202
+ }
203
+
204
+ // --- Sauvegarde -----------------------------------------------------------------------------------
205
+ let backup = null;
206
+ // Seulement si la base va vraiment être écrite : une poussée relancée qui n'a plus que des fichiers à
207
+ // envoyer ne refait pas de sauvegarde de la production
208
+ const writesDb = dbWrites(preview, sel, push);
209
+ if (push && env.production && writesDb) {
210
+ const t0 = Date.now();
211
+ try {
212
+ backup = await api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/backup`, { body: {}, what: 'backup', timeout: 15 * 60 * 1000 });
213
+ } catch (e) {
214
+ note({ part: 'backup', outcome: 'failed', duration_ms: Date.now() - t0 });
215
+ await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
216
+ throw new api.CloudError(`Nothing copied: the backup of ${env.branch} failed (${e.message}).`, { code: 'backup_failed', exit: api.EXIT.failed });
217
+ }
218
+ note({ part: 'backup', bytes: Number(backup.bytes) || 0, outcome: 'done', duration_ms: Date.now() - t0 });
219
+ out.log(`${chalk.greenBright('✔')} backup of ${env.branch}: ${backup.file || 'done'}${backup.bytes ? chalk.grey(` (${P.size(backup.bytes)})`) : ''}`);
220
+ }
221
+ if (!push && writesDb && localStarted && (inv ? localHasData(inv) : true)) {
222
+ const t0 = Date.now();
223
+ require('../config').ensureGitignore(root);
224
+ const dir = path.join(poadDir, 'backups');
225
+ fs.mkdirSync(dir, { recursive: true });
226
+ const file = path.join(dir, `${stamp()}-pre-pull.dump`);
227
+ try {
228
+ const bytes = await pg.dumpLocal(container, file);
229
+ backup = { file: path.relative(process.cwd(), file), bytes };
230
+ note({ part: 'backup', bytes, outcome: 'done', duration_ms: Date.now() - t0 });
231
+ out.log(`${chalk.greenBright('✔')} local backup: ${backup.file} ${chalk.grey(`(${P.size(bytes)}; pg_restore to bring it back)`)}`);
232
+ } catch (e) {
233
+ note({ part: 'backup', outcome: 'failed', duration_ms: Date.now() - t0 });
234
+ await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
235
+ throw new api.CloudError(`Nothing copied: the local backup failed (${e.message}).`, { code: 'backup_failed', exit: api.EXIT.failed });
236
+ }
237
+ }
238
+
239
+ // --- Exécution -------------------------------------------------------------------------------------
240
+ const results = {};
241
+ let failed = false;
242
+ const stop = (part, why) => {
243
+ failed = true;
244
+ results[part] = { ...(results[part] || {}), outcome: 'failed', error: why };
245
+ };
246
+
247
+ if (has('code') && preview.code && preview.code.todo) {
248
+ const t0 = Date.now();
249
+ const r = push ? await codePush(env, opts, out) : await codePull(env, opts, out, poadDir, preview.code, localStarted);
250
+ results.code = r;
251
+ note({ part: 'code', rows: r.count || 0, outcome: r.ok ? 'done' : 'failed', duration_ms: Date.now() - t0 });
252
+ if (!r.ok) stop('code', r.error || 'code part failed');
253
+ }
254
+
255
+ if (!failed && (has('base') || has('auth'))) {
256
+ // La structure a pu changer (partie code) : inventaire et différence refaits
257
+ let base = preview.base;
258
+ let auth = preview.auth;
259
+ if (results.code && results.code.changed) {
260
+ inv = await inventories(pg, container, src, dst, P);
261
+ if (has('base')) base = await basePlan(pg, P, container, src, dst, inv, { exclude: refTargets, only: sel.tables, push });
262
+ if (has('auth')) auth = await authPreview(pg, P, container, src, dst, inv);
263
+ }
264
+ if (base && base.blocked.length) {
265
+ for (const b of base.blocked) out.log(` ${chalk.redBright('✕')} ${b.key}: ${b.detail}`);
266
+ stop('base', 'the structure of the target differs');
267
+ note({ part: 'base', outcome: 'refused', duration_ms: 0 });
268
+ } else {
269
+ let r = null;
270
+ if (clean && base && base.rewrite.length) {
271
+ const t0 = Date.now();
272
+ try {
273
+ await pg.query(container, dst, P.truncateSql(base.rewrite));
274
+ note({ part: 'base', outcome: 'done', rows: base.rewrite.length, bytes: base.rewrite.reduce((x, t) => x + ((t.target && t.target.bytes) || 0), 0), duration_ms: Date.now() - t0, step: 'clean' });
275
+ out.log(`${chalk.greenBright('✔')} --clean: ${base.rewrite.length} table(s) emptied on the target ${chalk.grey(`(${P.size(base.rewrite.reduce((x, t) => x + ((t.target && t.target.bytes) || 0), 0))} freed)`)}`);
276
+ } catch (e) {
277
+ note({ part: 'base', outcome: 'failed', duration_ms: Date.now() - t0, step: 'clean' });
278
+ out.log(chalk.redBright(` ✕ --clean: the tables could not be emptied, nothing changed (${e.message})`));
279
+ r = { ok: false, lines: [], tables: [], error: `--clean: ${e.message}` };
280
+ }
281
+ }
282
+ if (!r) r = await transferData(pg, P, container, src, dst, { base, auth, inv, sel, out });
283
+ for (const l of r.lines) note(l);
284
+ if (has('base')) results.base = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'base'), error: r.ok ? undefined : r.error };
285
+ if (has('auth')) results.auth = { outcome: r.ok ? 'done' : 'failed', tables: r.tables.filter((t) => t.part === 'auth'), error: r.ok ? undefined : r.error };
286
+ if (!r.ok) failed = true;
287
+ }
288
+ }
289
+
290
+ if (!failed && has('refs') && preview.refs) {
291
+ const t0 = Date.now();
292
+ try {
293
+ const r = await refsApply(id, env, poadDir, preview.refs, push, opts, out, config, has('code'));
294
+ results.refs = r;
295
+ for (const t of r.tables || []) note({ part: 'refs', table: t.target, rows: t.rows, outcome: t.outcome, duration_ms: t.duration_ms });
296
+ if (r.failed) stop('refs', 'a reference table could not be loaded');
297
+ } catch (e) {
298
+ note({ part: 'refs', outcome: 'failed', duration_ms: Date.now() - t0 });
299
+ stop('refs', e.message);
300
+ }
301
+ }
302
+
303
+ if (!failed && has('s3') && preview.s3 && preview.s3.todo) {
304
+ const t0 = Date.now();
305
+ const r = await storagePlan(storage, false, out, { clean, concurrency: deps.concurrency, sleep: deps.sleep });
306
+ results.s3 = r;
307
+ for (const l of fileLines(r)) note(l);
308
+ note({ part: 's3', rows: r.totals.added + r.totals.updated + r.totals.removed, bytes: r.totals.bytes, outcome: r.totals.failed ? 'failed' : 'done', duration_ms: Date.now() - t0 });
309
+ if (r.totals.failed) stop('s3', `${r.totals.failed} file(s) failed`);
310
+ }
311
+
312
+ if (!failed && has('secrets')) {
313
+ const t0 = Date.now();
314
+ const script = P.secretsScript({ srcFn: src.psql, dstFn: dst.psql, queries: P.secretsSql(inv.srcProbe, { targetStorage: inv.dst.storage_credentials }) });
315
+ const r = await pg.transfer(container, src, dst, script);
316
+ const ok = r.code === 0;
317
+ results.secrets = { outcome: ok ? 'done' : 'failed', variables: preview.secrets.variables.length, credentials: preview.secrets.credentials.length };
318
+ note({ part: 'secrets', rows: preview.secrets.variables.length + preview.secrets.credentials.length, outcome: ok ? 'done' : 'failed', duration_ms: Date.now() - t0 });
319
+ out.log(ok ? `${chalk.greenBright('✔')} secrets: ${preview.secrets.variables.length} variable value(s), ${preview.secrets.credentials.length} credential(s)` : chalk.redBright(' ✕ secrets not copied (nothing changed: one transaction)'));
320
+ if (!ok) stop('secrets', 'secrets not copied');
321
+ }
322
+
323
+ note({ part: 'all', outcome: failed ? 'failed' : 'done', duration_ms: Date.now() - started });
324
+ await flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction });
325
+
326
+ out.log(' ');
327
+ if (results.s3 && results.s3.totals.failed) printFailures(out, results.s3, { direction, env, opts });
328
+ if (failed) out.log(chalk.redBright(` ${push ? 'Push' : 'Pull'} stopped: ${Object.entries(results).filter(([, r]) => r && r.outcome === 'failed').map(([p, r]) => `${p} (${r.error})`).join(', ')}.`));
329
+ else out.log(`${chalk.greenBright('✔')} ${push ? `Pushed to ${env.branch}` : `Pulled from ${env.branch}`} in ${((Date.now() - started) / 1000).toFixed(1)} s.`);
330
+ out.log(chalk.grey(` Logs: poad logs cli event=${event}${push ? ` (and --env ${env.branch} on poad.io)` : ''}`));
331
+ out.log(' ');
332
+ out.result(resultOf({ direction, id, env, sel, dry: false, preview, blocking, events, started, results, backup, failed }));
333
+ return failed ? api.EXIT.failed : 0;
334
+ });
335
+ }
336
+
337
+ // --- Inventaire -----------------------------------------------------------------------------------------
338
+
339
+ async function inventories(pg, container, src, dst, P) {
340
+ const [srcProbe, dstProbe] = await Promise.all([pg.json(container, src, P.PROBE_SQL), pg.json(container, dst, P.PROBE_SQL)]);
341
+ const [s, d] = await Promise.all([pg.json(container, src, P.inventorySql(srcProbe)), pg.json(container, dst, P.inventorySql(dstProbe))]);
342
+ return { src: s, dst: d, srcProbe, dstProbe };
343
+ }
344
+
345
+ /** Plan de la partie base : tables copiables, bloquées, différence ligne à ligne */
346
+ async function basePlan(pg, P, container, src, dst, inv, { exclude, only, code, push }) {
347
+ const cmp = P.compareTables(inv.src.tables, inv.dst.tables, { exclude, only });
348
+ const migrations = P.compareMigrations(inv.src.migrations, inv.dst.migrations);
349
+ const items = cmp.tables.map((t) => ({ t, sql: P.diffable(t) ? P.hashSql(t) : P.countSql(t), exact: P.diffable(t) }));
350
+ const [a, b] = await Promise.all([batch(pg, container, src, items), batch(pg, container, dst, items)]);
351
+ const tables = items.map((it, i) => {
352
+ const d = it.exact ? P.diffHashes(a[i], b[i], Boolean(it.t.pk)) : { rows: Number(a[i]) || 0, target_rows: Number(b[i]) || 0, exact: false };
353
+ return { ...it.t, diff: d, changed: P.changed(d) };
354
+ });
355
+ const seqs = P.sequencesFor(inv.src.sequences, inv.dst.sequences, tables.map((t) => t.key), { all: !only });
356
+ return { tables, rewrite: tables.filter((t) => t.changed), blocked: cmp.blocked, excluded: cmp.excluded, unknown: cmp.unknown, extra: cmp.extra, migrations, sequences: seqs, structure_after_code: Boolean(code && code.structure), push };
357
+ }
358
+
359
+ /** Comptes : tables reprises, différence des comptes par identifiant (jetons hors empreinte) */
360
+ async function authPreview(pg, P, container, src, dst, inv) {
361
+ const plan = P.authPlan(inv.src.auth, inv.dst.auth);
362
+ const items = plan.tables.map((t) => ({ t, sql: P.hashSql(t, { blank: t.blank }) }));
363
+ const [a, b] = await Promise.all([batch(pg, container, src, items), batch(pg, container, dst, items)]);
364
+ plan.tables = items.map((it, i) => ({ ...it.t, diff: P.diffHashes(a[i], b[i], Boolean(it.t.pk)) }));
365
+ plan.changed = plan.tables.some((t) => P.changed(t.diff));
366
+ return plan;
367
+ }
368
+
369
+ const localHasData = (inv) => {
370
+ if (!inv) return false;
371
+ const local = inv.dstLocal || inv.dst;
372
+ return (local.tables || []).some((t) => Number(t.estimate) > 0 || Number(t.bytes) > 16384) || Number((local.auth.users || {}).rows) > 0;
373
+ };
374
+
375
+ // --- Code -------------------------------------------------------------------------------------------------
376
+
377
+ const envArgs = (env, opts) => ['--env', env.branch, ...(opts.project ? ['--project', opts.project] : [])];
378
+
379
+ async function codePushPreview(env, opts, out) {
380
+ const r = await self(['deploy', ...envArgs(env, opts), '--dry-run', '--json'], { json: true });
381
+ const d = r.data || {};
382
+ if (d.error) return { ok: false, error: d.error.message, todo: true, structure: false };
383
+ const m = d.migrations || {};
384
+ const pending = (m.pending || []).length;
385
+ const errors = (m.errors || []).map((e) => e.message || String(e));
386
+ return { ok: r.code === 0, files: d.files || 0, bytes: d.bytes || 0, pending, pending_list: m.pending || [], errors, fix: d.fix || [], todo: true, structure: pending > 0, large_references: d.large_references || [] };
387
+ }
388
+
389
+ async function codePullPreview(id, env, poadDir, out, deps) {
390
+ const api = require('../cloud/api');
391
+ const C = require('./code');
392
+ const r = await self(['migration', 'pull', '--env', env.branch, '--dry-run', '--json'], { json: true });
393
+ const m = r.data || {};
394
+ const pull = Array.isArray(m.pull) ? m.pull : [];
395
+ let files = null;
396
+ let error = null;
397
+ try {
398
+ const ex = await (deps.exportBranch || ((i, b) => api.call('GET', `v1/projects/${api.enc(i)}/branches/${api.enc(b)}/export`, { what: 'export', timeout: 150000 })))(id, env.branch);
399
+ const remote = C.exportFiles(ex.files);
400
+ const plan = C.planFiles(remote, C.localFiles(poadDir), C.gitFiles(poadDir));
401
+ files = { ...plan, remote };
402
+ } catch (e) {
403
+ error = e.message;
404
+ }
405
+ const todo = pull.length > 0 || Boolean(files && (files.add.length || files.update.length || files.remove.length));
406
+ return { migrations: pull, conflicts: m.conflicts || [], unavailable: m.unavailable || [], files, error: error || (m.error && m.error.message) || null, todo, structure: pull.length > 0 };
407
+ }
408
+
409
+ async function codePush(env, opts, out) {
410
+ const args = ['deploy', ...envArgs(env, opts), '--yes', ...(opts['allow-destructive'] || opts['accept-data-loss'] ? ['--allow-destructive'] : [])];
411
+ if (out.json) {
412
+ const r = await self([...args, '--json'], { json: true });
413
+ const d = r.data || {};
414
+ return { ok: r.code === 0, changed: ((d.migrations || {}).applied || []).length > 0, count: ((d.migrations || {}).applied || []).length, deploy: d, error: r.code === 0 ? null : (d.error && d.error.message) || `poad deploy exit ${r.code}` };
415
+ }
416
+ out.log(out.chalk.bold('\n code: poad deploy'));
417
+ const r = await self(args, { inherit: true });
418
+ return { ok: r.code === 0, changed: true, error: r.code === 0 ? null : `poad deploy exit ${r.code}` };
419
+ }
420
+
421
+ async function codePull(env, opts, out, poadDir, preview, localStarted) {
422
+ const C = require('./code');
423
+ const { chalk } = out;
424
+ let count = 0;
425
+ if (preview.migrations.length) {
426
+ const r = await self(['migration', 'pull', '--env', env.branch, '--yes', '--json'], { json: true });
427
+ const written = (r.data && r.data.written) || [];
428
+ count += written.length;
429
+ for (const w of written) out.log(` ${chalk.greenBright('+')} migrations/${typeof w === 'string' ? path.basename(w) : w.file || w.version}`);
430
+ if (r.code !== 0) return { ok: false, error: `poad migration pull exit ${r.code}`, count };
431
+ }
432
+ if (preview.files) {
433
+ C.applyFiles(poadDir, preview.files, preview.files.remote);
434
+ for (const f of preview.files.add) out.log(` ${chalk.greenBright('+')} ${f}`);
435
+ for (const f of preview.files.update) out.log(` ${chalk.yellowBright('~')} ${f}`);
436
+ for (const f of preview.files.remove) out.log(` ${chalk.redBright('-')} ${f}`);
437
+ count += preview.files.add.length + preview.files.update.length + preview.files.remove.length;
438
+ }
439
+ let migrated = null;
440
+ if (localStarted && preview.migrations.length) {
441
+ const r = await self(['migrate', '--json'], { json: true });
442
+ migrated = r.code === 0;
443
+ out.log(migrated ? `${chalk.greenBright('✔')} poad migrate: the local base has the structure of ${env.branch}` : chalk.redBright(' ✕ poad migrate failed: run it to see why'));
444
+ if (!migrated) return { ok: false, error: 'poad migrate failed', count, changed: true };
445
+ }
446
+ return { ok: true, count, changed: true, migrated };
447
+ }
448
+
449
+ // --- Données (base et comptes), une transaction -----------------------------------------------------------
450
+
451
+ async function transferData(pg, P, container, src, dst, { base, auth, inv, sel, out }) {
452
+ const { chalk } = out;
453
+ const tables = [];
454
+ const clear = [];
455
+ const after = [];
456
+ if (base) {
457
+ for (const t of base.rewrite) {
458
+ tables.push({ part: 'base', schema: t.schema, name: t.name, key: t.key, columns: t.columns, rows: t.diff.rows, bytes: t.bytes, diff: t.diff });
459
+ clear.push(`delete from ${P.qname(t.schema, t.name)};`);
460
+ }
461
+ }
462
+ if (auth && auth.changed) {
463
+ clear.push(...auth.clear);
464
+ after.push(...auth.after);
465
+ for (const t of auth.tables) tables.push({ part: 'auth', schema: 'auth', name: t.name, key: t.key, columns: t.columns, rows: t.diff.rows, bytes: t.bytes, diff: t.diff });
466
+ }
467
+ const seqSql = base ? P.sequencesSql(base.sequences) : null;
468
+ if (!tables.length && !seqSql) return { ok: true, lines: [], tables: [] };
469
+ const script = P.transferScript({ srcFn: src.psql, dstFn: dst.psql, tables, clear, after, sequences: seqSql });
470
+ const t0 = Date.now();
471
+ const marks = {};
472
+ const r = await pg.transfer(container, src, dst, script, {
473
+ onMarker: (l) => {
474
+ const m = /^@@poad start (\d+) (\d+)/.exec(l);
475
+ if (m) {
476
+ marks[m[1]] = Number(m[2]);
477
+ const t = tables[Number(m[1])];
478
+ if (t && !out.json && process.stderr.isTTY) process.stderr.write(`\r\x1b[2K ${chalk.grey('copying')} ${t.key}…`);
479
+ }
480
+ },
481
+ });
482
+ if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[2K');
483
+ const mk = P.parseMarkers(r.stderr);
484
+ const ok = r.code === 0 && mk.rc === 0;
485
+ const end = mk.done || Date.now();
486
+ const lines = [];
487
+ const done = tables.map((t, i) => {
488
+ const s = (mk.tables[i] || {}).start;
489
+ const next = (mk.tables[i + 1] || {}).start || end;
490
+ const res = { part: t.part, table: t.key, rows: t.rows, bytes: t.bytes || 0, duration_ms: s ? Math.max(0, next - s) : 0, outcome: ok ? 'done' : 'rolled_back', diff: t.diff };
491
+ lines.push({ part: t.part, table: t.key, rows: t.rows, bytes: res.bytes, duration_ms: res.duration_ms, outcome: res.outcome });
492
+ if (!out.json) {
493
+ const d = t.diff;
494
+ const what = d.exact ? `+${n(d.added)} ~${n(d.replaced)} -${n(d.deleted)}` : `${n(d.target_rows)} → ${n(d.rows)}`;
495
+ out.log(` ${ok ? chalk.greenBright('✔') : chalk.redBright('✕')} ${t.key} ${chalk.grey(`${what} ${n(t.rows)} rows, ${P.size(res.bytes)}${res.duration_ms ? `, ${(res.duration_ms / 1000).toFixed(1)} s` : ''}`)}`);
496
+ }
497
+ return res;
498
+ });
499
+ if (base && base.sequences.length && ok && !out.json) out.log(chalk.grey(` ${base.sequences.length} sequence(s) set as on the source`));
500
+ if (auth && auth.changed && ok && !out.json && auth.closed.length) out.log(chalk.grey(' sessions and refresh tokens of the target closed: accounts sign in again there'));
501
+ const error = ok ? null : P.errorLine(mk.errors) || `exit ${r.code}`;
502
+ if (!ok) out.log(chalk.redBright(` ✕ data not copied, nothing changed on the target (one transaction): ${error}`));
503
+ lines.push({ part: 'data', rows: tables.reduce((s, t) => s + (t.rows || 0), 0), bytes: done.reduce((s, t) => s + t.bytes, 0), duration_ms: Date.now() - t0, outcome: ok ? 'done' : 'rolled_back' });
504
+ return { ok, lines, tables: done, error };
505
+ }
506
+
507
+ // --- Références -------------------------------------------------------------------------------------------
508
+
509
+ const localRefsFile = (poadDir) => path.join(poadDir, 'data', 'reference-local.json');
510
+ const readJson = (f) => {
511
+ try {
512
+ return JSON.parse(fs.readFileSync(f, 'utf8'));
513
+ } catch {
514
+ return {};
515
+ }
516
+ };
517
+
518
+ function refsPreview(registry, env, poadDir, push, withCode) {
519
+ const items = Array.isArray(registry.items) ? registry.items : [];
520
+ if (push) {
521
+ const refStore = require('../reference-store');
522
+ const large = refStore.largeFiles(poadDir);
523
+ const applied = (registry.applied && registry.applied[env.branch]) || {};
524
+ const outdated = items.filter((s) => !applied[s.target] || applied[s.target].sha256 !== s.sha256).map((s) => s.target);
525
+ return { store: Boolean(registry.store), large: large.map((f) => ({ rel: f.rel, target: f.target, bytes: f.size })), large_by_code: withCode, load: outdated, todo: large.length > 0 || outdated.length > 0 };
526
+ }
527
+ const loaded = readJson(localRefsFile(poadDir));
528
+ const load = items.filter((s) => !loaded[s.target] || loaded[s.target] !== s.sha256).map((s) => ({ target: s.target, sha256: s.sha256, rows: s.rows }));
529
+ return { store: Boolean(registry.store), load, todo: load.length > 0 };
530
+ }
531
+
532
+ async function refsApply(id, env, poadDir, plan, push, opts, out, config, withCode) {
533
+ const api = require('../cloud/api');
534
+ if (push) {
535
+ const tables = [];
536
+ if (plan.large.length && !withCode) {
537
+ const refStore = require('../reference-store');
538
+ const r = await refStore.sendAndLoad(id, env.branch, poadDir, refStore.largeFiles(poadDir), opts, out);
539
+ for (const t of r.tables) tables.push({ target: t.target, rows: t.rows || null, outcome: t.state === 'loaded' ? 'done' : t.state, duration_ms: 0 });
540
+ if (r.failed) return { tables, failed: true };
541
+ }
542
+ const rest = plan.load.filter((t) => !tables.some((x) => x.target === t));
543
+ if (rest.length) {
544
+ const { startAndWait } = require('../../project/ref/push');
545
+ const l = await startAndWait(id, env.branch, rest, opts, out);
546
+ for (const st of l.steps || []) tables.push({ target: st.target, rows: st.written ?? null, outcome: st.status === 'done' ? 'done' : st.status, duration_ms: st.duration_ms || 0 });
547
+ return { tables, failed: l.status === 'failed', load_id: l.load_id };
548
+ }
549
+ return { tables, failed: false };
550
+ }
551
+ const S = require('../seed/run');
552
+ const A = require('../seed/apply');
553
+ const order = A.loadOrder(plan.load.map((s) => s.target), await S.localEdges(config.project_uuid));
554
+ const loaded = readJson(localRefsFile(poadDir));
555
+ const tables = [];
556
+ for (const target of order) {
557
+ const t0 = Date.now();
558
+ const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `reference ${target}` });
559
+ const r = await S.loadLocal(config.project_uuid, d);
560
+ const s = plan.load.find((x) => x.target === target);
561
+ loaded[target] = s.sha256;
562
+ fs.mkdirSync(path.dirname(localRefsFile(poadDir)), { recursive: true });
563
+ fs.writeFileSync(localRefsFile(poadDir), JSON.stringify(loaded, null, 2) + '\n');
564
+ out.log(`${out.chalk.greenBright('✔')} ${target} loaded locally: ${n(r.written)} rows written, ${n(r.deleted)} removed`);
565
+ tables.push({ target, rows: r.written, outcome: 'done', duration_ms: Date.now() - t0 });
566
+ }
567
+ return { tables, failed: false };
568
+ }
569
+
570
+ // --- Fichiers du Stockage ---------------------------------------------------------------------------------
571
+
572
+ async function storageSides(env, opts, push, deps) {
573
+ const s = require('../storage');
574
+ const localT = await (deps.localTarget || s.localTarget)();
575
+ const cloudT = await (deps.cloudTarget || s.cloudTarget)({ env: env.branch, project: opts.project });
576
+ const [fromT, toT] = push ? [localT, cloudT] : [cloudT, localT];
577
+ return { fromT, toT, from: (deps.client || s.client)(fromT), to: (deps.client || s.client)(toT) };
578
+ }
579
+
580
+ async function storagePlan(st, dryRun, out, { clean = false, concurrency = 4, sleep } = {}) {
581
+ const ss = require('../storage-sync');
582
+ const s = require('../storage');
583
+ const P = require('./plan');
584
+ const live = { failed: 0, retried: 0, shownRetries: 0 };
585
+ const resumes = [];
586
+ const say = (line) => out && !out.json && out.log(line);
587
+ const r = await ss.sync(st.from, st.to, {
588
+ prune: true,
589
+ dryRun,
590
+ copyBytes: false,
591
+ concurrency,
592
+ sleep,
593
+ freeFirst: clean,
594
+ fromLabel: st.fromT.label,
595
+ toLabel: st.toT.label,
596
+ confirm: async () => true,
597
+ onItem: (e) => {
598
+ if (dryRun || !out) return;
599
+ const c = out.chalk;
600
+ const where = `${e.bucket}${e.name ? `/${e.name}` : ''}`;
601
+ if (e.action === 'resume') {
602
+ // Une reprise par fichier et par offset (un envoi qui retombe au même endroit ne se répète pas)
603
+ if (resumes.some((x) => x.bucket === e.bucket && x.name === e.name && x.offset === e.offset)) return;
604
+ resumes.push({ bucket: e.bucket, name: e.name, offset: e.offset, size: e.size });
605
+ return say(` ${c.cyanBright('↻')} ${where}: resumed at ${P.size(e.offset)} of ${P.size(e.size)}`);
606
+ }
607
+ if (e.action === 'retry') {
608
+ live.retried++;
609
+ if (live.shownRetries++ < 10) say(c.grey(` ↻ ${where}: ${e.reason}; try ${e.attempt + 1} in ${Math.max(1, Math.round(e.delay / 1000))} s`));
610
+ else if (live.shownRetries === 11) say(c.grey(' ↻ more retries (counted at the end)'));
611
+ return;
612
+ }
613
+ if (e.action === 'concurrency') return say(c.grey(` ${e.concurrency} transfer(s) at once now (${e.concurrency < concurrency ? 'errors: slowing down' : 'going back up'})`));
614
+ if (e.error) {
615
+ // Les premiers échecs au fil de l'eau ; tous dans le bilan de fin (repliés) et dans --json
616
+ if (++live.failed <= 5) say(c.redBright(` ✖ ${where}: ${s.reason(e.error)}`));
617
+ else if (live.failed === 6) say(c.redBright(' ✖ more failures: see the summary at the end'));
618
+ return;
619
+ }
620
+ if (out.json) return;
621
+ if (e.action === 'bucket') return say(` ${c.greenBright('+')} bucket ${e.bucket}`);
622
+ say(` ${e.action === 'add' ? c.greenBright('+') : e.action === 'update' ? c.yellowBright('~') : c.redBright('-')} ${where}`);
623
+ },
624
+ });
625
+ const t = r.totals;
626
+ const sizes = (list, k = 'size') => list.reduce((m, o) => m + (Number.isFinite(o[k]) ? o[k] : 0), 0);
627
+ const planned = r.buckets.reduce((acc, p) => acc + sizes(p.add) + sizes(p.update), 0);
628
+ // Place libérée sur la cible : fichiers retirés, versions remplacées (retirées par le Stockage une minute après)
629
+ const freed = r.buckets.reduce((acc, p) => acc + sizes(p.remove) + sizes(p.update, 'targetSize'), 0);
630
+ const bytes = dryRun && r.mode === 'bytes' ? planned : t.bytes || 0;
631
+ const totals = { added: t.added, updated: t.updated, removed: t.removed, unchanged: t.unchanged, buckets_created: t.buckets_created || 0, failed: t.failed || 0, retried: t.retried || live.retried || 0, resumed: resumes.length, bytes };
632
+ return {
633
+ mode: r.mode,
634
+ totals,
635
+ planned_bytes: r.mode === 'bytes' ? planned : 0,
636
+ freed_bytes: freed,
637
+ todo: totals.added + totals.updated + totals.removed + totals.buckets_created > 0,
638
+ buckets: r.buckets.map((p) => ({ bucket: p.bucket, created: p.create, added: p.add.length, updated: p.update.length, removed: p.remove.length })),
639
+ failures: r.errors,
640
+ resumes,
641
+ };
642
+ }
643
+
644
+ /** Lignes du puits pour les fichiers : un échec, une reprise (nom et tailles, jamais le contenu) ; 200 au plus */
645
+ function fileLines(r, max = 200) {
646
+ const out = [];
647
+ for (const f of r.failures || []) {
648
+ if (out.length >= max) break;
649
+ out.push({ part: 's3', file: `${f.bucket}/${f.name}`.slice(0, 512), outcome: 'failed', reason: reasonCode(f.error), attempts: f.attempts || 1, duration_ms: 0 });
650
+ }
651
+ for (const x of r.resumes || []) {
652
+ if (out.length >= max) break;
653
+ out.push({ part: 's3', file: `${x.bucket}/${x.name}`.slice(0, 512), outcome: 'resumed', offset: x.offset, bytes: x.size, duration_ms: 0 });
654
+ }
655
+ return out;
656
+ }
657
+
658
+ /** Catégorie d'un échec de transfert (le puits garde une catégorie, pas un message libre). Pure. */
659
+ function reasonCode(message) {
660
+ const m = String(message || '');
661
+ if (/did not answer within/.test(m)) return 'timeout';
662
+ if (/too large|HTTP 413/.test(m)) return 'too_large';
663
+ if (/does not answer on|connection lost|fetch failed|ECONNRESET|socket/i.test(m)) return 'network';
664
+ if (/after the upload/.test(m)) return 'verify';
665
+ if (/refused by the storage/.test(m)) return 'refused';
666
+ if (/not available \(HTTP 50/.test(m)) return 'unavailable';
667
+ const h = /HTTP (\d{3})/.exec(m);
668
+ return h ? `http_${h[1]}` : 'other';
669
+ }
670
+
671
+ /** Bilan des fichiers en échec : les 5 premiers, « et N autres », puis comment reprendre */
672
+ function printFailures(out, r, { direction, env, opts }) {
673
+ const { chalk } = out;
674
+ if (out.json) return;
675
+ const s = require('../storage');
676
+ const list = r.failures || [];
677
+ const n = list.length;
678
+ out.log(chalk.redBright(` ✖ ${n} file(s) failed${r.totals.retried ? chalk.grey(` (after ${r.totals.retried} retr${r.totals.retried > 1 ? 'ies' : 'y'})`) : ''}:`));
679
+ for (const f of list.slice(0, 5)) out.log(` ${f.bucket}/${f.name}: ${f.error}`);
680
+ if (n > 5) out.log(chalk.grey(` and ${n - 5} other(s): --json lists them all; poad logs cli event=project_push`));
681
+ const again = `poad ${direction}${opts.env ? ` --env ${env.branch}` : ''}`;
682
+ out.log(` Run ${chalk.cyanBright(again)} again (or ${chalk.cyanBright(`${again} --only s3`)}) to resume: files already there are not sent again, a cut upload goes on from where it stopped.`);
683
+ }
684
+
685
+ // --- Place, confirmation, journaux ------------------------------------------------------------------------
686
+
687
+ /** Ce que la copie écrira et libérera sur la cible, par partie (octets) */
688
+ function spaceAmounts(pv, { clean = false } = {}) {
689
+ const rewrite = pv.base ? pv.base.rewrite : [];
690
+ const needBase = rewrite.reduce((x, t) => x + (t.bytes || 0), 0) + (pv.auth && pv.auth.changed ? pv.auth.tables.reduce((x, t) => x + (t.bytes || 0), 0) : 0);
691
+ const freedBase = clean ? rewrite.reduce((x, t) => x + ((t.target && t.target.bytes) || 0), 0) : 0;
692
+ const s3 = pv.s3 && pv.s3.mode === 'bytes' ? pv.s3 : null;
693
+ return { need: { base: needBase, files: s3 ? s3.planned_bytes || 0 : 0 }, freed: { base: freedBase, files: s3 ? s3.freed_bytes || 0 : 0 } };
694
+ }
695
+
696
+ /** La sauvegarde n'a de sens que si la base va être écrite (lignes, comptes, secrets, migrations) */
697
+ function dbWrites(pv, sel, push) {
698
+ const has = (p) => sel.parts.includes(p);
699
+ if (has('secrets')) return true;
700
+ if (has('base') && pv.base && (pv.base.rewrite.length || pv.base.sequences.length)) return true;
701
+ if (has('auth') && pv.auth && pv.auth.changed) return true;
702
+ if (has('code') && pv.code) {
703
+ if (push && (pv.code.pending > 0 || pv.code.error)) return true;
704
+ if (!push && pv.code.migrations && pv.code.migrations.length > 0) return true;
705
+ }
706
+ return false;
707
+ }
708
+
709
+ async function spaceCheck(id, env, poadDir, push, amounts, P) {
710
+ const api = require('../cloud/api');
711
+ if (push) {
712
+ try {
713
+ const r = await api.call('GET', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-plan`, { what: 'room on poad.io' });
714
+ const sp = r.space && Number.isFinite(Number(r.space.limit)) ? { limit: Number(r.space.limit), used: Number(r.space.used), storage: r.space.storage === undefined || r.space.storage === null ? null : Number(r.space.storage) } : null;
715
+ return { where: env.branch, volume: true, ...P.room({ ...amounts, space: sp }) };
716
+ } catch (e) {
717
+ return { where: env.branch, ...P.room(amounts), note: e.status === 404 ? 'this poad.io does not tell the room left yet' : e.message };
718
+ }
719
+ }
720
+ try {
721
+ const st = fs.statfsSync(path.join(poadDir, 'data'));
722
+ const limit = st.blocks * st.bsize;
723
+ return { where: 'local disk', ...P.room({ ...amounts, space: { limit, used: limit - st.bavail * st.bsize, reserve: amounts.need.base > 0 ? 64 * 1024 ** 2 : 0 } }) };
724
+ } catch {
725
+ return { where: 'local disk', ...P.room(amounts) };
726
+ }
727
+ }
728
+
729
+ async function strongConfirm(id, env, opts, out) {
730
+ const api = require('../cloud/api');
731
+ const cli = require('../cloud/cli');
732
+ if (opts.confirm !== undefined) {
733
+ if (opts.confirm !== id) throw new api.CloudError(`--confirm ${opts.confirm}: this is not the project id (${id}). Nothing was changed.`, { code: 'confirmation_mismatch', exit: api.EXIT.confirm });
734
+ if (!cli.interactive() && !opts.yes) throw new api.CloudError('Outside a terminal, the production needs --yes and --confirm <project id>.', { code: 'confirmation_required', exit: api.EXIT.confirm });
735
+ return;
736
+ }
737
+ if (!cli.interactive() || out.json) throw new api.CloudError(`Production (${env.branch}) of ${id}: outside a terminal, confirm with --yes --confirm ${id}. Nothing was changed.`, { code: 'confirmation_required', exit: api.EXIT.confirm });
738
+ const { input } = require('@inquirer/prompts');
739
+ const typed = await input({ message: `This replaces the production of ${id} for the chosen parts (a backup is taken first). Type the project id (${id}) to confirm:` }).catch(() => '');
740
+ if (String(typed).trim() !== id) throw new api.CloudError('Cancelled: nothing was changed.', { code: 'cancelled', exit: api.EXIT.confirm });
741
+ }
742
+
743
+ /** Journaux : puits local (service cli) et, par poad.io, celui de l'environnement et de poad.io */
744
+ async function flushLogs({ api, id, env, rid, event, events, config, localStarted, out, direction }) {
745
+ const lines = events.map((e) => {
746
+ const l = { part: e.part, outcome: e.outcome, duration_ms: e.duration_ms };
747
+ if (e.table) l.table = e.table;
748
+ if (e.file) l.file = e.file;
749
+ if (e.reason) l.reason = e.reason;
750
+ if (e.step) l.step = e.step;
751
+ for (const k of ['rows', 'bytes', 'attempts', 'offset']) if (Number.isFinite(e[k])) l[k] = e[k];
752
+ return l;
753
+ });
754
+ if (localStarted) {
755
+ let client;
756
+ try {
757
+ client = await require('../migrations').connect(config);
758
+ for (const l of lines) {
759
+ const level = ['done', 'resumed', 'skipped', 'loaded'].includes(l.outcome) ? 'info' : 'warn';
760
+ const msg = `${direction} ${l.part}${l.table ? ` ${l.table}` : ''}${l.file ? ` ${l.file}` : ''}${l.step ? ` (${l.step})` : ''}: ${l.outcome}${l.reason ? ` (${l.reason})` : ''}`;
761
+ await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), $1, 'cli', $2, $3::jsonb)", [level, msg, JSON.stringify({ event, request_id: rid, project: id, env: env.branch, direction, ...l })]);
762
+ }
763
+ } catch {
764
+ out.log(out.chalk.grey(' (local log sink not reachable: lines not written locally)'));
765
+ } finally {
766
+ if (client) await client.end().catch(() => {});
767
+ }
768
+ }
769
+ const send = (body) => api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/sync-events`, { body, what: 'logs', timeout: 15000 });
770
+ try {
771
+ await send({ event, request_id: rid, lines: lines.slice(0, 500) });
772
+ } catch (e) {
773
+ // poad.io plus ancien : il refuse les lignes par fichier (outcome resumed, champ file) ; les autres passent
774
+ const plain = lines.filter((l) => !l.file && l.outcome !== 'resumed').map(({ reason, step, attempts, offset, ...l }) => l);
775
+ let sent = false;
776
+ if (e.status === 400 && plain.length) sent = await send({ event, request_id: rid, lines: plain.slice(0, 500) }).then(() => true, () => false);
777
+ if (!sent) out.log(out.chalk.grey(` (logs not written on poad.io: ${e.status === 404 ? 'this poad.io does not take them yet' : e.message})`));
778
+ }
779
+ }
780
+
781
+ const stamp = () => {
782
+ const d = new Date();
783
+ const p = (x) => String(x).padStart(2, '0');
784
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
785
+ };
786
+
787
+ function isNothing(pv, sel) {
788
+ const has = (p) => sel.parts.includes(p);
789
+ // Pousser le code : poad deploy redéploie toujours (fonctions, flows…) ; tirer : seulement ce qui diffère
790
+ if (has('code') && pv.code && pv.code.todo) return false;
791
+ if (has('base') && pv.base && (pv.base.rewrite.length || pv.base.sequences.length)) return false;
792
+ if (has('auth') && pv.auth && pv.auth.changed) return false;
793
+ if (has('refs') && pv.refs && pv.refs.todo) return false;
794
+ if (has('s3') && pv.s3 && pv.s3.todo) return false;
795
+ if (has('secrets')) return false;
796
+ return true;
797
+ }
798
+
799
+ function printPreview(out, P, pv, { push, env, sel }) {
800
+ const { chalk } = out;
801
+ if (out.json) return;
802
+ const pad = (s) => chalk.bold(String(s).padEnd(8));
803
+ out.log(' ');
804
+ if (pv.code) {
805
+ const c = pv.code;
806
+ if (push) {
807
+ if (c.error) out.log(` ${pad('code')}${chalk.redBright(c.error)}`);
808
+ else out.log(` ${pad('code')}poad deploy: ${c.files} file(s), ${c.pending} migration(s) to apply${c.pending_list && c.pending_list.length ? chalk.grey(` (${c.pending_list.slice(0, 5).join(', ')}${c.pending_list.length > 5 ? '…' : ''})`) : ''}`);
809
+ for (const e of c.errors || []) out.log(` ${chalk.redBright('✕')} ${e}`);
810
+ for (const f of c.fix || []) out.log(` ${chalk.grey('fix:')} ${chalk.cyanBright(f)}`);
811
+ } else {
812
+ const f = c.files;
813
+ out.log(` ${pad('code')}${c.migrations.length} migration(s) to pull${f ? `, files: +${f.add.length} ~${f.update.length} -${f.remove.length} (${f.unchanged} unchanged)` : ''}${c.error ? chalk.yellowBright(` (${c.error})`) : ''}`);
814
+ if (f) {
815
+ for (const x of f.add.slice(0, 20)) out.log(` ${chalk.greenBright('+')} ${x}`);
816
+ for (const x of f.update.slice(0, 20)) out.log(` ${chalk.yellowBright('~')} ${x}`);
817
+ for (const x of f.remove.slice(0, 20)) out.log(` ${chalk.redBright('-')} ${x}`);
818
+ for (const k of f.kept) out.log(` ${chalk.yellowBright('!')} ${k.rel} kept (${k.reason}): commit or stash it, then pull again`);
819
+ }
820
+ for (const cf of c.conflicts || []) out.log(` ${chalk.yellowBright('!')} migration ${cf.version}: ${cf.file} on poad.io, ${cf.local} here (left as is)`);
821
+ }
822
+ }
823
+ if (pv.base) {
824
+ const b = pv.base;
825
+ const same = b.tables.length - b.rewrite.length;
826
+ out.log(` ${pad('base')}${b.tables.length} table(s): ${b.rewrite.length} to rewrite, ${same} identical${b.excluded.length ? chalk.grey(`, ${b.excluded.length} reference table(s) left to refs`) : ''}`);
827
+ for (const t of b.rewrite) {
828
+ const d = t.diff;
829
+ const what = d.exact ? `${chalk.greenBright(`+${n(d.added)}`)} ${chalk.yellowBright(`~${n(d.replaced)}`)} ${chalk.redBright(`-${n(d.deleted)}`)}` : `${n(d.target_rows)} → ${n(d.rows)} rows (counts only: large table)`;
830
+ out.log(` ${t.key.padEnd(30)} ${what} ${chalk.grey(`${n(d.rows)} rows, ${P.size(t.bytes)}`)}`);
831
+ }
832
+ for (const x of b.blocked) out.log(` ${chalk.redBright('✕')} ${x.key}: ${x.detail}`);
833
+ if (b.blocked.length) out.log(` ${b.structure_after_code ? chalk.grey('the code part runs first and brings the structure: checked again after it') : chalk.yellowBright(`structure first: ${push ? 'poad deploy (or --only code)' : 'poad migration pull, then poad migrate (or --only code)'}`)}`);
834
+ if (b.migrations.missing.length) out.log(chalk.grey(` ${b.migrations.missing.length} migration(s) of the source not applied on the target${pv.code ? ' (code part)' : ''}`));
835
+ if (b.extra.length) out.log(chalk.grey(` only on the target, left as is: ${b.extra.slice(0, 8).join(', ')}${b.extra.length > 8 ? '…' : ''}`));
836
+ if (b.sequences.length) out.log(chalk.grey(` ${b.sequences.length} sequence(s) set as on the source`));
837
+ }
838
+ if (pv.auth) {
839
+ const a = pv.auth;
840
+ const u = a.tables.find((t) => t.name === 'users');
841
+ if (!u) out.log(` ${pad('auth')}${chalk.yellowBright('no auth.users table on one side: nothing to copy')}`);
842
+ else {
843
+ const d = u.diff;
844
+ out.log(` ${pad('auth')}${n(d.rows)} account(s): ${a.changed ? `${chalk.greenBright(`+${n(d.added)}`)} ${chalk.yellowBright(`~${n(d.replaced)}`)} ${chalk.redBright(`-${n(d.deleted)}`)}${a.closed.length ? chalk.grey(', sessions of the target closed') : ''}` : 'identical'}`);
845
+ if (a.dropped.length) out.log(chalk.yellowBright(` ⚠ not on the target, left out: ${a.dropped.join(', ')}`));
846
+ }
847
+ }
848
+ if (pv.refs) {
849
+ const r = pv.refs;
850
+ if (push) out.log(` ${pad('refs')}${r.large.length ? `${r.large.length} large file(s) to the store${r.large_by_code ? ' (by poad deploy)' : ''}, ` : ''}${r.load.length} table(s) to load in ${env.branch}${r.load.length ? chalk.grey(` (${r.load.slice(0, 6).join(', ')})`) : ''}`);
851
+ else out.log(` ${pad('refs')}${r.load.length} table(s) of the store to load locally${r.load.length ? chalk.grey(` (${r.load.slice(0, 6).map((x) => x.target).join(', ')})`) : ''}`);
852
+ }
853
+ if (pv.s3) {
854
+ const t = pv.s3.totals;
855
+ out.log(` ${pad('s3')}+${n(t.added)} ~${n(t.updated)} -${n(t.removed)} file(s)${t.buckets_created ? `, ${t.buckets_created} bucket(s) to create` : ''}, ${n(t.unchanged)} unchanged${pv.s3.mode === 'bytes' ? `, ${P.size(t.bytes)} to transfer` : chalk.grey(' (same place: references only)')}`);
856
+ }
857
+ if (sel.parts.includes('secrets')) {
858
+ const s = pv.secrets;
859
+ out.log(` ${pad('secrets')}${s.variables.length} variable value(s), ${s.credentials.length} credential(s)${s.credentials.length ? chalk.grey(` (${s.credentials.slice(0, 8).join(', ')})`) : ''}${s.target_storage.length ? chalk.grey(`; storage credentials of the target kept (${s.target_storage.join(', ')})`) : ''}`);
860
+ } else out.log(chalk.grey(` ${'secrets'.padEnd(8)}left out (--with-secrets to copy variable values and credentials)`));
861
+ if (pv.space) for (const [i, l] of roomLines(P, pv.space).entries()) out.log(i === 0 ? ` ${pad('room')}${l}` : ` ${l}`);
862
+ }
863
+
864
+ /** Lignes de la place (aperçu) : à écrire par partie, le volume (base et fichiers à part), libéré, verdict */
865
+ function roomLines(P, s) {
866
+ const chalk = require('chalk-v2');
867
+ const parts = [s.need.base ? `base ${P.size(s.need.base)}` : null, s.need.files ? `files ${P.size(s.need.files)}` : null].filter(Boolean).join(', ');
868
+ const lines = [`to write on ${s.where}: ${parts || 'nothing'}${s.need.base ? chalk.grey(` (base + 10 % + ${P.size(s.reserve || 0)} of journal)`) : ''}`];
869
+ if (!s.known) {
870
+ if (s.note) lines.push(chalk.grey(`room left unknown (${s.note})`));
871
+ return lines;
872
+ }
873
+ const split = s.used_files !== null && s.used_files !== undefined ? ` (base ${P.size(s.used_base)}, files ${P.size(s.used_files)})` : '';
874
+ lines.push(`${s.volume ? 'volume' : 'disk'} ${P.size(s.limit)}: ${P.size(s.used)} used${split}, ${s.over ? chalk.redBright(`exceeded by ${P.size(s.over)}`) : `${P.size(s.free)} free`}`);
875
+ const fr = s.freed.base + s.freed.files;
876
+ if (fr) lines.push(chalk.grey(`freed on the way: ${[s.freed.files ? `files ${P.size(s.freed.files)} (replaced or removed)` : null, s.freed.base ? `base ${P.size(s.freed.base)} (--clean)` : null].filter(Boolean).join(', ')}`));
877
+ lines.push(s.ok ? `${chalk.greenBright('fits')}: ${P.size(s.required)} needed, ${P.size(s.available)} available` : `${chalk.redBright('not enough')}: ${P.size(s.required)} needed, ${P.size(s.available)} available, ${chalk.redBright(`${P.size(s.missing)} missing`)} (a larger plan, or fewer files: --skip s3)`);
878
+ return lines;
879
+ }
880
+
881
+ function resultOf({ direction, id, env, sel, dry, preview, blocking, events, started, results, backup, failed }) {
882
+ const pv = preview;
883
+ const strip = (t) => ({ table: t.key, rows: t.diff.rows, target_rows: t.diff.target_rows, added: t.diff.added, replaced: t.diff.replaced, deleted: t.diff.deleted, unchanged: t.diff.unchanged, exact: t.diff.exact, bytes: t.bytes, rewrite: Boolean(t.changed) });
884
+ return {
885
+ direction,
886
+ project: id,
887
+ env: env.branch,
888
+ production: env.production,
889
+ dry_run: dry,
890
+ parts: sel.parts,
891
+ tables: sel.tables,
892
+ preview: {
893
+ code: pv.code ? (pv.code.files && pv.code.files.remote ? { ...pv.code, files: { add: pv.code.files.add, update: pv.code.files.update, remove: pv.code.files.remove, unchanged: pv.code.files.unchanged, kept: pv.code.files.kept } } : pv.code) : null,
894
+ base: pv.base ? { tables: pv.base.tables.map(strip), blocked: pv.base.blocked, excluded: pv.base.excluded, extra: pv.base.extra, migrations: pv.base.migrations, sequences: pv.base.sequences.length } : null,
895
+ auth: pv.auth ? { changed: pv.auth.changed, tables: pv.auth.tables.map((t) => strip({ ...t, bytes: t.bytes, changed: pv.auth.changed })), dropped: pv.auth.dropped } : null,
896
+ refs: pv.refs,
897
+ s3: pv.s3,
898
+ secrets: pv.secrets ? { variables: pv.secrets.variables.length, credentials: pv.secrets.credentials } : null,
899
+ space: pv.space,
900
+ },
901
+ blocking,
902
+ backup: backup || null,
903
+ results: results || null,
904
+ failed: Boolean(failed),
905
+ duration_ms: Date.now() - started,
906
+ logs: events,
907
+ };
908
+ }
909
+
910
+ module.exports = { run, SPEC, batch, self };