poad 2.75.1 → 2.75.3

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/global/start.js CHANGED
@@ -43,12 +43,26 @@ module.exports = async (args = {}) => {
43
43
  const all = wantsAll(args);
44
44
  const bare = Boolean(args.bare || args['--bare']);
45
45
 
46
+ // Types des fonctions (poad/functions/.poad/types) : rafraîchis à chaque démarrage, pour suivre le runtime
47
+ // de l'engine lancé (sinon un projet garde ceux de l'engine où il les a posés). Seulement si le projet a
48
+ // des fonctions ou des types déjà posés ; silencieux si rien ne change.
49
+ const refreshFunctionTypes = async () => {
50
+ const fsSync = require('fs');
51
+ const dir = path.join(path.dirname(root), 'functions');
52
+ const has = fsSync.existsSync(path.join(dir, '.poad', 'types')) || (fsSync.existsSync(dir) && fsSync.readdirSync(dir).some((n) => fsSync.existsSync(path.join(dir, n, 'index.ts')) || fsSync.existsSync(path.join(dir, n, 'index.js'))));
53
+ if (!has) return;
54
+ const types = require('../utils/function-types');
55
+ const done = types.write(dir, await types.fetchBundle(require('../utils/config').loadConfig(root), 30));
56
+ if (done && done.changed) console.log(chalk.grey(` Editor types of the functions refreshed: ${path.relative(process.cwd(), path.join(dir, '.poad', 'types')) || '.'} (${done.count} files).`));
57
+ };
58
+
46
59
  // Services optionnels à lancer, puis l'état complet du projet
47
60
  const finish = async () => {
48
61
  const targets = bare ? [] : all ? SERVICES.filter((s) => s.optional && s.configured(config)) : autostartServices(config, root);
49
62
  // Groupe « Services » de la console (Mailpit, Keycloak) : ports de cette machine, après leur réattribution
50
63
  require('../utils/console-services').write(root);
51
64
  if (targets.length) await require('./run')({ services: targets.map((s) => s.id), quiet: true });
65
+ await refreshFunctionTypes();
52
66
  console.log(' ');
53
67
  await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root), { justStarted: true });
54
68
  };
@@ -233,7 +247,7 @@ module.exports = async (args = {}) => {
233
247
  process.exitCode = 1;
234
248
  } else {
235
249
  waiting.stop();
236
- const migrated = migrate ? await require('../utils/migrate-run')(root, config, { quietWhenNone: false }) : true;
250
+ const migrated = migrate ? await require('../utils/migrate-run')(root, config, { quietWhenNone: false, via: 'poad start' }) : true;
237
251
  // Code de sortie 1 si une migration ou le seed échoue (scripts, CI)
238
252
  if (!migrated) process.exitCode = 1;
239
253
  if (hasReference && migrated && !(await reference.sync(root, config))) process.exitCode = 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.75.1",
3
+ "version": "2.75.3",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
@@ -89,4 +89,39 @@ module.exports = async (args = {}) => {
89
89
  console.log(' ');
90
90
  await require('../../utils/report').printServices(root, readConfig(root));
91
91
  }
92
+ // Sources « Fichier envoyé » : leur fichier n'était que dans le stockage local, effacé avec lui. Le bucket
93
+ // poad-sources revient (meta), la déclaration aussi, mais le fichier ne revient que par un nouvel envoi.
94
+ const uploads = uploadSources(path.dirname(root));
95
+ if (uploads.length) {
96
+ console.log(' ');
97
+ console.log(chalk.yellowBright(` ${uploads.length} source(s) loaded from a sent file: the file was erased with the local storage, send it again to reload the table:`));
98
+ for (const u of uploads) console.log(chalk.grey(` poad source import <file> --table ${u.table}`));
99
+ }
100
+ };
101
+
102
+ /** Sources « Fichier envoyé » déclarées dans poad/sources (origin.kind: upload) : { name, table } */
103
+ const uploadSources = (root) => {
104
+ const fs = require('fs');
105
+ const path = require('path');
106
+ const dir = path.join(root, 'sources');
107
+ let files = [];
108
+ try {
109
+ files = fs.readdirSync(dir).filter((f) => /\.ya?ml$/.test(f));
110
+ } catch {
111
+ return [];
112
+ }
113
+ const out = [];
114
+ for (const f of files) {
115
+ let text = '';
116
+ try {
117
+ text = fs.readFileSync(path.join(dir, f), 'utf8');
118
+ } catch {
119
+ continue;
120
+ }
121
+ if (!/^\s+kind:\s*['"]?upload['"]?\s*(#.*)?$/m.test(text) && !/kind:\s*['"]?upload['"]?\s*[,}]/.test(text)) continue;
122
+ const table = (/^table:\s*['"]?(?:public\.)?([A-Za-z0-9_]+)/m.exec(text) || [])[1] || f.replace(/\.ya?ml$/, '');
123
+ out.push({ name: f.replace(/\.ya?ml$/, ''), table });
124
+ }
125
+ return out;
92
126
  };
127
+ module.exports.uploadSources = uploadSources;
package/project/deploy.js CHANGED
@@ -1,4 +1,4 @@
1
- // poad deploy [--env <branche>] [--dry-run] [--yes] [--json]
1
+ // poad deploy [--env <branche>] [--dry-run] [--yes] [--allow-destructive | --accept-data-loss] [--json]
2
2
  //
3
3
  // Envoie le dossier poad/ (liste blanche, sans aucun secret : utils/cloud/bundle.js)
4
4
  // à l'environnement du projet poad.io lié :
@@ -6,15 +6,21 @@
6
6
  // x-poad-sha commit git courant, si poad/ n'a aucun changement non commité
7
7
  // x-poad-dry-run 1 avec --dry-run : le serveur dit ce qu'il ferait, rien ne change
8
8
  // réponse : { deploy_id?, status?, migrations: { applied, pending, errors }, warnings }
9
- // warnings : migrations qui perdent des données (drop table, truncate…), signalées, jamais refusées
9
+ // x-poad-allow-destructive 1 avec --allow-destructive (ou après confirmation) : la production applique des
10
+ // migrations qui perdent des données
11
+ // warnings : migrations appliquées modifiées depuis… (et, pour les anciens CLI, le résumé des pertes de données)
12
+ // data_loss : [{ file, line, statement, target, rows, kind, decision, message }] (poad.io 0.70+) : ce que les
13
+ // migrations en attente perdent vraiment, compté sur la base de l'environnement (utils/data-loss.js) ; silence
14
+ // quand la cible est créée par le même déploiement ou vide. Production : refus destructive_migrations sans
15
+ // x-poad-allow-destructive, avant toute écriture ; dans un terminal, le CLI demande et relance avec l'en-tête.
10
16
  // api_exposure : fonctions et vues que l'API ne sert pas à anon ni à authenticated (SECURITY DEFINER, vues
11
17
  // sans security_invoker, vues matérialisées), dans la base et dans les migrations en attente, avec ce que
12
18
  // l'engine de l'environnement en fait et le correctif de chacune (poad.io 0.66.0+), jamais bloquant
13
19
  // asynchrone (deploy_id et état non terminé) : GET …/deploys/:deploy_id jusqu'à la fin
14
20
  //
15
21
  // Production (main) : résumé puis confirmation, sauf --yes (obligatoire hors
16
- // terminal). Codes de sortie : 0 déployé, 5 déploiement en échec (erreurs de
17
- // migration), 4 confirmation manquante, 3 session, 2 usage, 1 autre erreur.
22
+ // terminal ; --yes n'accepte pas une perte de données). Codes de sortie : 0 déployé, 5 déploiement en échec
23
+ // (erreurs de migration), 4 confirmation manquante (ou perte de données refusée), 3 session, 2 usage, 1 autre erreur.
18
24
  const DONE = ['succeeded', 'success', 'refused', 'done', 'deployed', 'completed', 'ok', 'failed', 'error', 'cancelled', 'canceled'];
19
25
  const FAILED = ['failed', 'error', 'cancelled', 'canceled', 'refused'];
20
26
 
@@ -67,13 +73,25 @@ function summarize(d = {}) {
67
73
  dry_run: Boolean(d.dry_run),
68
74
  migrations: { applied: names(m.applied), pending: names(m.pending), errors },
69
75
  message: typeof d.message === 'string' ? d.message : null,
70
- // Signalé, jamais bloquant : migrations qui perdent des données (drop table, truncate…)
71
- warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [] })),
76
+ // Signalé, jamais bloquant : migrations appliquées modifiées, résumé des pertes de données (code data_loss)
77
+ warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [], ...(w && typeof w.code === 'string' ? { code: w.code } : {}) })),
78
+ data_loss: dataLossOf(d.data_loss),
79
+ refused: errors.some((e) => e.code === 'destructive_migrations') ? 'destructive_migrations' : null,
72
80
  failed: errors.length > 0 || FAILED.includes(status),
73
81
  api_exposure: exposureOf(d.api_exposure),
74
82
  };
75
83
  }
76
84
 
85
+ /** Pertes de données rendues par poad.io, ramenées aux champs connus (textes bornés) */
86
+ function dataLossOf(list) {
87
+ if (!Array.isArray(list)) return [];
88
+ const str = (v, n) => (typeof v === 'string' ? v.slice(0, n) : null);
89
+ return list
90
+ .filter((x) => x && typeof x.file === 'string' && typeof x.kind === 'string')
91
+ .slice(0, 200)
92
+ .map((x) => ({ file: str(x.file, 200), line: Number.isInteger(x.line) ? x.line : null, statement: str(x.statement, 300), target: str(x.target, 200), rows: typeof x.rows === 'number' ? x.rows : null, approx: Boolean(x.approx), kind: str(x.kind, 40), loss: Boolean(x.loss), decision: str(x.decision, 20), message: str(x.message, 400) }));
93
+ }
94
+
77
95
  /** Avertissement de l'API (poad.io) ramené à la règle du CLI (utils/api-exposure) : textes en anglais */
78
96
  function exposureOf(x) {
79
97
  if (!x || typeof x !== 'object' || !Array.isArray(x.items)) return null;
@@ -101,7 +119,7 @@ function gitState(dir) {
101
119
  }
102
120
 
103
121
  module.exports = (args, raw) =>
104
- require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive'] }, async ({ opts, out }) => {
122
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive', 'accept-data-loss'] }, async ({ opts, out }) => {
105
123
  const path = require('path');
106
124
  const api = require('../utils/cloud/api');
107
125
  const cli = require('../utils/cloud/cli');
@@ -118,7 +136,9 @@ module.exports = (args, raw) =>
118
136
  // Tables de référence trop lourdes pour git : hors de l'archive, envoyées au magasin de références
119
137
  const large = refStore.largeFiles(poadDir);
120
138
  const ignored = refStore.ensureGitignore(poadDir, large);
121
- // --allow-destructive : accepté, sans effet (poad.io signale les migrations qui perdent des données, sans refuser)
139
+ // --allow-destructive (alias --accept-data-loss) : la production applique sans demander les migrations qui
140
+ // perdent des données ; sans lui, poad.io refuse (avant toute écriture) et le CLI demande dans un terminal
141
+ let allowLoss = Boolean(opts['allow-destructive'] || opts['accept-data-loss']);
122
142
 
123
143
  const env = await branches.resolve(id, { wanted: opts.env, root });
124
144
  let b;
@@ -158,22 +178,55 @@ module.exports = (args, raw) =>
158
178
  const route = `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}`;
159
179
  // --env des commandes proposées : omis quand poad deploy l'aurait aussi omis (production par défaut)
160
180
  const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
161
- const headers = {};
162
- if (sha) headers['x-poad-sha'] = sha;
163
- if (dryRun) headers['x-poad-dry-run'] = '1';
164
- let result = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000 }));
165
-
166
- // Déploiement asynchrone : suivi jusqu'à son terme
167
- if (result.deploy_id && result.status && !DONE.includes(result.status)) {
168
- const started = Date.now();
169
- let last = result.status;
170
- out.log(chalk.grey(` deploy ${result.deploy_id}: ${last}…`));
171
- while (!DONE.includes(result.status)) {
172
- if (Date.now() - started > 15 * 60 * 1000) throw new api.CloudError(`Deploy ${result.deploy_id} still ${result.status} after 15 min: follow it on poad.io.`, { code: 'timeout' });
173
- await new Promise((r) => setTimeout(r, Number(process.env.POAD_DEPLOY_POLL_MS) || 2000));
174
- const next = summarize(await api.call('GET', `${route}/deploys/${api.enc(result.deploy_id)}`, { what: 'deploy status' }));
175
- result = { ...next, deploy_id: next.deploy_id || result.deploy_id };
176
- if (result.status !== last) out.log(chalk.grey(` deploy ${result.deploy_id}: ${(last = result.status)}`));
181
+ const send = async () => {
182
+ const headers = {};
183
+ if (sha) headers['x-poad-sha'] = sha;
184
+ if (dryRun) headers['x-poad-dry-run'] = '1';
185
+ if (allowLoss) headers['x-poad-allow-destructive'] = '1';
186
+ let r = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000 }));
187
+ // Déploiement asynchrone : suivi jusqu'à son terme
188
+ if (r.deploy_id && r.status && !DONE.includes(r.status)) {
189
+ const started = Date.now();
190
+ let last = r.status;
191
+ out.log(chalk.grey(` deploy ${r.deploy_id}: ${last}…`));
192
+ while (!DONE.includes(r.status)) {
193
+ if (Date.now() - started > 15 * 60 * 1000) throw new api.CloudError(`Deploy ${r.deploy_id} still ${r.status} after 15 min: follow it on poad.io.`, { code: 'timeout' });
194
+ await new Promise((res) => setTimeout(res, Number(process.env.POAD_DEPLOY_POLL_MS) || 2000));
195
+ const next = summarize(await api.call('GET', `${route}/deploys/${api.enc(r.deploy_id)}`, { what: 'deploy status' }));
196
+ r = { ...next, deploy_id: next.deploy_id || r.deploy_id };
197
+ if (r.status !== last) out.log(chalk.grey(` deploy ${r.deploy_id}: ${(last = r.status)}`));
198
+ }
199
+ }
200
+ return r;
201
+ };
202
+ let result = await send();
203
+ const lossLines = (r) => require('../utils/migrate-run').dataLossLines(r.data_loss, chalk, { production: env.production });
204
+
205
+ // Production : des migrations perdent des données, poad.io a refusé avant toute écriture. Dans un terminal :
206
+ // ce qui serait perdu, puis la question ; oui : même envoi avec x-poad-allow-destructive. Sinon : refus (code 4).
207
+ let lossRefused = false;
208
+ let lossShown = false;
209
+ if (result.refused === 'destructive_migrations' && !allowLoss && !dryRun) {
210
+ out.log(' ');
211
+ for (const l of lossLines(result)) out.log(l);
212
+ lossShown = true;
213
+ const lost = result.data_loss.filter((d) => d.loss && d.decision === 'confirm');
214
+ const total = lost.reduce((n, d) => n + (d.rows || 0), 0);
215
+ if (cli.interactive() && !out.json) {
216
+ const { confirm: ask } = require('@inquirer/prompts');
217
+ out.log(' ');
218
+ const ok = await ask({ message: `Apply anyway on production (${env.branch})? ${lost.length} statement(s), ${total.toLocaleString('en-US')}${lost.some((d) => d.approx || d.rows === null) ? '+' : ''} row(s) or value(s) lost (a backup is taken first).`, default: false }).catch(() => false);
219
+ if (ok) {
220
+ allowLoss = true;
221
+ result = await send();
222
+ } else {
223
+ out.log(chalk.grey(' Cancelled: nothing was changed.'));
224
+ lossRefused = true;
225
+ }
226
+ } else {
227
+ out.log(chalk.redBright(' Refused: these migrations lose data on production. Nothing was changed.'));
228
+ out.log(chalk.grey(' Run poad deploy in a terminal to confirm, or add --allow-destructive.'));
229
+ lossRefused = true;
177
230
  }
178
231
  }
179
232
 
@@ -182,12 +235,17 @@ module.exports = (args, raw) =>
182
235
  for (const n of m.applied) out.log(` ${chalk.greenBright('✔')} ${n}`);
183
236
  for (const n of m.pending) out.log(` ${chalk.yellow('○')} ${n} ${chalk.grey(dryRun ? '(would be applied)' : '(pending)')}`);
184
237
  for (const e of m.errors) {
238
+ // Refus pour pertes de données : déjà détaillé (et demandé) plus haut
239
+ if (e.code === 'destructive_migrations' && result.data_loss.length) continue;
185
240
  out.log(` ${chalk.redBright('✕')} ${e.migration ? chalk.bold(e.migration) + ': ' : ''}${e.message}`);
186
241
  // Refus : lesquelles ; migrations manquantes ou hors d'ordre : la commande qui lève le refus
187
242
  for (const f of e.files || []) out.log(` ${chalk.yellow(f)}`);
188
243
  for (const l of refusalLines(e, { env: env.branch, where, chalk })) out.log(l);
189
244
  }
245
+ // Pertes de données (sauf si déjà montrées avec le refus) : fichier, instruction, nombre de lignes
246
+ if (!result.refused && !lossShown) for (const l of lossLines(result)) out.log(l);
190
247
  for (const w of result.warnings || []) {
248
+ if (w.code === 'data_loss' && result.data_loss.length) continue;
191
249
  out.log(` ${chalk.yellowBright('⚠')} ${w.message}`);
192
250
  for (const f of w.files) out.log(` ${chalk.yellow(f)}`);
193
251
  }
@@ -202,7 +260,8 @@ module.exports = (args, raw) =>
202
260
  }
203
261
 
204
262
  out.log(' ');
205
- if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
263
+ if (lossRefused) out.log(chalk.redBright(' Deploy refused: pending migrations lose data on production.'));
264
+ else if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
206
265
  else if (dryRun && large.length) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}. ${large.map((f) => f.target).join(', ')} would go to the reference store, then be loaded.`);
207
266
  else if (dryRun) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}.`);
208
267
  else out.log(`${chalk.greenBright('✔')} Deployed to ${env.branch}${result.deploy_id ? chalk.grey(` (${result.deploy_id})`) : ''}.`);
@@ -225,7 +284,7 @@ module.exports = (args, raw) =>
225
284
  large_references: large.map((f) => ({ path: `poad/${f.rel}`, bytes: f.size, target: f.target })),
226
285
  references,
227
286
  });
228
- return result.failed ? api.EXIT.failed : 0;
287
+ return lossRefused ? api.EXIT.confirm : result.failed ? api.EXIT.failed : 0;
229
288
  });
230
289
 
231
290
  module.exports.summarize = summarize;
@@ -25,29 +25,6 @@ export default {
25
25
  };
26
26
  `;
27
27
 
28
- // tsconfig.json de poad/functions : API web (celles de workerd) et @poadio/*
29
- // relié aux types déposés par l'engine, pour l'autocomplétion sans node_modules
30
- const TSCONFIG = `{
31
- "compilerOptions": {
32
- "target": "ES2022",
33
- "module": "ESNext",
34
- "moduleResolution": "bundler",
35
- "lib": ["ES2022", "WebWorker"],
36
- "types": [],
37
- "strict": true,
38
- "noEmit": true,
39
- "skipLibCheck": true,
40
- "allowImportingTsExtensions": true,
41
- "paths": {
42
- "@poadio/*": ["./.poad/types/@poadio/*/index.d.ts"]
43
- }
44
- },
45
- "include": ["**/*.ts", "**/*.tsx"],
46
- "exclude": ["node_modules"]
47
- }
48
- `;
49
- const TYPE_FILE_RE = /^@poadio\/[a-z][a-z0-9-]*(\/[A-Za-z0-9_-]+)*\/[A-Za-z0-9_.-]+\.d\.ts$/;
50
-
51
28
  module.exports = async (args = {}) => {
52
29
  const chalk = require('chalk-v2');
53
30
  const fs = require('fs');
@@ -62,34 +39,14 @@ module.exports = async (args = {}) => {
62
39
  const rel = (p) => path.relative(process.cwd(), p) || p;
63
40
  const words = Object.keys(args);
64
41
 
65
- // Types pour l'éditeur : lus sur l'engine lancé (accordés à son client poad)
42
+ // Types pour l'éditeur : lus sur l'engine lancé (accordés à son runtime)
66
43
  // et déposés dans poad/functions/.poad/types. Renvoie le nombre de fichiers, ou null.
67
44
  const installTypes = async () => {
68
45
  const config = readConfig(root);
69
46
  if (!(await isDockerExist(config.project_uuid))) return null;
70
- let bundle;
71
- try {
72
- const res = await fetch(`http://localhost:${config.web.port}/functions/v1/types.json`, { signal: AbortSignal.timeout(5000) });
73
- if (!res.ok) return null;
74
- bundle = await res.json();
75
- } catch {
76
- return null;
77
- }
78
- const files = Object.entries((bundle && bundle.files) || {}).filter(([name, text]) => TYPE_FILE_RE.test(name) && !name.includes('..') && typeof text === 'string');
79
- if (!files.length) return null;
80
- const typesDir = path.join(dir, '.poad', 'types');
81
- fs.rmSync(typesDir, { recursive: true, force: true });
82
- for (const [name, text] of files) {
83
- const target = path.join(typesDir, name);
84
- fs.mkdirSync(path.dirname(target), { recursive: true });
85
- fs.writeFileSync(target, text);
86
- }
87
- // L'ancien fichier de types (client en « any ») masquerait les nouveaux
88
- const old = path.join(dir, 'poad-functions.d.ts');
89
- if (fs.existsSync(old) && fs.readFileSync(old, 'utf8').startsWith('// Généré par poad')) fs.rmSync(old);
90
- const tsconfig = path.join(dir, 'tsconfig.json');
91
- if (!fs.existsSync(tsconfig)) fs.writeFileSync(tsconfig, TSCONFIG);
92
- return files.length;
47
+ const types = require('../utils/function-types');
48
+ const done = types.write(dir, await types.fetchBundle(config));
49
+ return done ? done.count : null;
93
50
  };
94
51
  const reportTypes = (count) => {
95
52
  if (count) console.log(chalk.grey(` Editor types: ${rel(path.join(dir, '.poad', 'types'))} (${count} files) and ${rel(path.join(dir, 'tsconfig.json'))}. No install needed.`));
@@ -1,4 +1,5 @@
1
- // poad migrate : applique les migrations en attente de poad/migrations
1
+ // poad migrate [--dry-run] [--json] : applique les migrations en attente de poad/migrations (avant : ce qu'elles
2
+ // perdent sur la base, utils/data-loss.js, avertissement seulement en local)
2
3
  // poad migrate pull | list | renumber : poad/migrations face à poad.io (migration-pull.js, migrate-cloud.js)
3
4
  module.exports = async (args, raw = []) => {
4
5
  if (raw[0] === 'pull') return require('./migration-pull')(raw.slice(1));
@@ -30,10 +31,13 @@ module.exports = async (args, raw = []) => {
30
31
  let ok;
31
32
  let refOk = true;
32
33
  try {
33
- ok = await require('../utils/migrate-run')(root, config, { report, exposureList: true });
34
+ // --dry-run : migrations en attente et ce qu'elles perdraient (comptées sur la base), rien d'appliqué
35
+ const dryRun = process.argv.includes('--dry-run');
36
+ ok = await require('../utils/migrate-run')(root, config, { report, exposureList: true, dryRun });
37
+ if (dryRun) report.dry_run = true;
34
38
  // Tables de référence : après les migrations, quand leur structure est à jour
35
39
  // --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
36
- if (ok) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
40
+ if (ok && !dryRun) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
37
41
  } finally {
38
42
  console.log = log;
39
43
  }
@@ -107,6 +107,15 @@ function fakeCloud(t, behaviour = {}) {
107
107
  if (req.method === 'POST' && m[2] === '/deploy') {
108
108
  const dry = req.headers['x-poad-dry-run'] === '1';
109
109
  if (behaviour.refuse) return send(res, 200, { deploy_id: 'dr', outcome: 'refused', dry_run: dry, migrations_applied: [], migrations_pending: [], errors: [behaviour.refuse] });
110
+ // Pertes de données (push.sh, control/data-loss.cjs) : production refusée sans x-poad-allow-destructive
111
+ if (behaviour.dataLoss) {
112
+ const prod = branch === 'main';
113
+ const allow = req.headers['x-poad-allow-destructive'] === '1';
114
+ const item = (decision) => ({ file: '20261204212826_sans_fichier.sql', line: 2, statement: 'alter table public.documents drop column fichier', target: 'public.documents.fichier', rows: 1240, approx: false, kind: 'drop_column', loss: true, decision, message: 'DROP COLUMN public.documents.fichier — 1,240 non-null value(s) will be lost' });
115
+ const summary = { message: 'pending migrations lose data or break API clients', files: ['20261204212826_sans_fichier.sql'], code: 'data_loss' };
116
+ if (prod && !allow && !dry) return send(res, 200, { deploy_id: 'dl', outcome: 'refused', migrations_applied: [], migrations_pending: ['20261204212826_sans_fichier.sql'], errors: [{ code: 'destructive_migrations', message: 'pending migrations lose data on production', files: ['20261204212826_sans_fichier.sql'] }], warnings: [], data_loss: [item('confirm')] });
117
+ return send(res, 200, { deploy_id: 'dl', outcome: 'success', dry_run: dry, migrations_applied: dry ? [] : ['20261204212826_sans_fichier.sql'], migrations_pending: dry ? ['20261204212826_sans_fichier.sql'] : [], errors: [], warnings: [summary], data_loss: [item(!prod ? 'warn' : allow ? 'accepted' : 'confirm')] });
118
+ }
110
119
  if (behaviour.async) {
111
120
  state.deploys.d1 = 0;
112
121
  // La forme réelle de poad.io (control/server.mjs, deployView) : outcome, migrations_applied…
@@ -827,3 +836,44 @@ test('pendingToRenumber : pure', () => {
827
836
  assert.deepStrictEqual(pendingToRenumber([l('20261109000000'), l('20261101000000'), l('20261111000000')], remote).map((m) => m.version), ['20261101000000', '20261109000000', '20261111000000']);
828
837
  assert.deepStrictEqual(pendingToRenumber([l('20261101000000')], []), []);
829
838
  });
839
+
840
+ test('deploy : pertes de données (à la Prisma) : recette avertie ; production refusée hors terminal (code 4), --allow-destructive passe ; --json data_loss', async (t) => {
841
+ const box = sandbox(t);
842
+ const cloud = await fakeCloud(t, { dataLoss: true });
843
+ await login(box, cloud);
844
+ await poad(box, cloud.api, ['link', PID]);
845
+ git(box.app, 'commit', '-qam', 'link');
846
+
847
+ // Recette : avertissement avec fichier, instruction et nombre ; jamais de question
848
+ const dev = await poad(box, cloud.api, ['deploy', '--env', 'dev']);
849
+ assert.strictEqual(dev.status, 0, dev.all);
850
+ assert.match(dev.stdout, /20261204212826_sans_fichier\.sql:2\s+DROP COLUMN public\.documents\.fichier — 1,240 non-null value\(s\) will be lost/);
851
+ assert.match(dev.stdout, /alter table public\.documents drop column fichier/);
852
+ assert.doesNotMatch(dev.stdout, /pending migrations lose data or break API clients\n/, 'résumé des anciens CLI remplacé par le détail');
853
+
854
+ // Production, hors terminal, --yes : refus (--yes n'accepte pas une perte de données), rien appliqué
855
+ const refused = await poad(box, cloud.api, ['deploy', '--yes']);
856
+ assert.strictEqual(refused.status, 4, refused.all);
857
+ assert.match(refused.stdout, /1,240 non-null value\(s\) will be lost/);
858
+ assert.match(refused.stdout, /--allow-destructive/);
859
+ assert.match(refused.stdout, /Deploy refused/);
860
+ assert.strictEqual(cloud.requests.filter((q) => q.route.endsWith('/main/deploy')).length, 1, 'un seul envoi');
861
+
862
+ const j = jsonOf(await poad(box, cloud.api, ['deploy', '--yes', '--json']));
863
+ assert.strictEqual(j.refused, 'destructive_migrations');
864
+ assert.deepStrictEqual(Object.fromEntries(['file', 'statement', 'target', 'rows', 'kind'].map((k) => [k, j.data_loss[0][k]])), { file: '20261204212826_sans_fichier.sql', statement: 'alter table public.documents drop column fichier', target: 'public.documents.fichier', rows: 1240, kind: 'drop_column' });
865
+
866
+ // --dry-run : la même chose, sans refus ni envoi de l'en-tête
867
+ const dry = await poad(box, cloud.api, ['deploy', '--dry-run']);
868
+ assert.strictEqual(dry.status, 0, dry.all);
869
+ assert.match(dry.stdout, /1,240 non-null value\(s\) will be lost/);
870
+ assert.match(dry.stdout, /data is lost only after a confirmation/);
871
+
872
+ // --allow-destructive (ou --accept-data-loss) : l'en-tête part, déployé
873
+ for (const flag of ['--allow-destructive', '--accept-data-loss']) {
874
+ const ok = await poad(box, cloud.api, ['deploy', '--yes', flag]);
875
+ assert.strictEqual(ok.status, 0, ok.all);
876
+ assert.strictEqual(cloud.requests.filter((q) => q.route.endsWith('/main/deploy')).at(-1).headers['x-poad-allow-destructive'], '1');
877
+ assert.match(ok.stdout, /Deployed to main/);
878
+ }
879
+ });
@@ -0,0 +1,112 @@
1
+ // Avertissement à la Prisma (utils/data-loss.js) : lecture des migrations, décision. Sans base : les résultats
2
+ // des requêtes sont donnés à la main (le comptage réel est essayé sur un projet jetable, poad migrate).
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const dl = require('../utils/data-loss');
6
+
7
+ const kinds = (sql) => dl.analyze([{ file: '20261204212826_x.sql', sql }]).map((f) => `${f.kind} ${f.schema}${f.table ? '.' + f.table : ''}${f.column ? '.' + f.column : ''}`);
8
+
9
+ test('commentaires, chaînes et corps de fonctions ($$, BEGIN ATOMIC) ignorés', () => {
10
+ const sql = `-- drop table a;
11
+ /* drop table b; /* imbriqué */ truncate c; */
12
+ create function f() returns void language plpgsql as $$ begin drop table z; delete from w; end $$;
13
+ create function g() returns void language plpgsql as $body$ begin execute 'truncate q'; end $body$;
14
+ do $x$ begin alter table t drop column c; end $x$;
15
+ select 'drop table k', E'it\\'s; drop table j', "drop table";
16
+ create function h() returns int language sql begin atomic select case when true then 1 end; delete from inatomic; end;
17
+ drop table vraie;`;
18
+ assert.deepStrictEqual(kinds(sql), ['drop_table public.vraie']);
19
+ });
20
+
21
+ test('instructions repérées avec leur cible', () => {
22
+ const sql = `ALTER TABLE public.documents DROP COLUMN fichier, ADD COLUMN x int DEFAULT f(1, 2), ALTER COLUMN n TYPE numeric(5,2) USING n::numeric;
23
+ alter table t drop constraint k, alter column c drop default, alter column d set not null;
24
+ truncate table a, only s.b restart identity;
25
+ delete from logs; delete from s.l2 where id in (select id from z);
26
+ with d as (delete from old returning *) select 1;
27
+ drop table if exists t1, "Mixte".T2 cascade; drop schema arch cascade;
28
+ alter table x rename column a to b; alter table x rename to y; alter table x rename constraint k to l;
29
+ drop view if exists v1; drop function g(int, text);`;
30
+ assert.deepStrictEqual(kinds(sql), [
31
+ 'drop_column public.documents.fichier',
32
+ 'alter_type public.documents.n',
33
+ 'truncate public.a',
34
+ 'truncate s.b',
35
+ 'delete public.logs',
36
+ 'delete_where s.l2',
37
+ 'delete public.old',
38
+ 'drop_table public.t1',
39
+ 'drop_table Mixte.t2',
40
+ 'drop_schema arch',
41
+ 'rename_column public.x.a',
42
+ 'rename_table public.x',
43
+ 'drop_view public.v1',
44
+ 'drop_function public.g',
45
+ ]);
46
+ const [f] = dl.analyze([{ file: 'a.sql', sql: '\n\nalter table documents\n drop column fichier; -- fin' }]);
47
+ assert.strictEqual(f.line, 3);
48
+ assert.strictEqual(f.statement, 'alter table documents drop column fichier');
49
+ });
50
+
51
+ test('renommage dans le lot : la cible est cherchée sous son nom sur la base ; vue recréée : silence', () => {
52
+ const f = dl.analyze([
53
+ { file: '1.sql', sql: 'alter table old_name rename to new_name;' },
54
+ { file: '2.sql', sql: 'alter table new_name drop column c; drop view if exists v; create or replace view v as select 1;' },
55
+ ]);
56
+ assert.deepStrictEqual(f[1].db, { schema: 'public', table: 'old_name', column: 'c' });
57
+ assert.strictEqual(f[2].recreated, true);
58
+ });
59
+
60
+ const one = (sql, result, opts) => {
61
+ const findings = dl.analyze([{ file: '20261204212826_x.sql', sql }]);
62
+ return dl.decide(findings, [result], opts)[0];
63
+ };
64
+
65
+ test('décision : base neuve (cible absente) et table vide : silence', () => {
66
+ assert.strictEqual(one('drop table documents;', { exists: false }).decision, 'silent');
67
+ assert.strictEqual(one('drop table documents;', { exists: false }, { production: true }).reason, 'target_absent');
68
+ assert.strictEqual(one('alter table documents drop column fichier;', { exists: true, relkind: 'r', column: true, rows: 0 }, { production: true }).decision, 'silent');
69
+ assert.strictEqual(one('alter table documents drop column fichier;', { exists: true, relkind: 'r', column: false, rows: null }).reason, 'target_absent');
70
+ assert.strictEqual(one('drop table ft;', { exists: true, relkind: 'f', rows: null }).reason, 'foreign_table');
71
+ });
72
+
73
+ test('décision : table pleine + DROP COLUMN : avertissement avec le nombre ; production : confirmation ; acceptée', () => {
74
+ const r = { exists: true, relkind: 'r', column: true, rows: 1240 };
75
+ const w = one('alter table public.documents drop column fichier;', r);
76
+ assert.strictEqual(w.decision, 'warn');
77
+ assert.strictEqual(w.message, 'DROP COLUMN public.documents.fichier — 1,240 non-null value(s) will be lost');
78
+ assert.strictEqual(one('alter table public.documents drop column fichier;', r, { production: true }).decision, 'confirm');
79
+ assert.strictEqual(one('alter table public.documents drop column fichier;', r, { production: true, accepted: true }).decision, 'accepted');
80
+ // Comptage impossible (délai) : prudence, comme une perte
81
+ assert.strictEqual(one('truncate documents;', null, { production: true }).decision, 'confirm');
82
+ // JSON : { file, statement, target, rows, kind }
83
+ const [j] = dl.jsonOf([w]);
84
+ assert.deepStrictEqual([j.file, j.statement, j.target, j.rows, j.kind], ['20261204212826_x.sql', 'alter table public.documents drop column fichier', 'public.documents.fichier', 1240, 'drop_column']);
85
+ });
86
+
87
+ test('décision : conversions sans perte, renommages et vues hors API', () => {
88
+ assert.strictEqual(one('alter table t alter column c type text;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'character varying(20)' }).reason, 'lossless_conversion');
89
+ assert.strictEqual(one('alter table t alter column c type bigint;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'integer' }).reason, 'lossless_conversion');
90
+ assert.strictEqual(one('alter table t alter column c type integer;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'text' }, { production: true }).decision, 'confirm');
91
+ const ren = one('alter table t rename column a to b;', { exists: true, relkind: 'r', column: true, rows: 5 }, { production: true });
92
+ assert.deepStrictEqual([ren.decision, ren.loss], ['warn', false]);
93
+ assert.strictEqual(one('drop view v;', { exists: true, relkind: 'v', api: false }).reason, 'not_exposed');
94
+ assert.strictEqual(one('drop view v;', { exists: true, relkind: 'v', api: true }).decision, 'warn');
95
+ assert.strictEqual(one('drop view private.v;', { exists: true, relkind: 'v', api: true }).reason, 'not_exposed');
96
+ });
97
+
98
+ test('script psql et lecture de sa sortie ; ligne de journal sans instruction', () => {
99
+ const findings = dl.analyze([{ file: 'x.sql', sql: "alter table documents drop column fichier; delete from notes where body = 'secret';" }]);
100
+ const s = dl.script(dl.checks(findings));
101
+ assert.match(s, /^begin transaction read only;/);
102
+ assert.match(s, /statement_timeout = '3s'/);
103
+ assert.doesNotMatch(s, /secret/);
104
+ const res = dl.parseOutput('0 e {"exists":true,"relkind":"r","column":true,"rows":3}\n1 f {"exists":true,"relkind":"r","rows":7}\n', 2);
105
+ assert.strictEqual(res[0].rows, 3);
106
+ assert.deepStrictEqual([res[1].rows, res[1].approx], [7, true]);
107
+ const d = dl.decide(findings, res);
108
+ const a = dl.logAttrs(d[1]);
109
+ assert.strictEqual(a.event, 'migration_data_loss_check');
110
+ assert.strictEqual(a.target, 'public.notes');
111
+ assert.doesNotMatch(JSON.stringify(a) + dl.logMsg(d[1]), /secret|body/);
112
+ });
@@ -0,0 +1,20 @@
1
+ // poad db reset : sources « Fichier envoyé » rappelées (leur fichier est effacé avec le stockage local)
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { uploadSources } = require('../project/db/reset');
8
+
9
+ test('uploadSources : seules les sources origin.kind upload, avec leur table', () => {
10
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-reset-'));
11
+ const dir = path.join(root, 'sources');
12
+ fs.mkdirSync(dir);
13
+ fs.writeFileSync(path.join(dir, 'mesures.yaml'), 'name: mesures\nmode: imported\norigin:\n kind: upload # fichier envoyé : une nouvelle version se charge en l’envoyant de nouveau\n path: poad-sources/sources/20261204-ab/mesures.csv\n format: csv\ntable: public.mesures\nkey: [a]\n');
14
+ fs.writeFileSync(path.join(dir, 'gares.yaml'), 'name: gares\nmode: imported\norigin: { kind: upload, path: poad-sources/x/gares.csv, format: csv }\ntable: gares_fr\n');
15
+ fs.writeFileSync(path.join(dir, 'communes.yaml'), 'name: communes\norigin:\n kind: file\n url: https://example.org/c.csv\ntable: public.communes\n');
16
+ fs.writeFileSync(path.join(dir, 'notes.txt'), 'kind: upload\n');
17
+ const got = uploadSources(root).sort((a, b) => a.name.localeCompare(b.name));
18
+ assert.deepStrictEqual(got, [{ name: 'gares', table: 'gares_fr' }, { name: 'mesures', table: 'mesures' }]);
19
+ assert.deepStrictEqual(uploadSources(path.join(root, 'absent')), []);
20
+ });
@@ -0,0 +1,51 @@
1
+ // Types des fonctions déposés dans poad/functions/.poad/types (utils/function-types.js)
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const types = require('../utils/function-types');
8
+
9
+ const bundle = (text) => ({ files: { '@poadio/functions/index.d.ts': text, '@poadio/client-js/index.d.ts': 'export {};\n', '../evil.d.ts': 'x', '@poadio/x/a.js': 'x' } });
10
+ const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'poad-fntypes-'));
11
+
12
+ test('dépose les types valides seulement, et le tsconfig qui inclut @poadio/functions', () => {
13
+ const dir = tmp();
14
+ const done = types.write(dir, bundle('export declare const flowStep: () => null;\n'));
15
+ assert.deepStrictEqual(done, { count: 2, changed: true });
16
+ assert.match(fs.readFileSync(path.join(dir, '.poad/types/@poadio/functions/index.d.ts'), 'utf8'), /flowStep/);
17
+ assert.ok(!fs.existsSync(path.join(dir, '.poad/evil.d.ts')));
18
+ const tsconfig = JSON.parse(fs.readFileSync(path.join(dir, 'tsconfig.json'), 'utf8'));
19
+ assert.ok(tsconfig.include.includes('.poad/types/@poadio/functions/index.d.ts'));
20
+ fs.rmSync(dir, { recursive: true, force: true });
21
+ });
22
+
23
+ test('rien ne change si les types sont les mêmes ; des types périmés sont remplacés', () => {
24
+ const dir = tmp();
25
+ types.write(dir, bundle('export declare const caller: () => null;\n'));
26
+ assert.deepStrictEqual(types.write(dir, bundle('export declare const caller: () => null;\n')), { count: 2, changed: false });
27
+ const done = types.write(dir, bundle('export declare const caller: () => null;\nexport declare const flowStep: () => null;\n'));
28
+ assert.strictEqual(done.changed, true);
29
+ assert.match(fs.readFileSync(path.join(dir, '.poad/types/@poadio/functions/index.d.ts'), 'utf8'), /flowStep/);
30
+ fs.rmSync(dir, { recursive: true, force: true });
31
+ });
32
+
33
+ test('le tsconfig d\'un ancien CLI est mis à niveau, un tsconfig modifié à la main est gardé', () => {
34
+ const dir = tmp();
35
+ fs.writeFileSync(path.join(dir, 'tsconfig.json'), types.OLD_TSCONFIGS[0]);
36
+ types.write(dir, bundle('export {};\n'));
37
+ assert.strictEqual(fs.readFileSync(path.join(dir, 'tsconfig.json'), 'utf8'), types.TSCONFIG);
38
+ const mine = '{ "compilerOptions": { "strict": false } }\n';
39
+ fs.writeFileSync(path.join(dir, 'tsconfig.json'), mine);
40
+ types.write(dir, bundle('export {};\n'));
41
+ assert.strictEqual(fs.readFileSync(path.join(dir, 'tsconfig.json'), 'utf8'), mine);
42
+ fs.rmSync(dir, { recursive: true, force: true });
43
+ });
44
+
45
+ test('sans types servis : null, rien d\'écrit', () => {
46
+ const dir = tmp();
47
+ assert.strictEqual(types.write(dir, null), null);
48
+ assert.strictEqual(types.write(dir, { files: {} }), null);
49
+ assert.ok(!fs.existsSync(path.join(dir, 'tsconfig.json')));
50
+ fs.rmSync(dir, { recursive: true, force: true });
51
+ });