poad 2.63.0 → 2.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/project/source.js CHANGED
@@ -1,5 +1,13 @@
1
1
  // poad source ls sources du projet (poad/sources/<nom>.yaml) et leur état
2
2
  // poad source refresh <nom> [--force] synchronise une source maintenant et suit son exécution
3
+ // poad source import <fichier> [--table t] charge un fichier (CSV, JSON, GeoJSON, JSONL, gzip) dans une table :
4
+ // source « Fichier envoyé » (nouvelle, ou nouvelle version d'une source envoyée)
5
+ // poad source link <table> --host h --database d --remote schéma.table --credential c [--sslmode m] [--port p] [--columns a,b]
6
+ // table liée (mode virtual, engine 0.66.0+) : une table d'une autre base PostgreSQL
7
+ // lue à chaque requête, rien n'est copié ; colonnes proposées par l'engine
8
+ // poad source test <nom> table liée : vérifie l'adresse (garde des adresses internes), rebranche, lit une ligne
9
+ // poad source pull <nom> [--force] rapatrie la déclaration d'une source (créée dans la console
10
+ // de poad.io avec --env) dans poad/sources/<nom>.yaml
3
11
  //
4
12
  // Une source est une table du projet tenue à jour depuis une adresse (JSON,
5
13
  // GeoJSON, CSV, JSONL) : l'engine (0.64.0+, meta /meta/v1/sources) crée la
@@ -15,11 +23,35 @@
15
23
  // clé anon : jamais affichés. En local : la clé service_role du projet.
16
24
  const flows = require('./flows');
17
25
 
18
- const NAME_RE = /^[a-z][a-z0-9-]{0,55}$/; // meta, sources.ts : SOURCE_NAME_RE
26
+ const NAME_RE = /^(?:[a-z][a-z0-9-]{0,55}|[a-z_][a-z0-9_]{0,62})$/; // meta, sources.ts : SOURCE_NAME_RE (nom de table, ou d'avant 0.65.0)
27
+ /** Formats d'une source (meta : sources.ts FORMATS ; ics… lus par l'étape source-read 1.3.0, engine avec meta 1.43.0) */
28
+ const FORMATS = ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx'];
29
+
30
+ /** Ce que le lecteur d'un format a trouvé (réponse de /sources/sample) : une ligne, ou null. Pure. */
31
+ const describeReader = (sample) => {
32
+ const d = (sample && sample.details) || {};
33
+ const o = (sample && sample.options) || {};
34
+ const out = [];
35
+ if (d.sheet) out.push(`sheet "${d.sheet}"${Array.isArray(d.sheets) && d.sheets.length > 1 ? ` (of ${d.sheets.map((x) => `"${x}"`).join(', ')}; --sheet)` : ''}`);
36
+ if (d.header_row) out.push(`header on row ${d.header_row}`);
37
+ else if (o.header === false) out.push('no header row');
38
+ if (o.records) out.push(`records ${o.records}`);
39
+ if (o.expand && o.expand.until) out.push(`recurrences expanded until ${o.expand.until}`);
40
+ if (typeof d.events === 'number') out.push(`${d.events} event(s)`);
41
+ if (typeof d.placemarks === 'number') out.push(`${d.placemarks} placemark(s)`);
42
+ if (sample && sample.run_id) out.push(`read by source-read (run ${sample.run_id})`);
43
+ return out.length ? out.join(', ') : null;
44
+ };
45
+
19
46
  const POLL_MS = 1000;
20
- const TIMEOUT_MS = 15000;
47
+ const TIMEOUT_MS = 30000;
21
48
  const FINAL = ['completed', 'failed', 'cancelled'];
22
- const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach], and --env <name> | --project <id> for poad.io';
49
+ const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | import <file> [--table <table>] [--name <source>] | link <table> --host <host> --database <db> --remote <schema.table> --credential <name> | test <name> | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
50
+ const LINK_USAGE = 'Usage: poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>] [--env <name>]';
51
+ const SSLMODES = ['require', 'verify-full', 'disable'];
52
+
53
+ /** Origine d'une table liée : hôte[:port]/base · schéma.table (jamais d'identifiant). Pure. */
54
+ const linkedOrigin = (o) => (o && o.host ? `${o.host}${o.port && o.port !== 5432 ? `:${o.port}` : ''}/${o.database || ''} · ${o.schema || 'public'}.${o.table || ''}` : '');
23
55
 
24
56
  // Engine 0.64.0 et plus : sources (/meta/v1/sources), déclarées dans poad/sources
25
57
  const supportsSources = (config) => {
@@ -52,6 +84,19 @@ const sourceLines = (s, width = 0) => {
52
84
  const more = (s.problems || []).length > 1 ? ` (+${s.problems.length - 1} more)` : '';
53
85
  return [chalk.redBright(` ✖ ${name} ${s.file}`), chalk.redBright(` ${first.line ? `line ${first.line}: ` : first.path ? `${first.path}: ` : ''}${first.message || 'invalid declaration'}${more}`)];
54
86
  }
87
+ if (s.mode === 'virtual') {
88
+ // Table liée : rien n'est copié, pas d'exécution ; branchée (adresse vérifiée et user mapping posés) ou non
89
+ const attached = Boolean(s.linked && s.linked.attached) && s.table_exists !== false;
90
+ const state = attached ? `linked (${s.linked.address})` : 'not linked';
91
+ const facts = ['linked table', s.table, linkedOrigin(s.origin), state].filter(Boolean).join(' ');
92
+ const out = [` ${attached && !(s.problems && s.problems.length) ? chalk.greenBright('✔') : chalk.yellowBright('!')} ${chalk.bold(name)} ${chalk.grey(facts)}`];
93
+ if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
94
+ for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
95
+ if (s.linked && s.linked.credential_problem) out.push(chalk.yellowBright(` credential: ${s.linked.credential_problem}`));
96
+ if (s.drift && s.drift.issues) for (const issue of s.drift.issues.slice(0, 5)) out.push(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
97
+ if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
98
+ return out;
99
+ }
55
100
  const last = s.last_run;
56
101
  const failed = last && last.status === 'failed';
57
102
  const state = !last ? 'never run' : last.status === 'completed' ? `synced ${age(s.age_seconds)} ago` : last.status;
@@ -82,6 +127,7 @@ const reportLines = (r) => {
82
127
  ` ${count(r.received)} received, ${count(r.inserted)} added, ${count(r.updated)} updated, ${count(r.deleted)} removed, ${count(r.unchanged)} unchanged`,
83
128
  chalk.grey(` ${r.table || ''}: ${count(r.rows)} rows${r.forced ? ', deletion guard lifted (--force)' : ''}${typeof r.duration_ms === 'number' ? `, applied in ${flows.duration(r.duration_ms)}` : ''}`),
84
129
  ];
130
+ if (r.strategy === 'replace') out.push(chalk.grey(' full replacement (generated key without a natural key)'));
85
131
  if (typeof r.received === 'number' && typeof r.kept === 'number' && r.kept < r.received) out.push(chalk.yellowBright(` ${count(r.received - r.kept)} received row(s) left out (no key, or the same key twice)`));
86
132
  for (const p of Array.isArray(r.problems) ? r.problems : []) out.push(chalk.yellowBright(` ${p}`));
87
133
  return out;
@@ -99,6 +145,7 @@ const main = async (args = {}, raw, deps = {}) => {
99
145
  const path = require('path');
100
146
  const { findPoadDir } = require('../utils/findpoad');
101
147
  const { readConfig } = require('../utils/config');
148
+ const fs = require('fs');
102
149
  const cwd = deps.cwd || process.cwd();
103
150
  const doFetch = deps.fetch || fetch;
104
151
  const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
@@ -170,7 +217,9 @@ const main = async (args = {}, raw, deps = {}) => {
170
217
  if (res.status >= 200 && res.status < 300) return data || {};
171
218
  const error = data && typeof data === 'object' && data.error && typeof data.error === 'object' ? data.error : null;
172
219
  if (error && error.message) throw new SourceError(`${error.message}${error.hint ? ` (${error.hint})` : ''}`);
173
- if (res.status === 404) throw new SourceError(`${t.cloud ? t.label : 'The engine'} has no sources API (HTTP 404): engine 0.64.0 or later is needed.`);
220
+ // Fichier envoyé, échantillon, rapprochement : engine 0.65.0 ; le reste : 0.64.0
221
+ const needs = /\/sources\/(uploads|sample|propose|preview|tables)\b/.test(route) ? '0.65.0' : '0.64.0';
222
+ if (res.status === 404) throw new SourceError(`${t.cloud ? t.label : 'The engine'} has no ${needs === '0.65.0' ? 'such sources API' : 'sources API'} (HTTP 404): engine ${needs} or later is needed.`);
174
223
  if (res.status === 401 || res.status === 403) throw new SourceError(t.cloud ? `${t.label} refused the access (HTTP ${res.status}): "poad login" again, or check that you own the project.` : `the engine refused the service_role key (HTTP ${res.status})`);
175
224
  throw new SourceError(`HTTP ${res.status}`);
176
225
  };
@@ -185,43 +234,8 @@ const main = async (args = {}, raw, deps = {}) => {
185
234
  }
186
235
  };
187
236
 
188
- // ------------------------------------------------------------------ ls
189
- if (command === 'ls' || command === 'list') {
190
- if (words.length > 1) return fail(USAGE, 2);
191
- const t = await ready();
192
- if (!t) return;
193
- const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
194
- if (!list) return;
195
- if (json) return console.log(JSON.stringify(list.sources || [], null, 2));
196
- const all = list.sources || [];
197
- console.log(`${chalk.bold('Sources')} ${chalk.grey(cloud ? t.label : 'poad/sources')}`);
198
- console.log(' ');
199
- if (!all.length) return console.log(chalk.grey(` None yet: declare one in poad/sources/<name>.yaml${cloud ? ', then "poad deploy"' : ''}.`));
200
- const width = Math.max(...all.map((s) => String(s.name).length));
201
- for (const s of all) for (const line of sourceLines(s, width)) console.log(line);
202
- if (all.some((s) => !s.valid)) process.exitCode = 1;
203
- return;
204
- }
205
-
206
- // ------------------------------------------------------------------ refresh
207
- if (command === 'refresh' || command === 'sync') {
208
- let name = null;
209
- let force = false;
210
- let wait = true;
211
- for (const w of words.slice(1)) {
212
- if (w === '--force') force = true;
213
- else if (w === '--detach' || w === '--no-wait' || w === '-d') wait = false;
214
- else if (w === '--wait') wait = true;
215
- else if (w.startsWith('-')) return fail(`poad source refresh: unknown option ${w}.`, 2);
216
- else if (name === null) name = w;
217
- else return fail(`poad source refresh: one source at a time ("${w}").`, 2);
218
- }
219
- if (!name) return fail('Usage: poad source refresh <name> [--force] [--detach] [--env <name>] ("poad source ls" lists them).', 2);
220
- if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (poad/sources/<name>.yaml: a-z, 0-9 and "-", a letter first, 56 characters at most).`, 2);
221
- const t = await ready();
222
- if (!t) return;
223
- const started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force }));
224
- if (!started) return;
237
+ /** Suit l'exécution d'une synchronisation lancée (started : réponse de /refresh ou de la création) jusqu'au bilan */
238
+ const followRun = async (t, name, started, force, wait) => {
225
239
  const runId = started.run_id;
226
240
  if (!runId) return fail('Source not refreshed: the engine gave no run id.');
227
241
  if (!wait) {
@@ -277,10 +291,295 @@ const main = async (args = {}, raw, deps = {}) => {
277
291
  if (guardRefused(error) && !force) console.log(chalk.grey(` Nothing was changed. If the source is right: poad source refresh ${name} --force${where}`));
278
292
  console.log(chalk.grey(` Details: poad flows show ${runId}${where} · poad logs source=${name}`));
279
293
  return;
294
+ };
295
+
296
+ // ------------------------------------------------------------------ ls
297
+ if (command === 'ls' || command === 'list') {
298
+ if (words.length > 1) return fail(USAGE, 2);
299
+ const t = await ready();
300
+ if (!t) return;
301
+ const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
302
+ if (!list) return;
303
+ if (json) return console.log(JSON.stringify(list.sources || [], null, 2));
304
+ const all = list.sources || [];
305
+ console.log(`${chalk.bold('Sources')} ${chalk.grey(cloud ? t.label : 'poad/sources')}`);
306
+ console.log(' ');
307
+ if (!all.length) return console.log(chalk.grey(` None yet: declare one in poad/sources/<name>.yaml${cloud ? ', then "poad deploy"' : ''}.`));
308
+ const width = Math.max(...all.map((s) => String(s.name).length));
309
+ for (const s of all) for (const line of sourceLines(s, width)) console.log(line);
310
+ if (all.some((s) => !s.valid)) process.exitCode = 1;
311
+ return;
312
+ }
313
+
314
+ // ------------------------------------------------------------------ refresh
315
+ if (command === 'refresh' || command === 'sync') {
316
+ let name = null;
317
+ let force = false;
318
+ let wait = true;
319
+ for (const w of words.slice(1)) {
320
+ if (w === '--force') force = true;
321
+ else if (w === '--detach' || w === '--no-wait' || w === '-d') wait = false;
322
+ else if (w === '--wait') wait = true;
323
+ else if (w.startsWith('-')) return fail(`poad source refresh: unknown option ${w}.`, 2);
324
+ else if (name === null) name = w;
325
+ else return fail(`poad source refresh: one source at a time ("${w}").`, 2);
326
+ }
327
+ if (!name) return fail('Usage: poad source refresh <name> [--force] [--detach] [--env <name>] ("poad source ls" lists them).', 2);
328
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (poad/sources/<name>.yaml: a-z, 0-9 and "-", a letter first, 56 characters at most).`, 2);
329
+ const t = await ready();
330
+ if (!t) return;
331
+ const started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force }));
332
+ if (!started) return;
333
+ return followRun(t, name, started, force, wait);
334
+ }
335
+
336
+ // ------------------------------------------------------------------ import
337
+ // Un fichier (CSV, JSON, GeoJSON, JSONL, gzip accepté) chargé dans une table, par une source « Fichier envoyé » :
338
+ // envoyé dans le bucket système poad-sources, lu en flux par le flow de la source (aucune limite de taille).
339
+ // Nouvelle source : échantillon lu par l'engine, nouvelle table (ou --existing), déclaration écrite, chargement.
340
+ // Source déjà envoyée (--name, ou le nom tiré du fichier) : nouvelle version au même chemin, puis chargement.
341
+ if (command === 'import') {
342
+ const opts = { file: null, name: null, table: null, key: null, generated: null, format: null, root: null, existing: false, wait: true, options: {} };
343
+ const rest = words.slice(1);
344
+ for (let i = 0; i < rest.length; i++) {
345
+ const w = rest[i];
346
+ const value = () => {
347
+ const v = rest[++i];
348
+ if (v === undefined || v.startsWith('--')) throw new SourceError(`poad source import: ${w} needs a value.`);
349
+ return v;
350
+ };
351
+ try {
352
+ if (w === '--name') opts.name = value();
353
+ else if (w === '--table') opts.table = value().replace(/^public\./, '');
354
+ else if (w === '--key') opts.key = value().split(',').map((x) => x.trim()).filter(Boolean);
355
+ else if (w === '--key-generated') opts.generated = value();
356
+ else if (w === '--format') opts.format = value();
357
+ else if (w === '--root') opts.root = value();
358
+ // Options du lecteur des formats lus par source-read 1.3.0 (bloc origin.<format> de la déclaration)
359
+ else if (w === '--sheet') {
360
+ const v = value();
361
+ opts.options.sheet = /^\d+$/.test(v) ? Number(v) : v;
362
+ } else if (w === '--header') {
363
+ const v = value();
364
+ if (v === 'none' || v === '0' || v === 'false') opts.options.header = false;
365
+ else if (/^[1-9]\d*$/.test(v)) opts.options.header = Number(v);
366
+ else throw new SourceError(`poad source import: --header takes a row number, or none (got "${v}").`);
367
+ } else if (w === '--records') opts.options.records = value();
368
+ else if (w === '--expand-until') {
369
+ const v = value();
370
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) throw new SourceError(`poad source import: --expand-until takes a date, YYYY-MM-DD (got "${v}").`);
371
+ opts.options.expand = { until: v };
372
+ } else if (w === '--kinds') opts.options.kinds = value().split(',').map((x) => x.trim()).filter(Boolean);
373
+ else if (w === '--existing') opts.existing = true;
374
+ else if (w === '--detach' || w === '-d') opts.wait = false;
375
+ else if (w.startsWith('-')) return fail(`poad source import: unknown option ${w}.`, 2);
376
+ else if (opts.file === null) opts.file = w;
377
+ else return fail(`poad source import: one file at a time ("${w}").`, 2);
378
+ } catch (err) {
379
+ return fail(err.message, 2);
380
+ }
381
+ }
382
+ const usage =
383
+ 'Usage: poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format csv|json|geojson|jsonl|ics|xlsx|ods|xml|kml|kmz|gpx] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach] [--env <name>]';
384
+ if (!opts.file) return fail(usage, 2);
385
+ const file = path.resolve(cwd, opts.file);
386
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${opts.file}: no such file.`);
387
+ if (opts.format && !FORMATS.includes(opts.format)) return fail(`--format: ${FORMATS.join(', ')} (got "${opts.format}").`, 2);
388
+ if (opts.existing && !opts.table) return fail('--existing needs --table <table> (the table of the project to load).', 2);
389
+ if (opts.generated && !['uuid', 'identity', 'hash'].includes(opts.generated)) return fail(`--key-generated: uuid, identity or hash (got "${opts.generated}").`, 2);
390
+ if (opts.generated && (opts.key || opts.existing)) return fail('--key-generated is for a new table without a natural key: not with --key nor --existing.', 2);
391
+ const base = path.basename(file).replace(/\.gz$/i, '').replace(/\.[a-z0-9]+$/i, '');
392
+ const { cleanIdent } = require('../utils/naming');
393
+ // Nouvelle table : nom nettoyé (accents, espaces, chiffre en tête…) ; table existante : telle quelle
394
+ const table = opts.existing ? String(opts.table).replace(/^public\./, '') : cleanIdent(String(opts.table || base).replace(/^public\./, ''), 'table');
395
+ if (opts.table && !opts.existing && table !== String(opts.table).replace(/^public\./, '')) console.log(chalk.grey(` table name cleaned: "${opts.table}" → ${table}`));
396
+ const t = await ready();
397
+ if (!t) return;
398
+ const size = fs.statSync(file).size;
399
+ const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
400
+ if (!list) return;
401
+ // Le nom d'une source est celui de sa table (engine 0.65.0). --name reste accepté : une source existante de ce
402
+ // nom (même d'avant 0.65.0) reçoit une nouvelle version ; sinon il est ignoré s'il diffère de la table.
403
+ const byName = (n) => (list.sources || []).find((x) => x.name === n);
404
+ let name = table;
405
+ if (opts.name && byName(opts.name)) name = opts.name;
406
+ else if (opts.name && opts.name !== table) console.log(chalk.yellowBright(` --name ${opts.name} ignored: a source is named after its table (${table}).`));
407
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name: --table <table> (a-z, 0-9 and "_").`, 2);
408
+ const known = byName(name);
409
+ if (known && !(known.origin && known.origin.kind === 'upload')) return fail(`The source "${name}" reads an address: "poad source refresh ${name}" reloads it (or --table <another table>).`);
410
+ const target = await guard(() => call(t, 'POST', '/meta/v1/sources/uploads', known ? { source: name, size, file_name: path.basename(file) } : { file_name: path.basename(file), size, kind: 'source' }));
411
+ if (!target) return;
412
+ const { uploadImportFile, progressLine } = deps.upload || require('../utils/import-upload');
413
+ const bar = progressLine(path.basename(file));
414
+ const startedAt = Date.now();
415
+ let sent;
416
+ try {
417
+ sent = await uploadImportFile({ base: t.base, file, target, onProgress: bar.update, fetch: doFetch, auth: async () => (await fresh(t), { apikey: t.apikey, authorization: `Bearer ${t.key}` }) });
418
+ } catch (err) {
419
+ bar.done();
420
+ return fail(`Upload failed: ${(err && err.message) || err}`);
421
+ } finally {
422
+ bar.done();
423
+ }
424
+ console.log(`${chalk.greenBright('✔')} ${path.basename(file)} ${chalk.grey(`${(size / 1048576).toFixed(1)} MB sent in ${((Date.now() - startedAt) / 1000).toFixed(1)} s (${sent.method === 'tus' ? 'resumable' : 'simple'} upload) → ${target.path}`)}`);
425
+ let started;
426
+ if (known) {
427
+ // Nouvelle version : même chemin, la déclaration ne change pas
428
+ started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force: false }));
429
+ } else {
430
+ const options = Object.keys(opts.options).length ? { options: opts.options } : {};
431
+ const sample = await guard(() => call(t, 'POST', '/meta/v1/sources/sample', { path: target.path, ...(opts.format ? { format: opts.format } : {}), ...(opts.root ? { root: opts.root } : {}), ...options }));
432
+ if (!sample) return;
433
+ console.log(chalk.grey(` ${sample.format}${sample.gzip ? ' (gzip)' : ''}, ${(sample.fields || []).length} field(s): ${(sample.fields || []).map((f) => `${f.path} ${f.type}`).slice(0, 12).join(', ')}${(sample.fields || []).length > 12 ? '…' : ''}`));
434
+ // Formats lus par source-read : ce que le lecteur a choisi (feuille, ligne d'en-tête, enregistrements)
435
+ const found = describeReader(sample);
436
+ if (found) console.log(chalk.grey(` ${found}`));
437
+ const proposal = await guard(() => call(t, 'POST', '/meta/v1/sources/propose', { fields: sample.fields, format: sample.format, path: target.path, table, ...(opts.existing ? { existing: true, name } : {}) }));
438
+ if (!proposal) return;
439
+ let columns;
440
+ let key;
441
+ if (opts.existing) {
442
+ const blocking = (proposal.problems || []).filter((p) => p.level === 'error');
443
+ if (blocking.length) return fail(`public.${table} cannot take this file: ${blocking.map((p) => p.message).join(' ; ')}`);
444
+ columns = (proposal.matches || []).filter((m) => m.field).map((m) => ({ name: m.column, from: m.field, ...(m.transform ? { transform: m.transform } : {}) }));
445
+ key = opts.key || proposal.key || [];
446
+ } else {
447
+ if (proposal.table_exists) return fail(`public.${table} already exists: --table <another name>, or --existing to load into it.`);
448
+ columns = (proposal.columns || []).filter((c) => c.include !== false).map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) }));
449
+ key = opts.key || proposal.key || [];
450
+ }
451
+ // Clé générée par poad (nouvelle table sans clé naturelle) : colonne id ajoutée en tête
452
+ if (opts.generated) key = { generated: opts.generated };
453
+ else if (!key.length) return fail(`No key found for public.${table}: --key <column> (a column whose values are unique), or --key-generated uuid|identity|hash (an id column added by poad).`, 2);
454
+ const draft = {
455
+ mode: 'imported',
456
+ origin: { kind: 'upload', path: target.path, format: sample.format, ...(sample.root ? { root: sample.root } : {}), ...(sample.format === 'csv' && sample.csv ? { csv: { delimiter: sample.csv.delimiter, ...(sample.csv.encoding ? { encoding: sample.csv.encoding } : {}) } } : {}), ...(sample.options && Object.keys(sample.options).length ? { options: sample.options } : {}) },
457
+ table: `public.${table}`,
458
+ existing: opts.existing,
459
+ key,
460
+ columns,
461
+ };
462
+ const created = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft, run: true, ...(opts.existing ? { confirm: { existing: true } } : {}) }));
463
+ if (!created) return;
464
+ if (created.name) name = created.name;
465
+ for (const w of created.warnings || []) console.log(chalk.yellowBright(` ${w}`));
466
+ const keyText = Array.isArray(key) ? `key ${key.join(', ')}` : `generated key ${key.generated}`;
467
+ console.log(`${chalk.greenBright('✔')} source ${chalk.bold(name)} ${chalk.grey(`${created.file || 'created in the console'} → public.${table}, ${keyText}`)}`);
468
+ if (opts.generated === 'uuid' || opts.generated === 'identity') console.log(chalk.grey(' No natural key: each new version replaces the whole table content (one transaction), under the deletion guard.'));
469
+ started = created.run_id ? { run_id: created.run_id, flow: `source-${name.replace(/_/g, '-')}` } : null;
470
+ if (!started) return fail('The source was declared but no load was started: poad source refresh ' + name + where);
471
+ }
472
+ if (!started) return;
473
+ return followRun(t, name, started, false, opts.wait);
474
+ }
475
+
476
+ // ------------------------------------------------------------------ test
477
+ // Table liée : meta refait la garde des adresses, rebranche (adresse vérifiée, user mapping depuis le coffre) et lit une ligne
478
+ if (command === 'test') {
479
+ const name = words[1];
480
+ if (!name || words.length > 2) return fail('Usage: poad source test <name> [--env <name>] (a linked table: "poad source ls" lists them).', 2);
481
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
482
+ const t = await ready();
483
+ if (!t) return;
484
+ const r = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/test`, {}));
485
+ if (!r) return;
486
+ if (json) return console.log(JSON.stringify(r, null, 2));
487
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote table answers${typeof r.duration_ms === 'number' ? ` (${Math.round(r.duration_ms)} ms)` : ''}${r.address ? `, checked address ${r.address}` : ''}`)}`);
488
+ return;
489
+ }
490
+
491
+ // ------------------------------------------------------------------ link
492
+ // Table liée : l'engine se connecte en lecture seule (garde des adresses internes), propose les colonnes de la table
493
+ // distante, puis écrit la déclaration (poad/sources/<table>.yaml) et la migration de la table étrangère. Le credential
494
+ // (utilisateur et mot de passe) est déjà dans le coffre : poad credential, ou l'écran Credentials ; jamais ici.
495
+ if (command === 'link') {
496
+ const o = { table: null, host: null, port: null, database: null, remote: null, credential: null, sslmode: 'require', columns: null, title: null };
497
+ const rest = words.slice(1);
498
+ for (let i = 0; i < rest.length; i++) {
499
+ const w = rest[i];
500
+ const flag = { '--host': 'host', '--port': 'port', '--database': 'database', '--db': 'database', '--remote': 'remote', '--credential': 'credential', '--sslmode': 'sslmode', '--columns': 'columns', '--title': 'title' }[w];
501
+ if (flag) {
502
+ const v = rest[++i];
503
+ if (v === undefined || v.startsWith('--')) return fail(`poad source link: ${w} needs a value.`, 2);
504
+ o[flag] = v;
505
+ } else if (w.startsWith('-')) return fail(`poad source link: unknown option ${w}.\n${LINK_USAGE}`, 2);
506
+ else if (o.table === null) o.table = w.replace(/^public\./, '');
507
+ else return fail(`poad source link: one table at a time ("${w}").`, 2);
508
+ }
509
+ if (!o.table || !o.host || !o.database || !o.remote || !o.credential) return fail(LINK_USAGE, 2);
510
+ if (!/^[a-z_][a-z0-9_]{0,62}$/.test(o.table)) return fail(`"${o.table}" is not a table name (a-z, 0-9 and "_", a letter or "_" first).`, 2);
511
+ if (!SSLMODES.includes(o.sslmode)) return fail(`--sslmode: ${SSLMODES.join(', ')}.`, 2);
512
+ const port = o.port === null ? undefined : Number(o.port);
513
+ if (port !== undefined && !(Number.isInteger(port) && port >= 1 && port <= 65535)) return fail('--port: 1 to 65535.', 2);
514
+ const dot = o.remote.indexOf('.');
515
+ const remote = dot > 0 ? { schema: o.remote.slice(0, dot), table: o.remote.slice(dot + 1) } : { schema: 'public', table: o.remote };
516
+ const t = await ready();
517
+ if (!t) return;
518
+ const conn = { host: o.host, ...(port ? { port } : {}), database: o.database, credential: o.credential, sslmode: o.sslmode, name: o.table };
519
+ const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/linked/inspect', { ...conn, ...remote }));
520
+ if (!seen) return;
521
+ let columns = Array.isArray(seen.columns) ? seen.columns : [];
522
+ if (o.columns) {
523
+ const wanted = o.columns.split(',').map((x) => x.trim()).filter(Boolean);
524
+ const unknown = wanted.filter((w) => !columns.some((c) => c.from === w || c.name === w));
525
+ if (unknown.length) return fail(`${remote.schema}.${remote.table} has no column ${unknown.map((u) => `"${u}"`).join(', ')} (it has: ${columns.map((c) => c.from).join(', ')}).`);
526
+ columns = columns.filter((c) => wanted.includes(c.from) || wanted.includes(c.name));
527
+ }
528
+ if (!columns.length) return fail(`${remote.schema}.${remote.table}: no column to link.`);
529
+ const key = (seen.key || []).filter((k) => columns.some((c) => c.name === k));
530
+ const draft = {
531
+ table: `public.${o.table}`,
532
+ ...(o.title ? { title: o.title } : {}),
533
+ mode: 'virtual',
534
+ origin: { kind: 'postgres', host: o.host, ...(port ? { port } : {}), database: o.database, schema: remote.schema, table: remote.table, credential: o.credential, sslmode: o.sslmode },
535
+ columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type })),
536
+ ...(key.length ? { key } : {}),
537
+ };
538
+ const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft }));
539
+ if (!saved) return;
540
+ if (json) return console.log(JSON.stringify(saved, null, 2));
541
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(saved.name || o.table)} ${chalk.grey(`public.${o.table} → ${linkedOrigin(draft.origin)}, ${columns.length} column${columns.length > 1 ? 's' : ''}, nothing copied`)}`);
542
+ if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
543
+ for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
544
+ console.log(chalk.grey(` Private: never served by the API. Read it in SQL, through a security_invoker view or a function. "poad source test ${saved.name || o.table}" checks it.`));
545
+ return;
546
+ }
547
+
548
+ // ------------------------------------------------------------------ pull
549
+ // La déclaration d'une source (créée dans la console hébergée, gardée en base) écrite dans poad/sources :
550
+ // le fichier fait foi ensuite (poad deploy l'envoie ; sur poad.io, un fichier déployé l'emporte).
551
+ if (command === 'pull') {
552
+ let name = null;
553
+ let force = false;
554
+ let toStdout = false;
555
+ for (const w of words.slice(1)) {
556
+ if (w === '--force' || w === '-f') force = true;
557
+ else if (w === '--stdout') toStdout = true;
558
+ else if (w.startsWith('-')) return fail(`poad source pull: unknown option ${w}.`, 2);
559
+ else if (name === null) name = w;
560
+ else return fail(`poad source pull: one source at a time ("${w}").`, 2);
561
+ }
562
+ if (!name) return fail('Usage: poad source pull <name> [--force] [--stdout] --env <name> ("poad source ls --env <name>" lists them).', 2);
563
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (the name of its table: a-z, 0-9 and "_"; or, before engine 0.65.0, a-z, 0-9 and "-").`, 2);
564
+ if (!root && !toStdout) return fail('Not in a poad project folder: cd into one, or pass --stdout.');
565
+ const target = root ? path.join(path.dirname(root), 'sources', `${name}.yaml`) : null;
566
+ if (target && !toStdout && !force && (fs.existsSync(target) || fs.existsSync(target.replace(/\.yaml$/, '.yml'))))
567
+ return fail(`poad/sources/${name}.yaml already exists: --force replaces it (check "git diff" afterwards), or --stdout prints the declaration.`);
568
+ const t = await ready();
569
+ if (!t) return;
570
+ const got = await guard(() => call(t, 'GET', `/meta/v1/sources/${encodeURIComponent(name)}/yaml`));
571
+ if (!got) return;
572
+ if (typeof got.yaml !== 'string' || !got.yaml.trim()) return fail('The engine gave no declaration.');
573
+ if (toStdout) return process.stdout.write(got.yaml.endsWith('\n') ? got.yaml : `${got.yaml}\n`);
574
+ fs.mkdirSync(path.dirname(target), { recursive: true });
575
+ fs.writeFileSync(target, got.yaml.endsWith('\n') ? got.yaml : `${got.yaml}\n`);
576
+ console.log(`${chalk.greenBright('✔')} poad/sources/${name}.yaml ${chalk.grey(`from ${cloud ? t.label : 'the local engine'}${got.stored === 'console' ? ', created in the console' : ''}`)}`);
577
+ if (got.stored === 'console' && cloud) console.log(chalk.grey(` Commit it, then "poad deploy${where}": the deployed file then wins over the console copy.`));
578
+ return;
280
579
  }
281
580
 
282
581
  fail(USAGE, 2);
283
582
  };
284
583
 
285
584
  module.exports = (args, raw) => main(args, raw);
286
- Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, NAME_RE });
585
+ Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, linkedOrigin, NAME_RE, FORMATS, describeReader });
@@ -29,9 +29,11 @@ async function copy({ opts, positionals, out, move, deps = {} }) {
29
29
  const concurrency = s.concurrency(opts.concurrency);
30
30
  const api = s.client(await (deps.target || s.target)(opts));
31
31
  const { items } = await c.plan(api, positionals[0], positionals[1], { recursive: opts.recursive, remoteOnly: move });
32
+ // Gros fichiers : en morceaux reprenables (storage 0.6.0+) ; une reprise est dite
33
+ for (const it of items) it.onResume = (offset) => out.log(chalk.grey(` ↻ ${c.label(it.from)}: resuming at ${s.size(offset)} of ${s.size(it.size)}`));
32
34
  const r = await c.run(api, items, {
33
35
  concurrency,
34
- onDone: (it) => out.log(` ${chalk.greenBright('✔')} ${c.label(it.from)} ${chalk.grey('→')} ${c.label(it.to)} ${chalk.grey(s.size(it.size))}`),
36
+ onDone: (it) => out.log(` ${chalk.greenBright('✔')} ${c.label(it.from)} ${chalk.grey('→')} ${c.label(it.to)} ${chalk.grey(`${s.size(it.size)}${it.chunked ? ', in chunks' : ''}${it.resumedFrom ? `, resumed at ${s.size(it.resumedFrom)}` : ''}`)}`),
35
37
  onError: (it, e) => out.log(chalk.redBright(` ✖ ${c.label(it.from)} → ${c.label(it.to)}: ${s.reason(e)}`)),
36
38
  });
37
39
  let deleted = [];
@@ -54,7 +56,7 @@ async function copy({ opts, positionals, out, move, deps = {} }) {
54
56
  ),
55
57
  );
56
58
  printFailures(out, failures);
57
- const row = (it) => ({ from: c.label(it.from), to: c.label(it.to), size: it.size });
59
+ const row = (it) => ({ from: c.label(it.from), to: c.label(it.to), size: it.size, ...(it.chunked ? { chunked: true } : {}), ...(it.resumedFrom ? { resumed_from: it.resumedFrom } : {}) });
58
60
  out.result({
59
61
  [move ? 'moved' : 'copied']: r.done.map(row),
60
62
  unchanged: r.unchanged.map(row),
@@ -143,6 +143,16 @@ module.exports = async (args = {}) => {
143
143
  process.exitCode = 1;
144
144
  return;
145
145
  }
146
+ // Ce que l'API de la nouvelle version ne servira plus à anon ni à authenticated (lu dans la base, si elle tourne)
147
+ if (await isDockerExist(config.project_uuid)) {
148
+ const exposure = require('../utils/api-exposure');
149
+ const found = exposure.readLocal(config.project_uuid);
150
+ if (found) {
151
+ const lines = exposure.lines(exposure.impact({ current, target, items: found.items }), chalk);
152
+ for (const l of lines) console.log(l);
153
+ if (lines.length) console.log(' ');
154
+ }
155
+ }
146
156
  if (!(await confirm(`Upgrade to engine ${target}?`))) return;
147
157
  const running = await stopProject();
148
158
  await startProject(running, { upgrade: true, allowMinor: true, target });
@@ -0,0 +1,60 @@
1
+ // Ce que l'API ne sert pas à anon ni à authenticated (SECURITY DEFINER, vues sans security_invoker, vues
2
+ // matérialisées) : poad deploy (réponse de poad.io) et poad upgrade (base locale)
3
+ const test = require('node:test');
4
+ const assert = require('node:assert/strict');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const exposure = require('../utils/api-exposure');
8
+ const { summarize } = require('../project/deploy');
9
+
10
+ const chalk = new Proxy({}, { get: () => new Proxy((s) => s, { get: (_, __) => (s) => s }) });
11
+ const definer = { kind: 'function', schema: 'public', name: 'est_admin', signature: 'est_admin(uuid)', reason: 'security_definer', anon: true, authenticated: true };
12
+ const view = { kind: 'view', schema: 'public', name: 'stats', reason: 'view_owner_rights', anon: false, authenticated: true };
13
+
14
+ test('phases : servies avant 0.64.0, refusées à tous jusqu’à 0.65.x, service_role seulement depuis 0.66.0', () => {
15
+ assert.equal(exposure.phaseOf('0.62.0'), 'served');
16
+ assert.equal(exposure.phaseOf('0.64.0'), 'refused_all');
17
+ assert.equal(exposure.phaseOf('0.65.9'), 'refused_all');
18
+ assert.equal(exposure.phaseOf('0.66.0'), 'service_role_only');
19
+ assert.equal(exposure.phaseOf('?'), null);
20
+ assert.equal(exposure.phaseOf('0.66.0-rpc'), 'service_role_only');
21
+ assert.equal(exposure.impact({ current: '0.65.0', target: '0.66.0-rpc', items: [definer] }).change, 'regained_service_role');
22
+ });
23
+
24
+ test('poad upgrade 0.62 → 0.66 : perdues pour anon et authenticated, correctif par objet', () => {
25
+ const x = exposure.impact({ current: '0.62.0', target: '0.66.0', items: [definer, view] });
26
+ assert.equal(x.change, 'lost');
27
+ assert.deepEqual(x.items[1].roles, ['authenticated']);
28
+ assert.equal(x.items[1].fix, 'alter view public.stats set (security_invoker = true);');
29
+ const out = exposure.lines(x, chalk).join('\n');
30
+ assert.match(out, /With engine 0\.66\.0, the API no longer serves 2 function\(s\) or view\(s\) to anon or authenticated/);
31
+ assert.match(out, /alter function est_admin\(uuid\) security invoker;/);
32
+ assert.match(out, /public\.stats .*authenticated/);
33
+ });
34
+
35
+ test('0.65 → 0.66 : rien de perdu, service_role les reçoit de nouveau ; rien à dire sans objet', () => {
36
+ assert.equal(exposure.impact({ current: '0.65.0', target: '0.66.0', items: [definer] }).change, 'regained_service_role');
37
+ assert.deepEqual(exposure.lines(exposure.impact({ current: '0.62.0', target: '0.66.0', items: [] }), chalk), []);
38
+ });
39
+
40
+ test('poad deploy : l’avertissement de poad.io relu, décision du serveur gardée, objets des migrations en attente', () => {
41
+ const r = summarize({
42
+ outcome: 'success',
43
+ dry_run: true,
44
+ api_exposure: { current: '0.66.0', target: '0.66.0', change: 'unchanged', items: [{ kind: 'function', schema: 'public', name: 'nouvelle', reason: 'security_definer', roles: ['anon', 'authenticated'], source: 'pending_migration', file: '20261202000000_x.sql' }] },
45
+ });
46
+ assert.equal(r.api_exposure.change, 'unchanged');
47
+ assert.equal(r.api_exposure.count, 1);
48
+ const out = exposure.lines(r.api_exposure, chalk).join('\n');
49
+ assert.match(out, /refused to anon and authenticated/);
50
+ assert.match(out, /created by 20261202000000_x\.sql/);
51
+ assert.equal(summarize({ outcome: 'success' }).api_exposure, null);
52
+ });
53
+
54
+ test('la requête est la même que celle de poad.io (api-exposure.sql)', () => {
55
+ const sql = fs.readFileSync(path.join(__dirname, '../utils/api-exposure/api-exposure.sql'), 'utf8');
56
+ assert.match(sql, /set default_transaction_read_only = on/);
57
+ assert.match(sql, /p\.prosecdef/);
58
+ assert.match(sql, /security_invoker=true/);
59
+ assert.match(sql, /c\.relkind = 'm'/);
60
+ });