poad 2.69.0 → 2.71.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
@@ -8,7 +8,7 @@
8
8
  // poad source link <table> --url https://… | --storage bucket/chemin [--format f] [--delimiter ;] [--no-header]
9
9
  // [--encoding e] [--root a.b] [--columns a,b]
10
10
  // table distante sur fichier (mode virtual, engine 0.67.0+) : CSV, JSON, JSON-L,
11
- // GeoJSON ou Parquet lu par DuckDB dans Postgres à chaque requête, rien n'est copié
11
+ // GeoJSON ou Parquet lu par poad-files dans Postgres à chaque requête, rien n'est copié
12
12
  // poad source test <nom> table liée ou distante : vérifie l'adresse (garde des adresses internes),
13
13
  // rebranche, lit une ligne par Postgres
14
14
  // poad source pull <nom> [--force] rapatrie la déclaration d'une source (créée dans la console
@@ -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,12 @@ 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> [--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,…>] [--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,…>] [--env <name>]';
56
56
  const SSLMODES = ['require', 'verify-full', 'disable'];
57
- /** Formats d'une table distante sur fichier (meta, engine 0.67.0 : lus par DuckDB) */
58
- const REMOTE_FORMATS = ['csv', 'json', 'jsonl', 'geojson', 'parquet'];
57
+ /** Formats d'une table distante sur fichier (meta, engine 0.67.0 : lus par DuckDB ; 0.68.0 : par poad-files) */
58
+ // Engine 0.69.0 : tous les formats de poad-files se lisent aussi en table distante (détectés : --format pour surcharger)
59
+ const REMOTE_FORMATS = ['csv', 'json', 'jsonl', 'geojson', 'parquet', 'topojson', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'shapefile', 'gpkg', 'fgb'];
59
60
  const REMOTE_ENCODINGS = ['utf-8', 'latin-1', 'iso-8859-1', 'windows-1252', 'utf-16'];
60
61
  const BUCKET_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
61
62
 
@@ -89,8 +90,8 @@ const parseStorageRef = (raw) => {
89
90
  * Rend { ok: false, message } ou { ok: true, kind: 'postgres' | 'file', o }. Pure.
90
91
  */
91
92
  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' };
93
+ 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, sheet: null, layer: null, records: null };
94
+ 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', '--sheet': 'sheet', '--layer': 'layer', '--records': 'records' };
94
95
  for (let i = 0; i < words.length; i++) {
95
96
  const w = words[i];
96
97
  const flag = valued[w];
@@ -142,21 +143,89 @@ const parseLinkArgs = (words) => {
142
143
  return { ok: true, kind: 'file', o };
143
144
  };
144
145
 
146
+ const API_ROLES = ['anon', 'authenticated', 'service_role'];
147
+ const RATE_RE = /^\d{1,6}\/(s|min|h|j|jour|d|day)$/;
148
+ const RETAIN_RE = /^\d{1,5}\s*(d|j|jours?|days?|sem|w|weeks?|mois|m|ans?|y|h)$/i;
149
+ const TARGET_RE = /^(?:[a-z_][a-z0-9_]{0,62}\.)?[a-z_][a-z0-9_]{0,62}\.[a-z_][a-z0-9_]{0,62}$/;
150
+
151
+ /**
152
+ * Options de poad source expose (engine 0.69.0) : --roles, --filter (ou --filtre), --rate (ou --debit), --max-rows
153
+ * (ou --pagination). Rend le corps de PUT /meta/v1/sources/<nom>/api. Pure.
154
+ */
155
+ const parseExposeArgs = (words) => {
156
+ const o = { name: null, roles: null, filtre: undefined, debit: null, pagination: null };
157
+ const valued = { '--roles': 'roles', '--role': 'roles', '--filter': 'filtre', '--filtre': 'filtre', '--rate': 'debit', '--debit': 'debit', '--max-rows': 'pagination', '--pagination': 'pagination' };
158
+ for (let i = 0; i < words.length; i++) {
159
+ const w = words[i];
160
+ const k = valued[w];
161
+ if (k) {
162
+ const v = words[++i];
163
+ if (v === undefined) return { ok: false, message: `poad source expose: ${w} needs a value.` };
164
+ o[k] = v;
165
+ } else if (w === '--no-filter') o.filtre = null;
166
+ else if (w.startsWith('-')) return { ok: false, message: `poad source expose: unknown option ${w}.` };
167
+ else if (o.name === null) o.name = w;
168
+ else return { ok: false, message: `poad source expose: one source at a time ("${w}").` };
169
+ }
170
+ if (!o.name) return { ok: false, message: 'Usage: poad source expose <name> [--roles authenticated,anon] [--filter "owner_email = auth.email()"] [--rate 30/min] [--max-rows 100]' };
171
+ if (!NAME_RE.test(o.name)) return { ok: false, message: `"${o.name}" is not a source name.` };
172
+ const body = { expose: true };
173
+ if (o.roles !== null) {
174
+ const roles = o.roles.split(',').map((x) => x.trim()).filter(Boolean);
175
+ 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).` };
176
+ body.roles = [...new Set(roles)];
177
+ }
178
+ if (o.filtre !== undefined) body.filtre = o.filtre === null || !o.filtre.trim() ? null : o.filtre;
179
+ if (o.debit !== null) {
180
+ 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.' };
181
+ body.debit = o.debit.replace(/\s+/g, '');
182
+ }
183
+ if (o.pagination !== null) {
184
+ const n = Number(o.pagination);
185
+ if (!Number.isInteger(n) || n < 1 || n > 10000) return { ok: false, message: '--max-rows: 1 to 10000 rows per call.' };
186
+ body.pagination = n;
187
+ }
188
+ return { ok: true, name: o.name, body };
189
+ };
190
+
191
+ /** Ligne « api » d'une source dans poad source ls. Pure. */
192
+ const apiFacts = (s) => {
193
+ const e = s.exposure;
194
+ const out = [];
195
+ if (e) {
196
+ if (!e.expose) out.push(`api: not served (poad source expose ${s.name})`);
197
+ else out.push(`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)' : ''}` : ''}`);
198
+ }
199
+ for (const r of s.relations || []) out.push(`relation: ${r.column} → ${r.target}${r.name ? ` (${r.name})` : ''}${r.active ? '' : ' (not active)'}`);
200
+ 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)` : ''}`);
201
+ if (s.mode === 'virtual' && s.last_read_at) out.push(`last read ${s.last_read_at.replace('T', ' ').slice(0, 16)} UTC`);
202
+ return out;
203
+ };
204
+
145
205
  /** Brouillon d'une table distante sur fichier (POST /sources) : jamais de credential ni d'en-tête. Pure. */
146
206
  const remoteDraft = (o, inspected, columns, key) => {
147
207
  const format = o.format || inspected.format;
148
208
  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
209
  const root = format === 'json' ? (o.root || inspected.root || null) : null;
210
+ // Options du format (feuille, couche, chemin des enregistrements) : trouvées par l'engine, ou données
211
+ const options = { ...(inspected.options || {}), ...readerOptions(o) };
150
212
  return {
151
213
  table: `public.${o.table}`,
152
214
  ...(o.title ? { title: o.title } : {}),
153
215
  mode: 'virtual',
154
- origin: { kind: 'file', ...(o.storage ? { storage: o.storage } : { url: o.url }), format, ...(root ? { root } : {}), ...(csv && Object.keys(csv).length ? { csv } : {}) },
216
+ 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
217
  columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) })),
156
218
  ...(key && key.length ? { key } : {}),
157
219
  };
158
220
  };
159
221
 
222
+ /** Options du lecteur données en ligne de commande (--sheet, --layer, --records). Pure. */
223
+ const readerOptions = (o) => ({
224
+ ...(o.sheet ? { sheet: /^\d+$/.test(o.sheet) ? Number(o.sheet) : o.sheet } : {}),
225
+ ...(o.layer ? { layer: o.layer } : {}),
226
+ ...(o.records ? { records: o.records } : {}),
227
+ });
228
+
160
229
  /** Origine d'une table liée : hôte[:port]/base · schéma.table (jamais d'identifiant). Pure. */
161
230
  const linkedOrigin = (o) => (o && o.host ? `${o.host}${o.port && o.port !== 5432 ? `:${o.port}` : ''}/${o.database || ''} · ${o.schema || 'public'}.${o.table || ''}` : '');
162
231
 
@@ -175,6 +244,38 @@ const age = (seconds) => {
175
244
  return `${Math.round(seconds / 86400)} d`;
176
245
  };
177
246
 
247
+ /** Taille lisible (puissances de 1024). Pure. */
248
+ 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`);
249
+
250
+ const ENGINE_PROBLEMS = {
251
+ wrapper_missing: 'poad_files_wasm wrapper missing',
252
+ component_missing: 'Wasm component missing from the engine',
253
+ component_hash: 'unexpected Wasm component fingerprint',
254
+ refused: 'the Wasm component refused the table',
255
+ };
256
+
257
+ /**
258
+ * Moteur d'une table distante (remote.engine de meta, engine 0.69.0) : « wasm (key id, file of 46 MB) » ou
259
+ * « file_fdw (file of 2 MB, below 8 MB) ». meta rend un code et ses paramètres, jamais de texte. Pure.
260
+ */
261
+ const engineText = (e) => {
262
+ if (!e || typeof e !== 'object' || !e.engine) return '';
263
+ const p = e.params || {};
264
+ const types = (p.columns || []).map((c) => `${/geometry|geography/i.test(c.type) ? 'geometry' : c.type} (column ${c.column})`).join(', ');
265
+ const problem = ENGINE_PROBLEMS[p.problem] || 'Wasm component unavailable';
266
+ const why = {
267
+ forced: e.engine === 'wasm' ? 'forced by plan.moteur: wasm' : 'forced by plan.moteur: file',
268
+ forced_blocked: `wasm requested, but ${p.problem ? problem : `Wasm does not handle ${types}`}`,
269
+ types: `types Wasm does not handle: ${types}`,
270
+ key: 'no key declared',
271
+ component: problem,
272
+ unknown_size: 'file size not known yet, plan being built',
273
+ small: `file of ${bytes(p.size || 0)}, below ${bytes(p.threshold || 0)}`,
274
+ size: `key ${(p.key || []).join(', ')}, file of ${bytes(p.size || 0)}, filters pushed down`,
275
+ }[e.code] || e.code;
276
+ return `${e.engine === 'wasm' ? 'wasm' : 'file_fdw'} (${why})`;
277
+ };
278
+
178
279
  /** Nombre avec séparateur de milliers. Pure. */
179
280
  const count = (n) => (typeof n === 'number' && Number.isFinite(n) ? n.toLocaleString('en-US') : '?');
180
281
 
@@ -192,15 +293,19 @@ const sourceLines = (s, width = 0) => {
192
293
  return [chalk.redBright(` ✖ ${name} ${s.file}`), chalk.redBright(` ${first.line ? `line ${first.line}: ` : first.path ? `${first.path}: ` : ''}${first.message || 'invalid declaration'}${more}`)];
193
294
  }
194
295
  if (s.mode === 'virtual' && (s.remote || (s.origin && s.origin.kind === 'file'))) {
195
- // Table distante sur fichier : DuckDB relit le fichier à chaque requête ; branchée (user mapping posé) ou non
296
+ // Table distante sur fichier : poad-files relit le fichier à chaque requête ; branchée ou non (adresse refusée)
196
297
  const attached = Boolean(s.remote && s.remote.attached) && s.table_exists !== false;
197
298
  const where = (s.remote && s.remote.location) || remoteLocation(s.origin);
198
299
  const format = (s.remote && s.remote.format) || (s.origin && s.origin.format) || '';
199
300
  const facts = ['remote table (file)', s.table, [format, where].filter(Boolean).join(' '), attached ? 'attached' : 'not attached'].filter(Boolean).join(' ');
200
301
  const out = [` ${attached && !(s.problems && s.problems.length) ? chalk.greenBright('✔') : chalk.yellowBright('!')} ${chalk.bold(name)} ${chalk.grey(facts)}`];
201
302
  if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
303
+ // Moteur de lecture (engine 0.69.0) : wasm (filtres transmis, plan du fichier) ou file_fdw, et pourquoi
304
+ const engine = s.remote && engineText(s.remote.engine);
305
+ 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
306
  for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
203
307
  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)}`));
308
+ for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
204
309
  if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
205
310
  return out;
206
311
  }
@@ -214,6 +319,7 @@ const sourceLines = (s, width = 0) => {
214
319
  for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
215
320
  if (s.linked && s.linked.credential_problem) out.push(chalk.yellowBright(` credential: ${s.linked.credential_problem}`));
216
321
  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)}`));
322
+ for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
217
323
  if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
218
324
  return out;
219
325
  }
@@ -229,6 +335,7 @@ const sourceLines = (s, width = 0) => {
229
335
  for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
230
336
  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
337
  if (failed && last.error) out.push(chalk.redBright(` last run failed: ${String(last.error).split('\n')[0].slice(0, 300)}`));
338
+ for (const f of apiFacts(s)) out.push(chalk.grey(` ${f}`));
232
339
  return out;
233
340
  };
234
341
 
@@ -486,6 +593,7 @@ const main = async (args = {}, raw, deps = {}) => {
486
593
  else if (/^[1-9]\d*$/.test(v)) opts.options.header = Number(v);
487
594
  else throw new SourceError(`poad source import: --header takes a row number, or none (got "${v}").`);
488
595
  } else if (w === '--records') opts.options.records = value();
596
+ else if (w === '--layer') opts.options.layer = value();
489
597
  else if (w === '--expand-until') {
490
598
  const v = value();
491
599
  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 +609,7 @@ const main = async (args = {}, raw, deps = {}) => {
501
609
  }
502
610
  }
503
611
  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>]';
612
+ '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
613
  if (!opts.file) return fail(usage, 2);
506
614
  const file = path.resolve(cwd, opts.file);
507
615
  if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${opts.file}: no such file.`);
@@ -607,9 +715,10 @@ const main = async (args = {}, raw, deps = {}) => {
607
715
  if (json) return console.log(JSON.stringify(r, null, 2));
608
716
  const ms = typeof r.duration_ms === 'number' ? ` (${Math.round(r.duration_ms)} ms)` : '';
609
717
  if (r.location) {
610
- // Table distante sur fichier : lue par Postgres (DuckDB), à l'emplacement rendu sans query string
718
+ // Table distante sur fichier : lue par Postgres (poad-files), à l'emplacement rendu sans query string
611
719
  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
720
  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'}` : ''}`));
721
+ if (engineText(r.engine)) console.log(chalk.grey(` engine: ${engineText(r.engine)}`));
613
722
  return;
614
723
  }
615
724
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote table answers${ms}${r.address ? `, checked address ${r.address}` : ''}`)}`);
@@ -622,13 +731,13 @@ const main = async (args = {}, raw, deps = {}) => {
622
731
  // (utilisateur et mot de passe) est déjà dans le coffre : poad credential, ou l'écran Credentials ; jamais ici.
623
732
  // Table distante sur fichier (engine 0.67.0) : l'engine vérifie l'adresse (garde des adresses internes) ou l'objet du
624
733
  // Stockage, lit un échantillon et propose les colonnes ; puis la déclaration (poad/sources/<table>.yaml) et la
625
- // migration de la table étrangère (duckdb_fdw) sont écrites. Rien n'est copié : chaque requête relit le fichier.
734
+ // migration de la table étrangère (file_fdw) sont écrites. Rien n'est copié : chaque requête relit le fichier.
626
735
  const linkFile = async (o) => {
627
736
  const t = await ready();
628
737
  if (!t) return;
629
738
  const where = o.storage ? { storage: o.storage } : { url: o.url };
630
739
  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 }));
740
+ 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
741
  if (!seen) return;
633
742
  let columns = Array.isArray(seen.columns) ? seen.columns : [];
634
743
  if (o.columns) {
@@ -638,7 +747,7 @@ const main = async (args = {}, raw, deps = {}) => {
638
747
  columns = columns.filter((c) => wanted.includes(c.from) || wanted.includes(c.name));
639
748
  }
640
749
  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);
750
+ if (!o.format && !seen.format) return fail(`The engine could not tell the format of the file: --format ${REMOTE_FORMATS.join('|')}.`, 2);
642
751
  const key = (seen.key || []).filter((k) => columns.some((c) => c.name === k));
643
752
  const draft = remoteDraft(o, seen, columns, key);
644
753
  if (!json) {
@@ -652,7 +761,7 @@ const main = async (args = {}, raw, deps = {}) => {
652
761
  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
762
  if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
654
763
  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.`));
764
+ console.log(chalk.grey(` Every query reads the file again. Not served by the API until you ask: poad source expose ${saved.name || o.table} --roles authenticated [--filter …]. "poad source test ${saved.name || o.table}" checks it.`));
656
765
  };
657
766
 
658
767
  if (command === 'link') {
@@ -692,11 +801,85 @@ const main = async (args = {}, raw, deps = {}) => {
692
801
  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
802
  if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
694
803
  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.`));
804
+ console.log(chalk.grey(` Not served by the API until you ask: poad source expose ${saved.name || o.table} --roles authenticated [--filter …]. "poad source test ${saved.name || o.table}" checks it.`));
696
805
  return;
697
806
  }
698
807
 
699
808
  // ------------------------------------------------------------------ pull
809
+ // ------------------------------------------------------------------ expose, unexpose, relate, unrelate, retain
810
+ // API d'une source (engine 0.69.0) : seuls les blocs api, relations et conservation de poad/sources/<nom>.yaml
811
+ // changent ; l'engine vérifie le filtre (EXPLAIN de la vue protégée) avant d'écrire, puis pose la vue et les droits.
812
+ // Sur poad.io, une source déployée par fichier se modifie dans le dépôt, puis poad deploy.
813
+ const putApi = async (name, body, done) => {
814
+ const t = await ready();
815
+ if (!t) return;
816
+ const r = await guard(() => call(t, 'PUT', `/meta/v1/sources/${encodeURIComponent(name)}/api`, body));
817
+ if (!r) return;
818
+ if (json) return console.log(JSON.stringify(r, null, 2));
819
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(done)}`);
820
+ if (r.file && !cloud) console.log(chalk.grey(` ${r.file} updated`));
821
+ for (const p of r.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
822
+ };
823
+ const currentRelations = async (t, name) => {
824
+ const s = await guard(() => call(t, 'GET', `/meta/v1/sources/${encodeURIComponent(name)}`));
825
+ if (!s) return null;
826
+ return (s.relations || []).map((r) => ({ colonne: r.column, vers: r.target, ...(r.name ? { nom: r.name } : {}) }));
827
+ };
828
+
829
+ if (command === 'expose') {
830
+ const parsed = parseExposeArgs(words.slice(1));
831
+ if (!parsed.ok) return fail(parsed.message, 2);
832
+ const b = parsed.body;
833
+ return putApi(parsed.name, b, `served by the API, read only${b.roles ? `, to ${b.roles.join(', ')}` : ''}${b.filtre ? ', with its filter' : ''}${b.debit ? `, ${b.debit}` : ''}${b.pagination ? `, ${b.pagination} rows per call` : ''}`);
834
+ }
835
+ if (command === 'unexpose') {
836
+ const name = words[1];
837
+ if (!name || words.length > 2) return fail('Usage: poad source unexpose <name>', 2);
838
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
839
+ return putApi(name, { expose: false }, 'no longer served by the API (403 not_exposed)');
840
+ }
841
+ if (command === 'relate' || command === 'unrelate') {
842
+ const rest = words.slice(1);
843
+ let relName = null;
844
+ const pos = [];
845
+ for (let i = 0; i < rest.length; i++) {
846
+ if (rest[i] === '--name' && command === 'relate') relName = rest[++i] || '';
847
+ else if (rest[i].startsWith('-')) return fail(`poad source ${command}: unknown option ${rest[i]}.`, 2);
848
+ else pos.push(rest[i]);
849
+ }
850
+ const [name, column, target] = pos;
851
+ const usage = command === 'relate' ? 'Usage: poad source relate <name> <column> <schema.table.column> [--name <relation>]' : 'Usage: poad source unrelate <name> <column>';
852
+ if (!name || !column || (command === 'relate' ? !target || pos.length > 3 : pos.length > 2)) return fail(usage, 2);
853
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
854
+ 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);
855
+ if (relName !== null && !/^[a-z_][a-z0-9_]{0,62}$/.test(relName)) return fail('--name: a-z, 0-9 and "_".', 2);
856
+ const t = await ready();
857
+ if (!t) return;
858
+ const rels = await currentRelations(t, name);
859
+ if (!rels) return;
860
+ const vers = command === 'relate' ? (target.split('.').length === 2 ? `public.${target}` : target) : null;
861
+ const next = rels.filter((r) => r.colonne !== column || (command === 'relate' && r.vers !== vers));
862
+ if (command === 'unrelate' && next.length === rels.length) return fail(`${name} has no relation on ${column}.`);
863
+ if (command === 'relate') next.push({ colonne: column, vers, ...(relName ? { nom: relName } : {}) });
864
+ return putApi(name, { relations: next }, command === 'relate' ? `relation ${column} → ${vers} declared: include it in both directions` : `relation on ${column} removed`);
865
+ }
866
+ if (command === 'retain') {
867
+ let column = null;
868
+ const pos = [];
869
+ const rest = words.slice(1);
870
+ for (let i = 0; i < rest.length; i++) {
871
+ if (rest[i] === '--column') column = rest[++i] || '';
872
+ else if (rest[i].startsWith('-')) return fail(`poad source retain: unknown option ${rest[i]}.`, 2);
873
+ else pos.push(rest[i]);
874
+ }
875
+ const [name, duration] = pos;
876
+ if (!name || !duration || pos.length > 2) return fail('Usage: poad source retain <name> <90d|12w|6mois|1an|off> [--column <date column>]', 2);
877
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
878
+ if (duration === 'off') return putApi(name, { conservation: null }, 'no retention: the copy stays until the next sync changes it');
879
+ if (!RETAIN_RE.test(duration)) return fail('The duration is like 90d, 12w, 6mois, 1an.', 2);
880
+ 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`);
881
+ }
882
+
700
883
  // La déclaration d'une source (créée dans la console hébergée, gardée en base) écrite dans poad/sources :
701
884
  // le fichier fait foi ensuite (poad deploy l'envoie ; sur poad.io, un fichier déployé l'emporte).
702
885
  if (command === 'pull') {
@@ -733,4 +916,4 @@ const main = async (args = {}, raw, deps = {}) => {
733
916
  };
734
917
 
735
918
  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 });
919
+ 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,25 @@
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
+ });
@@ -312,7 +312,7 @@ test('source link --env : colonnes proposées par l’engine, brouillon sans sec
312
312
  key: ['id'],
313
313
  });
314
314
  assert.match(r.stdout, /✔ clients {2}public\.clients → db\.example\.com\/crm · ventes\.Clients, 2 columns, nothing copied/);
315
- assert.match(r.stdout, /never served by the API/);
315
+ assert.match(r.stdout, /Not served by the API until you ask: poad source expose clients/);
316
316
  const tst = await poad(box, cloud.api, ['source', 'test', 'clients', '--env', 'dev']);
317
317
  assert.strictEqual(tst.status, 0, tst.all);
318
318
  assert.match(tst.stdout, /✔ clients {2}the remote table answers \(12 ms\)/);
@@ -348,9 +348,9 @@ test('source import : formats lus par source-read et options du lecteur, refus c
348
348
  const cloud = await fakeCloud(t);
349
349
  const box = sandbox(t);
350
350
  fs.writeFileSync(path.join(box.app, 'mesures.xlsx'), 'PK');
351
- const badFormat = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--format', 'parquet']);
351
+ const badFormat = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--format', 'sqlite']);
352
352
  assert.strictEqual(badFormat.status, 2, badFormat.all);
353
- assert.match(badFormat.all, /--format: csv, json, geojson, jsonl, ics, xlsx, ods, xml, kml, kmz, gpx \(got "parquet"\)/);
353
+ assert.match(badFormat.all, /--format: csv, json, geojson, jsonl, ics, xlsx, ods, xml, kml, kmz, gpx, topojson, shapefile, gpkg, fgb, parquet \(got "sqlite"\)/);
354
354
  const badHeader = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--header', 'deux']);
355
355
  assert.strictEqual(badHeader.status, 2, badHeader.all);
356
356
  assert.match(badHeader.all, /--header takes a row number, or none/);
@@ -363,7 +363,7 @@ test('describeReader : feuille, en-tête, enregistrements, répétitions, exécu
363
363
  assert.strictEqual(source.describeReader({ details: { sheets: ['A', 'Mesures'], sheet: 'Mesures', header_row: 3 }, options: { sheet: 'Mesures', header: 3 }, run_id: 'r1' }), 'sheet "Mesures" (of "A", "Mesures"; --sheet), header on row 3, read by source-read (run r1)');
364
364
  assert.strictEqual(source.describeReader({ details: { events: 9 }, options: { expand: { until: '2027-12-31' } } }), 'recurrences expanded until 2027-12-31, 9 event(s)');
365
365
  assert.strictEqual(source.describeReader({ format: 'csv', csv: { delimiter: ';' } }), null);
366
- assert.deepStrictEqual(source.FORMATS, ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx']);
366
+ assert.deepStrictEqual(source.FORMATS, ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'topojson', 'shapefile', 'gpkg', 'fgb', 'parquet']);
367
367
  });
368
368
 
369
369
  // --- Tables distantes sur fichier (mode virtual, engine 0.67.0) ---------------------------
@@ -406,7 +406,7 @@ test('source link --storage : objet du Stockage, options CSV, adresse interne re
406
406
  assert.strictEqual(refused.status, 1, refused.all);
407
407
  assert.match(refused.stdout, /adresse interne refusée \(127\.0\.0\.1\)/);
408
408
  assert.strictEqual(cloud.state.requests.filter((q) => q.path === '/meta/v1/sources' && q.method === 'POST').length, 1, 'nothing more declared');
409
- for (const args of [['source', 'link', 'x', '--url', 'https://a.org/f.csv', '--host', 'h'], ['source', 'link', 'x', '--storage', 'sansChemin'], ['source', 'link', 'x', '--url', 'ftp://a.org/f.csv'], ['source', 'link', 'x', '--url', 'https://a.org/f', '--format', 'xlsx']]) {
409
+ for (const args of [['source', 'link', 'x', '--url', 'https://a.org/f.csv', '--host', 'h'], ['source', 'link', 'x', '--storage', 'sansChemin'], ['source', 'link', 'x', '--url', 'ftp://a.org/f.csv'], ['source', 'link', 'x', '--url', 'https://a.org/f', '--format', 'sqlite']]) {
410
410
  const u = await poad(box, cloud.api, [...args, '--env', 'dev']);
411
411
  assert.strictEqual(u.status, 2, `${args.join(' ')}: ${u.all}`);
412
412
  }
@@ -430,7 +430,10 @@ test('parseLinkArgs, parseStorageRef, remoteLocation, remoteDraft : formes et re
430
430
  assert.deepStrictEqual(d, { table: 'public.t', mode: 'virtual', origin: { kind: 'file', url: 'https://a.org/f.json', format: 'json', root: 'data.items' }, columns: [{ name: 'a', from: 'a', type: 'text' }] });
431
431
  const tab = source.parseLinkArgs(['t', '--storage', 'b/f.tsv', '--delimiter', 'tab', '--no-header']);
432
432
  assert.deepStrictEqual(source.remoteDraft(tab.o, { format: 'csv' }, [{ name: 'c', from: '#1', type: 'text' }], []).origin.csv, { delimiter: '\\t', header: false });
433
- assert.deepStrictEqual(source.REMOTE_FORMATS, ['csv', 'json', 'jsonl', 'geojson', 'parquet']);
433
+ assert.deepStrictEqual(source.REMOTE_FORMATS, ['csv', 'json', 'jsonl', 'geojson', 'parquet', 'topojson', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'shapefile', 'gpkg', 'fgb']);
434
+ // Engine 0.69.0 : options du lecteur données en ligne de commande, écrites dans la déclaration
435
+ const sheet = source.parseLinkArgs(['t', '--url', 'https://a.org/f.xlsx', '--sheet', '2', '--layer', 'communes']);
436
+ assert.deepStrictEqual(source.remoteDraft(sheet.o, { format: 'xlsx', options: { header: 3 } }, [{ name: 'c', from: 'c', type: 'text' }], []).origin.options, { header: 3, sheet: 2, layer: 'communes' });
434
437
  });
435
438
 
436
439
  test('sourceLines : table distante sur fichier branchée ou non, emplacement sans query string', () => {
@@ -442,3 +445,28 @@ test('sourceLines : table distante sur fichier branchée ou non, emplacement san
442
445
  assert.match(off, /poad source test arrets_bus tells why/);
443
446
  assert.ok(!off.includes('cle=1'));
444
447
  });
448
+
449
+ test('expose : options lues, corps de PUT /sources/<nom>/api', () => {
450
+ const { parseExposeArgs, apiFacts } = require('../project/source');
451
+ const r = parseExposeArgs(['gares', '--roles', 'authenticated,anon', '--filter', 'owner_email = auth.email()', '--rate', '30/min', '--max-rows', '50']);
452
+ assert.deepEqual(r, { ok: true, name: 'gares', body: { expose: true, roles: ['authenticated', 'anon'], filtre: 'owner_email = auth.email()', debit: '30/min', pagination: 50 } });
453
+ assert.equal(parseExposeArgs(['gares', '--filtre', 'a = 1', '--debit', '5/s']).body.debit, '5/s');
454
+ assert.match(parseExposeArgs(['gares', '--roles', 'admin']).message, /--roles/);
455
+ assert.match(parseExposeArgs(['gares', '--rate', 'vite']).message, /--rate/);
456
+ assert.match(parseExposeArgs(['gares', '--max-rows', '0']).message, /--max-rows/);
457
+ assert.equal(parseExposeArgs(['gares', '--no-filter']).body.filtre, null);
458
+ const lines = apiFacts({ name: 'gares', mode: 'virtual', exposure: { expose: true, served: true, roles: ['authenticated'], filter: 'x', rate: '30/min', pagination: 100 }, relations: [{ column: 'commune', target: 'public.communes.nom', name: null, active: true }], last_read_at: '2026-12-03T14:24:00.000Z' });
459
+ assert.deepEqual(lines, ['api: served to authenticated, filter, 30/min, 100 rows per call', 'relation: commune → public.communes.nom', 'last read 2026-12-03 14:24 UTC']);
460
+ assert.deepEqual(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: false } }), ['api: not served (poad source expose g)']);
461
+ assert.equal(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: true, served: true, roles: ['anon'], filter: null, rate: '60/min', pagination: 100, timeout: '10s', timeout_default: true } })[0], 'api: served to anon, 60/min, 100 rows per call, timeout 10s (default)');
462
+ });
463
+
464
+ test('engineText : moteur d\'une table distante d\'après le code et les paramètres de meta (engine 0.69.0)', () => {
465
+ const { engineText, sourceLines } = require('../project/source');
466
+ assert.equal(engineText({ engine: 'wasm', code: 'size', params: { key: ['id'], size: 46 * 1024 * 1024 } }), 'wasm (key id, file of 46 MB, filters pushed down)');
467
+ assert.equal(engineText({ engine: 'file', code: 'small', params: { size: 2 * 1024 * 1024, threshold: 8 * 1024 * 1024 } }), 'file_fdw (file of 2 MB, below 8 MB)');
468
+ assert.equal(engineText({ engine: 'file', code: 'forced_blocked', params: { columns: [{ column: 'geom', type: 'geometry' }] } }), 'file_fdw (wasm requested, but Wasm does not handle geometry (column geom))');
469
+ assert.equal(engineText(null), '');
470
+ const lines = sourceLines({ name: 'gares', valid: true, mode: 'virtual', table: 'public.gares', remote: { attached: true, location: 'https://x/y.csv', format: 'csv', engine: { engine: 'file', code: 'key', params: {} }, setting: 'auto' } }).join('\n');
471
+ assert.match(lines, /engine: file_fdw \(no key declared\)/);
472
+ });