poad 2.70.0 → 2.72.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
@@ -30,7 +30,7 @@ const flows = require('./flows');
30
30
 
31
31
  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)
32
32
  /** Formats d'une source (meta : sources.ts FORMATS ; ics… lus par l'étape source-read 1.3.0, engine avec meta 1.43.0) */
33
- const FORMATS = ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx'];
33
+ const FORMATS = ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'topojson', 'shapefile', 'gpkg', 'fgb', 'parquet'];
34
34
 
35
35
  /** Ce que le lecteur d'un format a trouvé (réponse de /sources/sample) : une ligne, ou null. Pure. */
36
36
  const describeReader = (sample) => {
@@ -51,11 +51,18 @@ const describeReader = (sample) => {
51
51
  const POLL_MS = 1000;
52
52
  const TIMEOUT_MS = 30000;
53
53
  const FINAL = ['completed', 'failed', 'cancelled'];
54
- 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> | link <table> --url <https://…> | --storage <bucket>/<path> | test <name> | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
55
- 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>]\n or: poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>] [--env <name>]';
54
+ const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | expose <name> [--read tous|connectes|personne] [--roles authenticated,anon] [--filter <sql>] [--rate 30/min] [--max-rows 100] | unexpose <name> | relate <name> <column> <schema.table.column> [--name <relation>] | unrelate <name> <column> | retain <name> <90d|off> [--column <date column>] | import <file> [--table <table>] [--name <source>] | link <table> --host <host> --database <db> --remote <schema.table> --credential <name> | link <table> --url <https://…> | --storage <bucket>/<path> | test <name> | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
55
+ 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,…>] [--read tous|connectes|personne] [--env <name>]\n or: poad source link <table> --mysql --host <host> --database <db> --remote <table> --credential <name> [--port <port>] [--sslmode require|disable] [--columns <col,…>] [--read tous|connectes|personne] [--env <name>]\n or: poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet|topojson|ics|xlsx|ods|xml|kml|kmz|gpx|shapefile|gpkg|fgb] [--sheet <name|n>] [--layer <name>] [--records <path>] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>] [--read tous|connectes|personne] [--env <name>]';
56
+ /** Qui peut lire une table distante ou liée (engine 0.70.0), comme le GRANT d'une vue */
57
+ const LECTURES = ['tous', 'connectes', 'personne'];
58
+ const LECTURE_ALIASES = { tous: 'tous', all: 'tous', everyone: 'tous', public: 'tous', anon: 'tous', connectes: 'connectes', 'connectés': 'connectes', authenticated: 'connectes', users: 'connectes', personne: 'personne', none: 'personne', nobody: 'personne', private: 'personne' };
59
+ /** --read / --lecture → tous | connectes | personne ; null si illisible. Pure. */
60
+ const parseLecture = (v) => LECTURE_ALIASES[String(v || '').trim().toLowerCase()] || null;
61
+ const LECTURE_TEXT = { tous: 'everyone (anon and signed-in users)', connectes: 'signed-in users', personne: 'nobody (not served by the API)' };
56
62
  const SSLMODES = ['require', 'verify-full', 'disable'];
57
63
  /** Formats d'une table distante sur fichier (meta, engine 0.67.0 : lus par DuckDB ; 0.68.0 : par poad-files) */
58
- const REMOTE_FORMATS = ['csv', 'json', 'jsonl', 'geojson', 'parquet'];
64
+ // Engine 0.69.0 : tous les formats de poad-files se lisent aussi en table distante (détectés : --format pour surcharger)
65
+ const REMOTE_FORMATS = ['csv', 'json', 'jsonl', 'geojson', 'parquet', 'topojson', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'shapefile', 'gpkg', 'fgb'];
59
66
  const REMOTE_ENCODINGS = ['utf-8', 'latin-1', 'iso-8859-1', 'windows-1252', 'utf-16'];
60
67
  const BUCKET_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
61
68
 
@@ -86,11 +93,12 @@ const parseStorageRef = (raw) => {
86
93
 
87
94
  /**
88
95
  * Options de « poad source link » : table liée (--host…) ou table distante sur fichier (--url / --storage).
89
- * Rend { ok: false, message } ou { ok: true, kind: 'postgres' | 'file', o }. Pure.
96
+ * --mysql (engine 0.70) : table liée MySQL (--remote = la table, la base tient lieu de schéma ; pas de verify-full,
97
+ * la connexion passe par le relais de la sortie). Rend { ok: false, message } ou { ok: true, kind: 'postgres' | 'mysql' | 'file', o }. Pure.
90
98
  */
91
99
  const parseLinkArgs = (words) => {
92
- const o = { table: null, host: null, port: null, database: null, remote: null, credential: null, sslmode: null, columns: null, title: null, url: null, storage: null, format: null, delimiter: null, header: null, encoding: null, root: null };
93
- const valued = { '--host': 'host', '--port': 'port', '--database': 'database', '--db': 'database', '--remote': 'remote', '--credential': 'credential', '--sslmode': 'sslmode', '--columns': 'columns', '--title': 'title', '--url': 'url', '--storage': 'storage', '--format': 'format', '--delimiter': 'delimiter', '--encoding': 'encoding', '--root': 'root' };
100
+ const o = { mysql: false, table: null, host: null, port: null, database: null, remote: null, credential: null, sslmode: null, columns: null, title: null, url: null, storage: null, format: null, delimiter: null, header: null, encoding: null, root: null, sheet: null, layer: null, records: null, lecture: null };
101
+ const valued = { '--read': 'lecture', '--lecture': 'lecture', '--host': 'host', '--port': 'port', '--database': 'database', '--db': 'database', '--remote': 'remote', '--credential': 'credential', '--sslmode': 'sslmode', '--columns': 'columns', '--title': 'title', '--url': 'url', '--storage': 'storage', '--format': 'format', '--delimiter': 'delimiter', '--encoding': 'encoding', '--root': 'root', '--sheet': 'sheet', '--layer': 'layer', '--records': 'records' };
94
102
  for (let i = 0; i < words.length; i++) {
95
103
  const w = words[i];
96
104
  const flag = valued[w];
@@ -100,6 +108,7 @@ const parseLinkArgs = (words) => {
100
108
  o[flag] = v;
101
109
  } else if (w === '--no-header') o.header = false;
102
110
  else if (w === '--header') o.header = true;
111
+ else if (w === '--mysql') o.mysql = true;
103
112
  else if (w === '--yes' || w === '-y') continue;
104
113
  else if (w.startsWith('-')) return { ok: false, message: `poad source link: unknown option ${w}.\n${LINK_USAGE}`, usage: true };
105
114
  else if (o.table === null) o.table = w.replace(/^public\./, '');
@@ -107,6 +116,11 @@ const parseLinkArgs = (words) => {
107
116
  }
108
117
  const file = o.url !== null || o.storage !== null;
109
118
  if (!o.table) return { ok: false, message: LINK_USAGE, usage: true };
119
+ if (o.lecture !== null) {
120
+ const l = parseLecture(o.lecture);
121
+ if (!l) return { ok: false, message: `--read: ${LECTURES.join(', ')} (who can read the table through the API, like the GRANT of a view).` };
122
+ o.lecture = l;
123
+ }
110
124
  if (!/^[a-z_][a-z0-9_]{0,62}$/.test(o.table)) return { ok: false, message: `"${o.table}" is not a table name (a-z, 0-9 and "_", a letter or "_" first).` };
111
125
  if (!file) {
112
126
  for (const k of ['format', 'delimiter', 'encoding', 'root']) if (o[k] !== null) return { ok: false, message: `--${k} is for a file (--url or --storage).` };
@@ -115,8 +129,14 @@ const parseLinkArgs = (words) => {
115
129
  o.sslmode = o.sslmode || 'require';
116
130
  if (!SSLMODES.includes(o.sslmode)) return { ok: false, message: `--sslmode: ${SSLMODES.join(', ')}.` };
117
131
  if (o.port !== null && !(Number.isInteger(Number(o.port)) && Number(o.port) >= 1 && Number(o.port) <= 65535)) return { ok: false, message: '--port: 1 to 65535.' };
132
+ if (o.mysql) {
133
+ if (o.sslmode === 'verify-full') return { ok: false, message: '--sslmode verify-full: not for MySQL (it goes through the egress relay, the certificate name cannot be checked): require or disable.' };
134
+ if (o.remote.includes('.')) return { ok: false, message: '--remote: the MySQL table name only (the database is --database).' };
135
+ return { ok: true, kind: 'mysql', o };
136
+ }
118
137
  return { ok: true, kind: 'postgres', o };
119
138
  }
139
+ if (o.mysql) return { ok: false, message: '--mysql is for a linked MySQL table (--host…), not a file.' };
120
140
  if (o.url !== null && o.storage !== null) return { ok: false, message: 'poad source link: --url or --storage, not both.' };
121
141
  for (const k of ['host', 'port', 'database', 'remote', 'credential', 'sslmode']) if (o[k] !== null) return { ok: false, message: `--${k} is for a linked PostgreSQL table, not a file (--url or --storage).` };
122
142
  if (o.url !== null) {
@@ -142,23 +162,104 @@ const parseLinkArgs = (words) => {
142
162
  return { ok: true, kind: 'file', o };
143
163
  };
144
164
 
165
+ const API_ROLES = ['anon', 'authenticated', 'service_role'];
166
+ const RATE_RE = /^\d{1,6}\/(s|min|h|j|jour|d|day)$/;
167
+ const RETAIN_RE = /^\d{1,5}\s*(d|j|jours?|days?|sem|w|weeks?|mois|m|ans?|y|h)$/i;
168
+ const TARGET_RE = /^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}\.[a-z_][a-z0-9_]{0,62}$/;
169
+
170
+ /**
171
+ * Options de poad source expose (engine 0.69.0) : --roles, --filter (ou --filtre), --rate (ou --debit), --max-rows
172
+ * (ou --pagination). Rend le corps de PUT /meta/v1/sources/<nom>/api. Pure.
173
+ */
174
+ const parseExposeArgs = (words) => {
175
+ const o = { name: null, lecture: null, roles: null, filtre: undefined, debit: null, pagination: null };
176
+ const valued = { '--read': 'lecture', '--lecture': 'lecture', '--roles': 'roles', '--role': 'roles', '--filter': 'filtre', '--filtre': 'filtre', '--rate': 'debit', '--debit': 'debit', '--max-rows': 'pagination', '--pagination': 'pagination' };
177
+ for (let i = 0; i < words.length; i++) {
178
+ const w = words[i];
179
+ const k = valued[w];
180
+ if (k) {
181
+ const v = words[++i];
182
+ if (v === undefined) return { ok: false, message: `poad source expose: ${w} needs a value.` };
183
+ o[k] = v;
184
+ } else if (w === '--no-filter') o.filtre = null;
185
+ else if (w.startsWith('-')) return { ok: false, message: `poad source expose: unknown option ${w}.` };
186
+ else if (o.name === null) o.name = w;
187
+ else return { ok: false, message: `poad source expose: one source at a time ("${w}").` };
188
+ }
189
+ if (!o.name) return { ok: false, message: 'Usage: poad source expose <name> [--read tous|connectes|personne] [--filter "owner_email = auth.email()"] [--rate 30/min] [--max-rows 100]' };
190
+ if (!NAME_RE.test(o.name)) return { ok: false, message: `"${o.name}" is not a source name.` };
191
+ // Engine 0.70.0 : --read dit qui lit (tous, connectes, personne) ; --roles reste pour les rôles écrits à la main
192
+ if (o.lecture !== null && o.roles !== null) return { ok: false, message: 'poad source expose: --read or --roles, not both.' };
193
+ const body = o.lecture !== null ? {} : { expose: true };
194
+ if (o.lecture !== null) {
195
+ const l = parseLecture(o.lecture);
196
+ if (!l) return { ok: false, message: `--read: ${LECTURES.join(', ')}.` };
197
+ body.lecture = l;
198
+ }
199
+ if (o.roles !== null) {
200
+ const roles = o.roles.split(',').map((x) => x.trim()).filter(Boolean);
201
+ if (!roles.length || roles.some((r) => !API_ROLES.includes(r))) return { ok: false, message: `--roles: a list among ${API_ROLES.join(', ')} (anon: readable without an account, only if you mean it).` };
202
+ body.roles = [...new Set(roles)];
203
+ }
204
+ if (o.filtre !== undefined) body.filtre = o.filtre === null || !o.filtre.trim() ? null : o.filtre;
205
+ if (o.debit !== null) {
206
+ if (!RATE_RE.test(o.debit.replace(/\s+/g, ''))) return { ok: false, message: '--rate: calls per unit, like 30/min, 5/s, 1000/h, 10000/jour.' };
207
+ body.debit = o.debit.replace(/\s+/g, '');
208
+ }
209
+ if (o.pagination !== null) {
210
+ const n = Number(o.pagination);
211
+ if (!Number.isInteger(n) || n < 1 || n > 10000) return { ok: false, message: '--max-rows: 1 to 10000 rows per call.' };
212
+ body.pagination = n;
213
+ }
214
+ return { ok: true, name: o.name, body };
215
+ };
216
+
217
+ /** Ligne « api » d'une source dans poad source ls. Pure. */
218
+ const apiFacts = (s) => {
219
+ const e = s.exposure;
220
+ const out = [];
221
+ if (e) {
222
+ const who = e.lecture && e.lecture !== 'custom' ? `read: ${e.lecture}${e.implicit ? ' (default)' : ''}${e.legacy_private ? ' (private in 0.69, kept private)' : ''}` : null;
223
+ if (!e.expose) out.push(`${who || 'read: personne'}, not served (poad source expose ${s.name} --read tous|connectes)`);
224
+ else out.push(`${who ? `${who}, ` : ''}api: ${e.served ? 'served' : 'NOT served yet'} to ${e.roles.join(', ')}${e.filter ? ', filter' : ''}, ${e.rate}, ${e.pagination} rows per call${e.timeout ? `, timeout ${e.timeout}${e.timeout_default ? ' (default)' : ''}` : ''}`);
225
+ }
226
+ for (const r of s.relations || []) out.push(`relation: ${r.column} → ${r.target}${r.name ? ` (${r.name})` : ''}${r.active ? '' : ' (not active)'}`);
227
+ if (s.conservation) out.push(`kept: ${s.conservation.text}${s.conservation.column ? ` (by ${s.conservation.column})` : ' after the last sync'}${s.conservation.last_purge_at ? `, last purge ${s.conservation.last_purge_at.replace('T', ' ').slice(0, 16)} UTC (${s.conservation.last_purge_rows} rows)` : ''}`);
228
+ if (s.mode === 'virtual' && s.last_read_at) out.push(`last read ${s.last_read_at.replace('T', ' ').slice(0, 16)} UTC`);
229
+ return out;
230
+ };
231
+
145
232
  /** Brouillon d'une table distante sur fichier (POST /sources) : jamais de credential ni d'en-tête. Pure. */
146
233
  const remoteDraft = (o, inspected, columns, key) => {
147
234
  const format = o.format || inspected.format;
148
235
  const csv = format === 'csv' ? { ...(inspected.csv || {}), ...(o.delimiter !== null ? { delimiter: o.delimiter === 'tab' ? '\\t' : o.delimiter } : {}), ...(o.header !== null ? { header: o.header } : {}), ...(o.encoding !== null ? { encoding: o.encoding.toLowerCase() } : {}) } : null;
149
236
  const root = format === 'json' ? (o.root || inspected.root || null) : null;
237
+ // Options du format (feuille, couche, chemin des enregistrements) : trouvées par l'engine, ou données
238
+ const options = { ...(inspected.options || {}), ...readerOptions(o) };
150
239
  return {
151
240
  table: `public.${o.table}`,
152
241
  ...(o.title ? { title: o.title } : {}),
153
242
  mode: 'virtual',
154
- origin: { kind: 'file', ...(o.storage ? { storage: o.storage } : { url: o.url }), format, ...(root ? { root } : {}), ...(csv && Object.keys(csv).length ? { csv } : {}) },
243
+ origin: { kind: 'file', ...(o.storage ? { storage: o.storage } : { url: o.url }), format, ...(root ? { root } : {}), ...(csv && Object.keys(csv).length ? { csv } : {}), ...(Object.keys(options).length ? { options } : {}) },
155
244
  columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) })),
156
245
  ...(key && key.length ? { key } : {}),
157
246
  };
158
247
  };
159
248
 
249
+ /** Options du lecteur données en ligne de commande (--sheet, --layer, --records). Pure. */
250
+ const readerOptions = (o) => ({
251
+ ...(o.sheet ? { sheet: /^\d+$/.test(o.sheet) ? Number(o.sheet) : o.sheet } : {}),
252
+ ...(o.layer ? { layer: o.layer } : {}),
253
+ ...(o.records ? { records: o.records } : {}),
254
+ });
255
+
160
256
  /** Origine d'une table liée : hôte[:port]/base · schéma.table (jamais d'identifiant). Pure. */
161
- const linkedOrigin = (o) => (o && o.host ? `${o.host}${o.port && o.port !== 5432 ? `:${o.port}` : ''}/${o.database || ''} · ${o.schema || 'public'}.${o.table || ''}` : '');
257
+ const linkedOrigin = (o) =>
258
+ o && o.host
259
+ ? o.kind === 'mysql'
260
+ ? `mysql://${o.host}${o.port && o.port !== 3306 ? `:${o.port}` : ''}/${o.database || ''} · ${o.table || ''}`
261
+ : `${o.host}${o.port && o.port !== 5432 ? `:${o.port}` : ''}/${o.database || ''} · ${o.schema || 'public'}.${o.table || ''}`
262
+ : '';
162
263
 
163
264
  // Engine 0.64.0 et plus : sources (/meta/v1/sources), déclarées dans poad/sources
164
265
  const supportsSources = (config) => {
@@ -175,6 +276,38 @@ const age = (seconds) => {
175
276
  return `${Math.round(seconds / 86400)} d`;
176
277
  };
177
278
 
279
+ /** Taille lisible (puissances de 1024). Pure. */
280
+ const bytes = (n) => (n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(1)} GB` : n >= 1024 ** 2 ? `${Math.round(n / 1024 ** 2)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`);
281
+
282
+ const ENGINE_PROBLEMS = {
283
+ wrapper_missing: 'poad_files_wasm wrapper missing',
284
+ component_missing: 'Wasm component missing from the engine',
285
+ component_hash: 'unexpected Wasm component fingerprint',
286
+ refused: 'the Wasm component refused the table',
287
+ };
288
+
289
+ /**
290
+ * Moteur d'une table distante (remote.engine de meta, engine 0.69.0) : « wasm (key id, file of 46 MB) » ou
291
+ * « file_fdw (file of 2 MB, below 8 MB) ». meta rend un code et ses paramètres, jamais de texte. Pure.
292
+ */
293
+ const engineText = (e) => {
294
+ if (!e || typeof e !== 'object' || !e.engine) return '';
295
+ const p = e.params || {};
296
+ const types = (p.columns || []).map((c) => `${/geometry|geography/i.test(c.type) ? 'geometry' : c.type} (column ${c.column})`).join(', ');
297
+ const problem = ENGINE_PROBLEMS[p.problem] || 'Wasm component unavailable';
298
+ const why = {
299
+ forced: e.engine === 'wasm' ? 'forced by plan.moteur: wasm' : 'forced by plan.moteur: file',
300
+ forced_blocked: `wasm requested, but ${p.problem ? problem : `Wasm does not handle ${types}`}`,
301
+ types: `types Wasm does not handle: ${types}`,
302
+ key: 'no key declared',
303
+ component: problem,
304
+ unknown_size: 'file size not known yet, plan being built',
305
+ small: `file of ${bytes(p.size || 0)}, below ${bytes(p.threshold || 0)}`,
306
+ size: `key ${(p.key || []).join(', ')}, file of ${bytes(p.size || 0)}, filters pushed down`,
307
+ }[e.code] || e.code;
308
+ return `${e.engine === 'wasm' ? 'wasm' : 'file_fdw'} (${why})`;
309
+ };
310
+
178
311
  /** Nombre avec séparateur de milliers. Pure. */
179
312
  const count = (n) => (typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('en-US') : '?');
180
313
 
@@ -199,8 +332,12 @@ const sourceLines = (s, width = 0) => {
199
332
  const facts = ['remote table (file)', s.table, [format, where].filter(Boolean).join(' '), attached ? 'attached' : 'not attached'].filter(Boolean).join(' ');
200
333
  const out = [` ${attached && !(s.problems && s.problems.length) ? chalk.greenBright('✔') : chalk.yellowBright('!')} ${chalk.bold(name)} ${chalk.grey(facts)}`];
201
334
  if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
335
+ // Moteur de lecture (engine 0.69.0) : wasm (filtres transmis, plan du fichier) ou file_fdw, et pourquoi
336
+ const engine = s.remote && engineText(s.remote.engine);
337
+ if (engine) out.push((s.remote.engine.code === 'forced_blocked' ? chalk.yellowBright : chalk.grey)(` engine: ${engine}${s.remote.setting && s.remote.setting !== 'auto' ? `, plan.moteur: ${s.remote.setting}` : ''}`));
202
338
  for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
203
339
  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)}`));
340
+ for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
204
341
  if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
205
342
  return out;
206
343
  }
@@ -214,6 +351,7 @@ const sourceLines = (s, width = 0) => {
214
351
  for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
215
352
  if (s.linked && s.linked.credential_problem) out.push(chalk.yellowBright(` credential: ${s.linked.credential_problem}`));
216
353
  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)}`));
354
+ for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
217
355
  if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
218
356
  return out;
219
357
  }
@@ -229,6 +367,7 @@ const sourceLines = (s, width = 0) => {
229
367
  for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
230
368
  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)}`));
231
369
  if (failed && last.error) out.push(chalk.redBright(` last run failed: ${String(last.error).split('\n')[0].slice(0, 300)}`));
370
+ for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
232
371
  return out;
233
372
  };
234
373
 
@@ -486,6 +625,7 @@ const main = async (args = {}, raw, deps = {}) => {
486
625
  else if (/^[1-9]\d*$/.test(v)) opts.options.header = Number(v);
487
626
  else throw new SourceError(`poad source import: --header takes a row number, or none (got "${v}").`);
488
627
  } else if (w === '--records') opts.options.records = value();
628
+ else if (w === '--layer') opts.options.layer = value();
489
629
  else if (w === '--expand-until') {
490
630
  const v = value();
491
631
  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}").`);
@@ -501,7 +641,7 @@ const main = async (args = {}, raw, deps = {}) => {
501
641
  }
502
642
  }
503
643
  const usage =
504
- '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>]';
644
+ '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|topojson|shapefile|gpkg|fgb|parquet] [--layer <name>] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach] [--env <name>]';
505
645
  if (!opts.file) return fail(usage, 2);
506
646
  const file = path.resolve(cwd, opts.file);
507
647
  if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${opts.file}: no such file.`);
@@ -610,6 +750,7 @@ const main = async (args = {}, raw, deps = {}) => {
610
750
  // Table distante sur fichier : lue par Postgres (poad-files), à l'emplacement rendu sans query string
611
751
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote file is readable${ms}, ${remoteLocation({ url: /^https?:/.test(r.location) ? r.location : null, storage: null }) || r.location}`)}`);
612
752
  if (r.table) console.log(chalk.grey(` ${r.table}: read by Postgres, nothing copied${typeof r.sample_rows === 'number' ? `, ${r.sample_rows ? 'rows found' : 'no row'}` : ''}`));
753
+ if (engineText(r.engine)) console.log(chalk.grey(` engine: ${engineText(r.engine)}`));
613
754
  return;
614
755
  }
615
756
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote table answers${ms}${r.address ? `, checked address ${r.address}` : ''}`)}`);
@@ -623,12 +764,36 @@ const main = async (args = {}, raw, deps = {}) => {
623
764
  // Table distante sur fichier (engine 0.67.0) : l'engine vérifie l'adresse (garde des adresses internes) ou l'objet du
624
765
  // Stockage, lit un échantillon et propose les colonnes ; puis la déclaration (poad/sources/<table>.yaml) et la
625
766
  // migration de la table étrangère (file_fdw) sont écrites. Rien n'est copié : chaque requête relit le fichier.
767
+ // Qui peut lire (engine 0.70.0) : un fichier par adresse est lisible par tous ; un fichier du Stockage ou une table
768
+ // liée, la question est posée (terminal), sinon personne tant que --read n'est pas donné
769
+ const askLecture = async (o, origin) => {
770
+ if (o.lecture) return o.lecture;
771
+ if (origin === 'url') return 'tous';
772
+ if (!process.stdin.isTTY || !process.stdout.isTTY || json) return null;
773
+ const { select } = require('@inquirer/prompts');
774
+ return select({
775
+ message: `Who can read ${o.table} through the API?`,
776
+ choices: [
777
+ { name: 'Signed-in users', value: 'connectes' },
778
+ { name: 'Everyone (anon too)', value: 'tous' },
779
+ { name: 'Nobody (SQL only)', value: 'personne' },
780
+ ],
781
+ });
782
+ };
783
+ // Engine antérieur à 0.70.0 : il ignore la lecture (rien dans la déclaration) ; la table n'est pas servie
784
+ const lectureLine = (name, l, saved) =>
785
+ saved && typeof saved.yaml === 'string' && !/^\s*lecture:/m.test(saved.yaml)
786
+ ? ` Not served by the API until you ask (engine before 0.70.0): poad source expose ${name} --roles authenticated [--filter …].`
787
+ : l === 'personne' || !l
788
+ ? ` Read: nobody. Not served by the API until you choose: poad source expose ${name} --read connectes|tous [--filter …]. "poad source test ${name}" checks it.`
789
+ : ` Read: ${LECTURE_TEXT[l]}, read only, like a view (/data/v1/${name}). Change it: poad source expose ${name} --read tous|connectes|personne [--filter …].`;
790
+
626
791
  const linkFile = async (o) => {
627
792
  const t = await ready();
628
793
  if (!t) return;
629
794
  const where = o.storage ? { storage: o.storage } : { url: o.url };
630
795
  const csv = { ...(o.delimiter !== null ? { delimiter: o.delimiter === 'tab' ? '\\t' : o.delimiter } : {}), ...(o.header !== null ? { header: o.header } : {}), ...(o.encoding !== null ? { encoding: o.encoding.toLowerCase() } : {}) };
631
- const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/remote/inspect', { ...where, ...(o.format ? { format: o.format } : {}), ...(o.root ? { root: o.root } : {}), ...(Object.keys(csv).length ? { csv } : {}), name: o.table }));
796
+ const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/remote/inspect', { ...where, ...(o.format ? { format: o.format } : {}), ...(o.root ? { root: o.root } : {}), ...(Object.keys(csv).length ? { csv } : {}), ...(Object.keys(readerOptions(o)).length ? { options: readerOptions(o) } : {}), name: o.table }));
632
797
  if (!seen) return;
633
798
  let columns = Array.isArray(seen.columns) ? seen.columns : [];
634
799
  if (o.columns) {
@@ -638,7 +803,7 @@ const main = async (args = {}, raw, deps = {}) => {
638
803
  columns = columns.filter((c) => wanted.includes(c.from) || wanted.includes(c.name));
639
804
  }
640
805
  if (!columns.length) return fail(`${remoteLocation(where)}: no column to read.`);
641
- if (!o.format && !seen.format) return fail('The engine could not tell the format of the file: --format csv|json|jsonl|geojson|parquet.', 2);
806
+ if (!o.format && !seen.format) return fail(`The engine could not tell the format of the file: --format ${REMOTE_FORMATS.join('|')}.`, 2);
642
807
  const key = (seen.key || []).filter((k) => columns.some((c) => c.name === k));
643
808
  const draft = remoteDraft(o, seen, columns, key);
644
809
  if (!json) {
@@ -646,13 +811,15 @@ const main = async (args = {}, raw, deps = {}) => {
646
811
  const w = Math.max(...columns.map((c) => c.name.length));
647
812
  for (const c of columns) console.log(chalk.grey(` ${c.name.padEnd(w)} ${c.type}${c.from !== c.name ? ` ← ${c.from}` : ''}${c.transform ? ` (${c.transform})` : ''}`));
648
813
  }
649
- const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft }));
814
+ const lecture = await askLecture(o, o.storage ? 'storage' : 'url');
815
+ const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft, ...(lecture ? { lecture } : {}) }));
650
816
  if (!saved) return;
651
817
  if (json) return console.log(JSON.stringify(saved, null, 2));
652
818
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(saved.name || o.table)} ${chalk.grey(`public.${o.table} → ${remoteLocation(draft.origin)}, ${columns.length} column${columns.length > 1 ? 's' : ''}, nothing copied`)}`);
653
819
  if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
654
820
  for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
655
- console.log(chalk.grey(` Every query reads the file again. 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.`));
821
+ console.log(chalk.grey(` Every query reads the file again, nothing is copied.`));
822
+ console.log(chalk.grey(lectureLine(saved.name || o.table, lecture || 'personne', saved)));
656
823
  };
657
824
 
658
825
  if (command === 'link') {
@@ -662,11 +829,12 @@ const main = async (args = {}, raw, deps = {}) => {
662
829
  if (parsed.kind === 'file') return linkFile(o);
663
830
  const port = o.port === null ? undefined : Number(o.port);
664
831
  if (port !== undefined && !(Number.isInteger(port) && port >= 1 && port <= 65535)) return fail('--port: 1 to 65535.', 2);
832
+ const mysql = parsed.kind === 'mysql';
665
833
  const dot = o.remote.indexOf('.');
666
- const remote = dot > 0 ? { schema: o.remote.slice(0, dot), table: o.remote.slice(dot + 1) } : { schema: 'public', table: o.remote };
834
+ const remote = mysql ? { schema: o.database, table: o.remote } : dot > 0 ? { schema: o.remote.slice(0, dot), table: o.remote.slice(dot + 1) } : { schema: 'public', table: o.remote };
667
835
  const t = await ready();
668
836
  if (!t) return;
669
- const conn = { host: o.host, ...(port ? { port } : {}), database: o.database, credential: o.credential, sslmode: o.sslmode, name: o.table };
837
+ const conn = { ...(mysql ? { kind: 'mysql' } : {}), host: o.host, ...(port ? { port } : {}), database: o.database, credential: o.credential, sslmode: o.sslmode, name: o.table };
670
838
  const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/linked/inspect', { ...conn, ...remote }));
671
839
  if (!seen) return;
672
840
  let columns = Array.isArray(seen.columns) ? seen.columns : [];
@@ -682,21 +850,159 @@ const main = async (args = {}, raw, deps = {}) => {
682
850
  table: `public.${o.table}`,
683
851
  ...(o.title ? { title: o.title } : {}),
684
852
  mode: 'virtual',
685
- origin: { kind: 'postgres', host: o.host, ...(port ? { port } : {}), database: o.database, schema: remote.schema, table: remote.table, credential: o.credential, sslmode: o.sslmode },
853
+ origin: mysql
854
+ ? { kind: 'mysql', host: o.host, ...(port ? { port } : {}), database: o.database, table: remote.table, credential: o.credential, sslmode: o.sslmode }
855
+ : { kind: 'postgres', host: o.host, ...(port ? { port } : {}), database: o.database, schema: remote.schema, table: remote.table, credential: o.credential, sslmode: o.sslmode },
686
856
  columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type })),
687
857
  ...(key.length ? { key } : {}),
688
858
  };
689
- const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft }));
859
+ const lecture = await askLecture(o, 'linked');
860
+ const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft, ...(lecture ? { lecture } : {}) }));
690
861
  if (!saved) return;
691
862
  if (json) return console.log(JSON.stringify(saved, null, 2));
692
863
  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`)}`);
693
864
  if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
694
865
  for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
695
- 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.`));
866
+ console.log(chalk.grey(lectureLine(saved.name || o.table, lecture || 'personne', saved)));
696
867
  return;
697
868
  }
698
869
 
699
870
  // ------------------------------------------------------------------ pull
871
+ // ------------------------------------------------------------------ expose, unexpose, relate, unrelate, retain
872
+ // API d'une source (engine 0.69.0) : seuls les blocs api, relations et conservation de poad/sources/<nom>.yaml
873
+ // changent ; l'engine vérifie le filtre (EXPLAIN de la vue protégée) avant d'écrire, puis pose la vue et les droits.
874
+ // Sur poad.io, une source déployée par fichier se modifie dans le dépôt, puis poad deploy.
875
+ const putApi = async (name, body, done) => {
876
+ const t = await ready();
877
+ if (!t) return;
878
+ const r = await guard(() => call(t, 'PUT', `/meta/v1/sources/${encodeURIComponent(name)}/api`, body));
879
+ if (!r) return;
880
+ if (json) return console.log(JSON.stringify(r, null, 2));
881
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(done)}`);
882
+ if (r.file && !cloud) console.log(chalk.grey(` ${r.file} updated`));
883
+ for (const p of r.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
884
+ };
885
+ const currentRelations = async (t, name) => {
886
+ const s = await guard(() => call(t, 'GET', `/meta/v1/sources/${encodeURIComponent(name)}`));
887
+ if (!s) return null;
888
+ return (s.relations || []).map((r) => ({ colonne: r.column, vers: r.target, ...(r.name ? { nom: r.name } : {}) }));
889
+ };
890
+
891
+ if (command === 'expose') {
892
+ const parsed = parseExposeArgs(words.slice(1));
893
+ if (!parsed.ok) return fail(parsed.message, 2);
894
+ const b = parsed.body;
895
+ if (b.lecture === 'personne') return putApi(parsed.name, b, 'read: personne, not served by the API');
896
+ return putApi(parsed.name, b, `served by the API, read only${b.lecture ? `, to ${LECTURE_TEXT[b.lecture]}` : ''}${b.roles ? `, to ${b.roles.join(', ')}` : ''}${b.filtre ? ', with its filter' : ''}${b.debit ? `, ${b.debit}` : ''}${b.pagination ? `, ${b.pagination} rows per call` : ''}`);
897
+ }
898
+ if (command === 'unexpose') {
899
+ const name = words[1];
900
+ if (!name || words.length > 2) return fail('Usage: poad source unexpose <name>', 2);
901
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
902
+ return putApi(name, { lecture: 'personne' }, 'read: personne, no longer served by the API (403 not_exposed)');
903
+ }
904
+ if (command === 'relate' || command === 'unrelate') {
905
+ const rest = words.slice(1);
906
+ let relName = null;
907
+ const pos = [];
908
+ for (let i = 0; i < rest.length; i++) {
909
+ if (rest[i] === '--name' && command === 'relate') relName = rest[++i] || '';
910
+ else if (rest[i].startsWith('-')) return fail(`poad source ${command}: unknown option ${rest[i]}.`, 2);
911
+ else pos.push(rest[i]);
912
+ }
913
+ const [name, column, target] = pos;
914
+ const usage = command === 'relate' ? 'Usage: poad source relate <name> <column> <schema.table.column> [--name <relation>]' : 'Usage: poad source unrelate <name> <column>';
915
+ if (!name || !column || (command === 'relate' ? !target || pos.length > 3 : pos.length > 2)) return fail(usage, 2);
916
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
917
+ if (command === 'relate' && !TARGET_RE.test(target)) return fail('The target is schema.table.column (public.communes.code): a table, a view or another source.', 2);
918
+ if (relName !== null && !/^[a-z_][a-z0-9_]{0,62}$/.test(relName)) return fail('--name: a-z, 0-9 and "_".', 2);
919
+ const t = await ready();
920
+ if (!t) return;
921
+ const rels = await currentRelations(t, name);
922
+ if (!rels) return;
923
+ const vers = command === 'relate' ? (target.split('.').length === 2 ? `public.${target}` : target) : null;
924
+ const next = rels.filter((r) => r.colonne !== column || (command === 'relate' && r.vers !== vers));
925
+ if (command === 'unrelate' && next.length === rels.length) return fail(`${name} has no relation on ${column}.`);
926
+ if (command === 'relate') next.push({ colonne: column, vers, ...(relName ? { nom: relName } : {}) });
927
+ return putApi(name, { relations: next }, command === 'relate' ? `relation ${column} → ${vers} declared: include it in both directions` : `relation on ${column} removed`);
928
+ }
929
+ // ------------------------------------------------------------------ relation (poad relation …, engine 0.70.0)
930
+ // Relations sans clé étrangère, entre tables, vues, tables distantes et liées : include dans les deux sens. Celle
931
+ // d'une colonne de source va dans poad/sources/<nom>.yaml ; celle d'une table ou d'une vue, dans le commentaire de
932
+ // la colonne (il suit les migrations).
933
+ if (command === 'relation' || command === 'relations') {
934
+ const sub = words[1] || 'ls';
935
+ const rest = words.slice(2);
936
+ let relName = null;
937
+ const pos = [];
938
+ for (let i = 0; i < rest.length; i++) {
939
+ if (rest[i] === '--name' && sub === 'add') relName = rest[++i] || '';
940
+ else if (rest[i].startsWith('-')) return fail(`poad relation ${sub}: unknown option ${rest[i]}.`, 2);
941
+ else pos.push(rest[i]);
942
+ }
943
+ const REL_USAGE = 'Usage: poad relation ls [table] | add <table.column> <table.column> [--name <relation>] | rm <table.column> <table.column> | suggest <table> | check <table.column> <table.column>';
944
+ const COL_RE = /^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}\.[a-z_][a-z0-9_]{0,62}$/;
945
+ const full = (x) => (x.split('.').length === 2 ? `public.${x}` : x);
946
+ const short = (r) => `${r.schema === 'public' ? '' : `${r.schema}.`}${r.table}.${r.column}`;
947
+ if (!['ls', 'add', 'rm', 'suggest', 'check'].includes(sub)) return fail(REL_USAGE, 2);
948
+ if (['add', 'rm', 'check'].includes(sub) && (pos.length !== 2 || !pos.every((x) => COL_RE.test(x)))) return fail(REL_USAGE, 2);
949
+ if (sub === 'suggest' && (pos.length !== 1 || !/^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}$/.test(pos[0]))) return fail(REL_USAGE, 2);
950
+ if (relName !== null && !/^[a-z_][a-z0-9_]{0,62}$/.test(relName)) return fail('--name: a-z, 0-9 and "_".', 2);
951
+ const t = await ready();
952
+ if (!t) return;
953
+ if (sub === 'ls') {
954
+ const r = await guard(() => call(t, 'GET', '/meta/v1/relations?schema=public'));
955
+ if (!r) return;
956
+ const list = (r.relations || []).filter((x) => !pos[0] || x.from.table === pos[0] || x.to.table === pos[0]);
957
+ if (json) return console.log(JSON.stringify(list, null, 2));
958
+ if (!list.length) return console.log(chalk.grey(`No relation${pos[0] ? ` on ${pos[0]}` : ''}. "poad relation suggest <table>" proposes some.`));
959
+ const KIND = { foreign_key: 'foreign key', source: 'declared (source)', column: 'declared' };
960
+ for (const x of list) console.log(`${short(x.from)} ${x.kind === 'foreign_key' ? '→' : '⇢'} ${short(x.to)} ${chalk.grey(`${KIND[x.kind] || x.kind}${x.source ? ` ${x.source}` : ''}${x.name ? `, ${x.name}` : ''}`)}`);
961
+ return;
962
+ }
963
+ if (sub === 'suggest') {
964
+ const r = await guard(() => call(t, 'GET', `/meta/v1/relations/suggest?table=${encodeURIComponent(full(`${pos[0]}.x`).replace(/\.x$/, ''))}`));
965
+ if (!r) return;
966
+ if (json) return console.log(JSON.stringify(r.suggestions, null, 2));
967
+ if (!(r.suggestions || []).length) return console.log(chalk.grey(`No relation to propose for ${pos[0]}.`));
968
+ for (const x of r.suggestions) console.log(`${x.from.replace(/^public\./, '')} ⇢ ${x.to.replace(/^public\./, '')} ${chalk.grey(x.reason)}\n ${chalk.grey(`poad relation add ${x.from.replace(/^public\./, '')} ${x.to.replace(/^public\./, '')}`)}`);
969
+ return;
970
+ }
971
+ if (sub === 'check') {
972
+ const r = await guard(() => call(t, 'POST', '/meta/v1/relations/check', { from: full(pos[0]), to: full(pos[1]) }));
973
+ if (!r) return;
974
+ if (json) return console.log(JSON.stringify(r, null, 2));
975
+ if (!r.broken) return console.log(`${chalk.greenBright('✔')} ${chalk.grey(`${r.total} row(s), every link found (${r.ms} ms)`)}`);
976
+ console.log(`${chalk.yellowBright('!')} ${r.broken} of ${r.total} row(s) of ${pos[0].split('.').slice(-2, -1)[0]} point to a missing ${pos[1].split('.').slice(-2, -1)[0]}${r.examples.length ? chalk.grey(` (e.g. ${r.examples.map((v) => JSON.stringify(v)).join(', ')})`) : ''}`);
977
+ console.log(chalk.grey(' Nothing is blocked: an include gives null (or no row) for them.'));
978
+ return;
979
+ }
980
+ const body = { from: full(pos[0]), to: full(pos[1]), ...(relName ? { name: relName } : {}) };
981
+ const r = await guard(() => call(t, sub === 'add' ? 'POST' : 'DELETE', '/meta/v1/relations', body));
982
+ if (!r) return;
983
+ if (json) return console.log(JSON.stringify(r, null, 2));
984
+ console.log(`${chalk.greenBright('✔')} ${pos[0]} ⇢ ${pos[1]} ${chalk.grey(sub === 'add' ? 'declared: include it in both directions' : 'removed')}`);
985
+ console.log(chalk.grey(r.stored === 'source' ? ` in ${r.file || `the source ${r.source}`}` : ' in the comment of the column: it goes with the next migration (poad db diff)'));
986
+ for (const p of r.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
987
+ return;
988
+ }
989
+ if (command === 'retain') {
990
+ let column = null;
991
+ const pos = [];
992
+ const rest = words.slice(1);
993
+ for (let i = 0; i < rest.length; i++) {
994
+ if (rest[i] === '--column') column = rest[++i] || '';
995
+ else if (rest[i].startsWith('-')) return fail(`poad source retain: unknown option ${rest[i]}.`, 2);
996
+ else pos.push(rest[i]);
997
+ }
998
+ const [name, duration] = pos;
999
+ if (!name || !duration || pos.length > 2) return fail('Usage: poad source retain <name> <90d|12w|6mois|1an|off> [--column <date column>]', 2);
1000
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
1001
+ if (duration === 'off') return putApi(name, { conservation: null }, 'no retention: the copy stays until the next sync changes it');
1002
+ if (!RETAIN_RE.test(duration)) return fail('The duration is like 90d, 12w, 6mois, 1an.', 2);
1003
+ return putApi(name, { conservation: column ? { duree: duration, colonne: column } : duration }, column ? `rows older than ${duration} (by ${column}) are purged` : `the copy is emptied ${duration} after its last successful sync`);
1004
+ }
1005
+
700
1006
  // La déclaration d'une source (créée dans la console hébergée, gardée en base) écrite dans poad/sources :
701
1007
  // le fichier fait foi ensuite (poad deploy l'envoie ; sur poad.io, un fichier déployé l'emporte).
702
1008
  if (command === 'pull') {
@@ -733,4 +1039,4 @@ const main = async (args = {}, raw, deps = {}) => {
733
1039
  };
734
1040
 
735
1041
  module.exports = (args, raw) => main(args, raw);
736
- Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, linkedOrigin, remoteLocation, parseStorageRef, parseLinkArgs, remoteDraft, REMOTE_FORMATS, NAME_RE, FORMATS, describeReader });
1042
+ Object.assign(module.exports, { main, supportsSources, sourceLines, engineText, parseExposeArgs, apiFacts, reportOf, reportLines, guardRefused, age, linkedOrigin, remoteLocation, parseStorageRef, parseLinkArgs, remoteDraft, REMOTE_FORMATS, NAME_RE, FORMATS, describeReader });
@@ -0,0 +1,41 @@
1
+ // node --test (comme le reste du CLI ; bun:test n'existe pas sous node)
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const { addBody, describe: line, options } = require('../project/connection');
5
+ const egress = require('../utils/egress');
6
+
7
+ test('poad connection : options et corps de add', () => {
8
+ const o = options(['--url', 'https://api.sncf.com', '--credential=sncf', '--rate', '5/s', '--paths', '/v1/**,/v2/*'], ['url', 'credential', 'rate', 'paths']);
9
+ assert.deepStrictEqual(addBody('sncf', o.opts), { name: 'sncf', base_url: 'https://api.sncf.com', auth: { type: 'bearer', credential: 'sncf' }, paths: ['/v1/**', '/v2/*'], rate: '5/s' });
10
+ assert.deepStrictEqual(addBody('x', { url: 'https://a.b', header: 'X-Key', credential: 'k' }).auth, { type: 'header', credential: 'k', header: 'X-Key' });
11
+ assert.ok(addBody('x', {}).error.includes('--url'));
12
+ assert.ok(addBody('x', { url: 'https://a.b', auth: 'bearer' }).error.includes('--credential'));
13
+ assert.ok(options(['--nope', '1'], ['url']).error.includes('--nope'));
14
+ });
15
+
16
+ test('poad connection : ligne de ls, jamais de secret, le credential par son nom', () => {
17
+ assert.strictEqual(line({ name: 'sncf', base_url: 'https://api.sncf.com', binding: 'SNCF', auth: { type: 'bearer', credential: { name: 'sncf', exists: false } }, rate: { requests: 5, per_ms: 1000 } }), 'sncf https://api.sncf.com bearer sncf (missing), 5/s env.SNCF');
18
+ });
19
+
20
+ test('[egress] de config.toml', () => {
21
+ assert.deepStrictEqual(egress.engineEnv({}), ['EGRESS_MODE=free']);
22
+ assert.deepStrictEqual(egress.engineEnv({ egress: { mode: 'declared', allow: ['api.github.com', '*.data.gouv.fr'] } }), ['EGRESS_MODE=declared', 'EGRESS_ALLOW=api.github.com,*.data.gouv.fr']);
23
+ assert.ok(egress.settings({ egress: { mode: 'open' } }).error.includes('free'));
24
+ assert.deepStrictEqual(egress.engineEnv({ egress: { allow: ['pas bon'] } }), ['EGRESS_MODE=declared']);
25
+ });
26
+
27
+ // Connexions typées (lot « connexions », engine 0.69.0)
28
+ const { typedBody, describeType } = require('../project/connection');
29
+ const AIRTABLE = { id: 'airtable', name: 'Airtable', family: 'applications', hosts: ['api.airtable.com'], fields: [{ key: 'token', kind: 'secret' }, { key: 'note', kind: 'text' }], legacy: false, problems: [] };
30
+
31
+ test('typedBody : secret jamais en argument, lu dans POAD_SECRET_<CLÉ>', () => {
32
+ assert.match(typedBody('at', { type: 'airtable', set: ['token=pat'] }, AIRTABLE).error, /never goes on the command line/);
33
+ assert.deepEqual(typedBody('at', { type: 'airtable', set: ['note=a=b'] }, AIRTABLE, { POAD_SECRET_TOKEN: 'pat-x' }), { name: 'at', type: 'airtable', values: { note: 'a=b', token: 'pat-x' } });
34
+ assert.match(typedBody('at', { type: 'x' }, undefined).error, /unknown type/);
35
+ assert.match(typedBody('at', { type: 'api-key' }, { ...AIRTABLE, id: 'api-key', legacy: true }).error, /migrated credentials/);
36
+ assert.match(typedBody('at', { type: 'airtable', set: ['autre=1'] }, AIRTABLE).error, /no such field/);
37
+ });
38
+
39
+ test('describeType : hôtes du secret', () => {
40
+ assert.equal(describeType(AIRTABLE), 'airtable Airtable (applications) secret → api.airtable.com');
41
+ });