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.
@@ -0,0 +1,72 @@
1
+ // poad db sync : tables synchronisées (engine 0.70.0+), contre un meta simulé
2
+ const test = require('node:test');
3
+ const assert = require('node:assert/strict');
4
+ // Les attentes du test, écrites au départ pour bun:test, sur node:assert (npm test lance node --test)
5
+ const expect = (v) => ({
6
+ toEqual: (w) => assert.deepStrictEqual(v, w),
7
+ toBeNull: () => assert.equal(v, null),
8
+ toContain: (w) => assert.ok(v != null && v.includes(w), `${JSON.stringify(v)} ne contient pas ${JSON.stringify(w)}`),
9
+ });
10
+ const sync = require('../project/db/sync');
11
+
12
+ test('table tapée : nom ou schéma.nom', () => {
13
+ expect(sync.target('notes')).toEqual({ schema: 'public', table: 'notes' });
14
+ expect(sync.target('app.notes')).toEqual({ schema: 'app', table: 'notes' });
15
+ expect(sync.target('a b')).toBeNull();
16
+ });
17
+
18
+ test('options : valeurs et drapeaux', () => {
19
+ expect(sync.options(['purge', 'notes', '--force', '--before', '2026-12-01'], ['before'], ['force'])).toEqual({ opts: { before: '2026-12-01' }, flags: new Set(['force']), rest: ['purge', 'notes'] });
20
+ expect(sync.options(['--nope'], [], []).error).toContain('--nope');
21
+ });
22
+
23
+ test('état lisible', () => {
24
+ const lines = sync.describeStatus('notes', { synced: true, key: 'id', retention: '30 days', version: 900, deleted_pending: 2, last_purge_at: null, devices: [{ device_id: 'tel', email: 'alice@x', last_version: 880, last_sync_at: new Date().toISOString(), stale: false }] });
25
+ expect(lines[0]).toContain('synced on key id');
26
+ expect(lines[1]).toContain('2 D row(s)');
27
+ expect(lines[3]).toContain('tel');
28
+ expect(sync.describeStatus('plain', { synced: false })[0]).toContain('poad db sync enable plain');
29
+ });
30
+
31
+ test('purge : appelle meta avec forcer et rend le nombre', async () => {
32
+ const calls = [];
33
+ const fetch = async (url, init) => {
34
+ calls.push([init.method, url, init.body && JSON.parse(init.body)]);
35
+ return new Response(JSON.stringify({ purged: 3, remaining_deleted: 0 }), { status: 200 });
36
+ };
37
+ const fs = require('fs');
38
+ const os = require('os');
39
+ const path = require('path');
40
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-sync-'));
41
+ fs.mkdirSync(path.join(dir, 'poad'));
42
+ fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "t"\nproject_uuid = "u"\nengine = "0.70.0"\n[web]\nport = 1234\n[auth]\nservice = "k"\n');
43
+ const logs = [];
44
+ const orig = console.log;
45
+ console.log = (m) => logs.push(String(m));
46
+ try {
47
+ await sync.main({}, ['purge', 'notes', '--force'], { fetch, cwd: dir, started: async () => true });
48
+ } finally {
49
+ console.log = orig;
50
+ }
51
+ expect(calls).toEqual([['POST', 'http://localhost:1234/meta/v1/tables/public/notes/sync/purge', { forcer: true }]]);
52
+ expect(logs.join('\n')).toContain('3 D row(s) purged');
53
+ });
54
+
55
+ test('engine trop ancien : refusé avec le conseil', async () => {
56
+ const fs = require('fs');
57
+ const os = require('os');
58
+ const path = require('path');
59
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-sync-'));
60
+ fs.mkdirSync(path.join(dir, 'poad'));
61
+ fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "t"\nproject_uuid = "u"\nengine = "0.69.1"\n[web]\nport = 1\n[auth]\nservice = "k"\n');
62
+ const logs = [];
63
+ const orig = console.log;
64
+ console.log = (m) => logs.push(String(m));
65
+ try {
66
+ await sync.main({}, ['status', 'notes'], { cwd: dir, started: async () => true });
67
+ } finally {
68
+ console.log = orig;
69
+ process.exitCode = 0;
70
+ }
71
+ expect(logs.join('\n')).toContain('engine 0.70.0');
72
+ });
@@ -0,0 +1,82 @@
1
+ // poad logs --env / --project : lecture par l'API /logs/v1 d'un projet hébergé (utils/logs-remote.js)
2
+ const test = require('node:test');
3
+ const assert = require('node:assert/strict');
4
+ const { entriesParams, explain } = require('../utils/logs-remote');
5
+ const logs = require('../project/logs');
6
+
7
+ test('options traduites en paramètres de /logs/v1/entries', () => {
8
+ const { params } = entriesParams({ level: 'WARN', since: '15m', request: '6f1c', grep: 'timeout', flow: 'demo', run: 'DAFB44E1', source: 'communes', tool: 'select_rows', limit: 20000 }, ['data', 'files']);
9
+ assert.equal(params.get('service'), 'data,files');
10
+ assert.equal(params.get('level'), 'warn');
11
+ assert.equal(params.get('since'), '15m');
12
+ assert.equal(params.get('request'), '6f1c');
13
+ assert.equal(params.get('grep'), 'timeout');
14
+ assert.equal(params.get('flow'), 'demo');
15
+ assert.equal(params.get('run'), 'dafb44e1');
16
+ assert.equal(params.get('source'), 'communes');
17
+ assert.equal(params.get('attr.tool'), 'select_rows');
18
+ assert.equal(params.get('limit'), '5000');
19
+ assert.match(entriesParams({ token: 'x' }).error, /token=/);
20
+ });
21
+
22
+ test('erreurs de l’API : une phrase, jamais le jeton', () => {
23
+ assert.match(explain(401, null, 'poad.io abc'), /poad login/);
24
+ assert.match(explain(404, null, 'poad.io abc'), /too old|paused/);
25
+ assert.match(explain(502, null, 'poad.io abc'), /does not answer/);
26
+ });
27
+
28
+ test('poad logs files level=warn --env recette : jeton court, filtres, lignes rendues', async () => {
29
+ const calls = [];
30
+ const out = [];
31
+ const log = console.log;
32
+ console.log = (...a) => out.push(a.join(' '));
33
+ try {
34
+ await logs({}, ['files', 'level=warn', '--env', 'recette', '--project', 'abc', '--json'], {
35
+ cwd: __dirname,
36
+ cloudTarget: async (o) => {
37
+ calls.push(['target', o]);
38
+ return { base: 'https://abc--recette.poad.io', key: 'jeton-court', apikey: 'anon', label: 'poad.io abc (recette)' };
39
+ },
40
+ fetch: async (url, init) => {
41
+ calls.push(['fetch', url, init.headers.authorization]);
42
+ return new Response(JSON.stringify({ entries: [{ id: '7', ts: '2026-12-03T10:00:00Z', level: 'warn', service: 'files', msg: 'lecture annulée', request_id: 'r1', attrs: {} }], last_id: '7' }), { status: 200 });
43
+ },
44
+ });
45
+ } finally {
46
+ console.log = log;
47
+ }
48
+ assert.deepEqual(calls[0], ['target', { env: 'recette', project: 'abc' }]);
49
+ const u = new URL(calls[1][1]);
50
+ assert.equal(u.origin + u.pathname, 'https://abc--recette.poad.io/logs/v1/entries');
51
+ assert.equal(u.searchParams.get('service'), 'files');
52
+ assert.equal(u.searchParams.get('level'), 'warn');
53
+ assert.equal(calls[1][2], 'Bearer jeton-court');
54
+ assert.ok(out.some((l) => l.includes('"lecture annulée"')));
55
+ assert.ok(!out.join('\n').includes('jeton-court'));
56
+ });
57
+
58
+ test('suivi -f : after=<dernier id>, jeton renouvelé avant sa fin', async () => {
59
+ const urls = [];
60
+ let n = 0;
61
+ let renewed = 0;
62
+ const log = console.log;
63
+ console.log = () => {};
64
+ try {
65
+ await logs({}, ['--project', 'abc', '-f'], {
66
+ cwd: '/',
67
+ sleep: async () => {},
68
+ stopped: () => n >= 3,
69
+ cloudTarget: async () => ({ base: 'https://abc.poad.io', key: 'k1', apikey: 'anon', label: 'poad.io abc', renew: { first: new Date(Date.now() + 30_000).toISOString(), next: async () => (renewed++, { token: 'k2', expires_at: new Date(Date.now() + 900_000).toISOString() }) } }),
70
+ fetch: async (url) => {
71
+ n++;
72
+ urls.push(url);
73
+ return new Response(JSON.stringify({ entries: [], last_id: String(40 + n) }), { status: 200 });
74
+ },
75
+ });
76
+ } finally {
77
+ console.log = log;
78
+ }
79
+ assert.equal(renewed, 1);
80
+ assert.match(urls[1], /limit=1$/);
81
+ assert.match(urls[2], /after=42/);
82
+ });
@@ -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, /Read: nobody. Not served by the API until you choose: poad source expose clients --read/);
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
  }
@@ -416,6 +416,10 @@ test('parseLinkArgs, parseStorageRef, remoteLocation, remoteDraft : formes et re
416
416
  const ok = source.parseLinkArgs(['t', '--url', 'https://a.org/f.json', '--format', 'json', '--root', 'data.items']);
417
417
  assert.strictEqual(ok.kind, 'file');
418
418
  assert.strictEqual(source.parseLinkArgs(['t', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c']).kind, 'postgres');
419
+ assert.strictEqual(source.parseLinkArgs(['t', '--mysql', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c']).kind, 'mysql');
420
+ assert.match(source.parseLinkArgs(['t', '--mysql', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c', '--sslmode', 'verify-full']).message, /not for MySQL/);
421
+ assert.match(source.parseLinkArgs(['t', '--mysql', '--host', 'h', '--database', 'd', '--remote', 'd.r', '--credential', 'c']).message, /table name only/);
422
+ assert.match(source.parseLinkArgs(['t', '--mysql', '--url', 'https://a.org/f.csv']).message, /not a file/);
419
423
  assert.match(source.parseLinkArgs(['t', '--url', 'https://a.org/f.json', '--storage', 'b/p']).message, /not both/);
420
424
  assert.match(source.parseLinkArgs(['t', '--url', 'https://u:p@a.org/f.csv']).message, /no user or password/);
421
425
  assert.match(source.parseLinkArgs(['t', '--url', 'https://a.org/f.csv', '--format', 'geojson', '--delimiter', ';']).message, /for a CSV file/);
@@ -430,7 +434,10 @@ test('parseLinkArgs, parseStorageRef, remoteLocation, remoteDraft : formes et re
430
434
  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
435
  const tab = source.parseLinkArgs(['t', '--storage', 'b/f.tsv', '--delimiter', 'tab', '--no-header']);
432
436
  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']);
437
+ assert.deepStrictEqual(source.REMOTE_FORMATS, ['csv', 'json', 'jsonl', 'geojson', 'parquet', 'topojson', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx', 'shapefile', 'gpkg', 'fgb']);
438
+ // Engine 0.69.0 : options du lecteur données en ligne de commande, écrites dans la déclaration
439
+ const sheet = source.parseLinkArgs(['t', '--url', 'https://a.org/f.xlsx', '--sheet', '2', '--layer', 'communes']);
440
+ 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
441
  });
435
442
 
436
443
  test('sourceLines : table distante sur fichier branchée ou non, emplacement sans query string', () => {
@@ -442,3 +449,34 @@ test('sourceLines : table distante sur fichier branchée ou non, emplacement san
442
449
  assert.match(off, /poad source test arrets_bus tells why/);
443
450
  assert.ok(!off.includes('cle=1'));
444
451
  });
452
+
453
+ test('expose : options lues, corps de PUT /sources/<nom>/api', () => {
454
+ const { parseExposeArgs, apiFacts } = require('../project/source');
455
+ const r = parseExposeArgs(['gares', '--roles', 'authenticated,anon', '--filter', 'owner_email = auth.email()', '--rate', '30/min', '--max-rows', '50']);
456
+ assert.deepEqual(r, { ok: true, name: 'gares', body: { expose: true, roles: ['authenticated', 'anon'], filtre: 'owner_email = auth.email()', debit: '30/min', pagination: 50 } });
457
+ assert.equal(parseExposeArgs(['gares', '--filtre', 'a = 1', '--debit', '5/s']).body.debit, '5/s');
458
+ assert.match(parseExposeArgs(['gares', '--roles', 'admin']).message, /--roles/);
459
+ assert.match(parseExposeArgs(['gares', '--rate', 'vite']).message, /--rate/);
460
+ assert.match(parseExposeArgs(['gares', '--max-rows', '0']).message, /--max-rows/);
461
+ assert.equal(parseExposeArgs(['gares', '--no-filter']).body.filtre, null);
462
+ 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' });
463
+ 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']);
464
+ assert.deepEqual(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: false } }), ['read: personne, not served (poad source expose g --read tous|connectes)']);
465
+ // Engine 0.70.0 : qui lit (lecture), par défaut ou gardée privée à la montée
466
+ assert.deepEqual(parseExposeArgs(['gares', '--read', 'connectés']), { ok: true, name: 'gares', body: { lecture: 'connectes' } });
467
+ assert.match(parseExposeArgs(['gares', '--read', 'tous', '--roles', 'anon']).message, /not both/);
468
+ assert.match(parseExposeArgs(['gares', '--read', 'peut-etre']).message, /--read/);
469
+ assert.equal(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: true, lecture: 'tous', implicit: true, served: true, roles: ['anon', 'authenticated', 'service_role'], filter: null, rate: '60/min', pagination: 100 } })[0], 'read: tous (default), api: served to anon, authenticated, service_role, 60/min, 100 rows per call');
470
+ assert.equal(apiFacts({ name: 'g', mode: 'virtual', exposure: { expose: false, lecture: 'personne', legacy_private: true } })[0], 'read: personne (private in 0.69, kept private), not served (poad source expose g --read tous|connectes)');
471
+ 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)');
472
+ });
473
+
474
+ test('engineText : moteur d\'une table distante d\'après le code et les paramètres de meta (engine 0.69.0)', () => {
475
+ const { engineText, sourceLines } = require('../project/source');
476
+ assert.equal(engineText({ engine: 'wasm', code: 'size', params: { key: ['id'], size: 46 * 1024 * 1024 } }), 'wasm (key id, file of 46 MB, filters pushed down)');
477
+ 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)');
478
+ 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))');
479
+ assert.equal(engineText(null), '');
480
+ 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');
481
+ assert.match(lines, /engine: file_fdw \(no key declared\)/);
482
+ });
@@ -0,0 +1,283 @@
1
+ // Copie de infra/services/meta/src/capture.ts (compilée en CommonJS) : garder
2
+ // les deux identiques, la console et poad db diff capturent pareil.
3
+ "use strict";
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.suggestName = exports.countItems = exports.capture = exports.describeEntry = exports.splitIdentity = exports.shortOf = exports.isRoutineStatement = exports.splitStatements = void 0;
6
+ // Ce qu'une migration tirée du journal emporte vraiment.
7
+ //
8
+ // Le journal note le texte envoyé par le client : un script entier de l'éditeur
9
+ // SQL (42 fonctions dont une seule modifiée) arrive en une entrée de 2 000 lignes
10
+ // qui cite 42 fonctions. Postgres signale un CREATE OR REPLACE même quand rien ne
11
+ // change.
12
+ //
13
+ // Pour les fonctions et procédures, ce n'est donc plus le texte qui part dans la
14
+ // migration, mais la différence du catalogue (poad_migrations.routine_changes(),
15
+ // engine 0.69.0) : formes canoniques (pg_get_functiondef, droits, commentaire,
16
+ // propriétaire), surcharges distinguées par leur signature complète.
17
+ // - une entrée qui cite des routines est découpée en instructions ; celles qui
18
+ // portent sur une routine (create/alter/drop function, comment on function,
19
+ // grant/revoke on function…) sont retirées, le reste (le « résidu ») est gardé
20
+ // tel quel ;
21
+ // - les entrées qui citent les mêmes routines forment un groupe (une unité de
22
+ // l'écran Migrations) ; sa dernière entrée porte le SQL de la différence ;
23
+ // - rien de changé : l'unité est « sans effet », il n'y a rien à écrire.
24
+ // Les entrées antérieures à la référence (routinesSince) gardent leur texte.
25
+ //
26
+ // Même code dans le CLI (utils/capture.js) : poad db diff fait pareil.
27
+ const compact_1 = require("./compact");
28
+ // ------------------------------------------------------------ découpage
29
+ /** Découpe un script SQL en instructions (chaînes, identifiants, $tag$…$tag$, commentaires). null : script mal formé. Pure. */
30
+ const splitStatements = (text) => {
31
+ const out = [];
32
+ let start = 0;
33
+ let i = 0;
34
+ const n = text.length;
35
+ while (i < n) {
36
+ const c = text[i];
37
+ const next = text[i + 1];
38
+ if (c === '-' && next === '-') {
39
+ const e = text.indexOf('\n', i);
40
+ i = e < 0 ? n : e + 1;
41
+ }
42
+ else if (c === '/' && next === '*') {
43
+ let depth = 1;
44
+ i += 2;
45
+ while (i < n && depth) {
46
+ if (text[i] === '/' && text[i + 1] === '*')
47
+ (depth++, (i += 2));
48
+ else if (text[i] === '*' && text[i + 1] === '/')
49
+ (depth--, (i += 2));
50
+ else
51
+ i++;
52
+ }
53
+ if (depth)
54
+ return null;
55
+ }
56
+ else if (c === "'" || c === '"') {
57
+ // E'…' : antislash échappé
58
+ const escapes = c === "'" && /[eE]/.test(text[i - 1] ?? '') && !/[\w$]/.test(text[i - 2] ?? '');
59
+ i++;
60
+ for (;;) {
61
+ if (i >= n)
62
+ return null;
63
+ if (escapes && text[i] === '\\')
64
+ i += 2;
65
+ else if (text[i] === c && text[i + 1] === c)
66
+ i += 2;
67
+ else if (text[i] === c)
68
+ break;
69
+ else
70
+ i++;
71
+ }
72
+ i++;
73
+ }
74
+ else if (c === '$' && !/[\w$]/.test(text[i - 1] ?? '')) {
75
+ const m = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(text.slice(i, i + 64));
76
+ if (!m) {
77
+ i++;
78
+ continue;
79
+ }
80
+ const end = text.indexOf(m[0], i + m[0].length);
81
+ if (end < 0)
82
+ return null;
83
+ i = end + m[0].length;
84
+ }
85
+ else if (c === ';') {
86
+ out.push(text.slice(start, i + 1));
87
+ start = ++i;
88
+ }
89
+ else
90
+ i++;
91
+ }
92
+ out.push(text.slice(start));
93
+ return out.map((s) => s.trim()).filter((s) => s && !/^;?$/.test(stripComments(s).trim()));
94
+ };
95
+ exports.splitStatements = splitStatements;
96
+ const stripComments = (s) => s.replace(/^(?:\s*(?:--[^\n]*\n?|\/\*[\s\S]*?\*\/))*/, '');
97
+ const ROUTINE_STATEMENT = /^\s*(?:create\s+(?:or\s+replace\s+)?(?:function|procedure)\b|(?:alter|drop)\s+(?:function|procedure|routine)\b|comment\s+on\s+(?:function|procedure|routine)\b|(?:grant|revoke)\b[^;]*?\bon\s+(?:function|procedure|routine)\b)/i;
98
+ /** L'instruction porte-t-elle sur une routine (create/alter/drop function, comment, grant/revoke on function) ? Pure. */
99
+ const isRoutineStatement = (stmt) => ROUTINE_STATEMENT.test(stripComments(stmt));
100
+ exports.isRoutineStatement = isRoutineStatement;
101
+ // ------------------------------------------------------------ description
102
+ const KINDS = ['schema', 'extension', 'table', 'view', 'materialized view', 'foreign table', 'type', 'domain', 'function', 'procedure', 'aggregate', 'trigger', 'policy', 'publication', 'index', 'sequence'];
103
+ const kindOf = (command) => /^(?:CREATE|ALTER|DROP)\s+(.+)$/i.exec(command.trim())?.[1]?.toLowerCase() ?? null;
104
+ /** public.f(pg_catalog.text) → public.f ; « p on public.t » reste tel quel. Pure. */
105
+ const shortOf = (identity) => identity.split('(')[0];
106
+ exports.shortOf = shortOf;
107
+ /** Schéma et nom d'une identité (public.todos, "Mon schéma".t, « p on public.t » → p). Pure. */
108
+ const splitIdentity = (identity) => {
109
+ const head = (0, exports.shortOf)(identity).split(' on ')[0];
110
+ const parts = (head.match(/"(?:[^"]|"")+"|[^.]+/g) ?? [head]).map((p) => p.replace(/^"|"$/g, '').replace(/""/g, '"'));
111
+ return parts.length > 1 ? { schema: parts[0], name: parts[parts.length - 1] } : { schema: '', name: parts[0] };
112
+ };
113
+ exports.splitIdentity = splitIdentity;
114
+ const escapeRe = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
115
+ /** L'objet principal d'une entrée du journal, lisible (type, nom, motif). Pure. */
116
+ const describeEntry = (e, objects = e.objects.filter((o) => Boolean(o))) => {
117
+ const rank = (k) => (k && KINDS.includes(k) ? KINDS.indexOf(k) : KINDS.length);
118
+ const main = [...e.commands].sort((a, b) => rank(kindOf(a)) - rank(kindOf(b)))[0] ?? '';
119
+ const verb = main.split(/\s+/)[0].toUpperCase();
120
+ if (!objects.length)
121
+ return null;
122
+ const named = objects.find((o) => new RegExp(`(^|[^\\w$])"?${escapeRe((0, exports.splitIdentity)(o).name)}"?($|[^\\w$])`, 'i').test(e.statement));
123
+ const object = named ?? objects[0];
124
+ const type = kindOf(main) ?? (verb === 'GRANT' || verb === 'REVOKE' ? 'grants' : verb === 'COMMENT' ? 'comment' : 'object');
125
+ const change = verb === 'DROP' ? 'dropped' : verb === 'CREATE' && !/^\s*create\s+or\s+replace\b/i.test(stripComments(e.statement)) ? 'created' : 'modified';
126
+ return { type, ...(0, exports.splitIdentity)(object), change };
127
+ };
128
+ exports.describeEntry = describeEntry;
129
+ /** a, b, c et 47 autres. Pure. */
130
+ const shortList = (xs, max = 3) => (xs.length <= max ? xs.join(', ') : `${xs.slice(0, max).join(', ')} et ${xs.length - max} autres`);
131
+ // ------------------------------------------------------------ capture
132
+ /**
133
+ * Unités de l'écran Migrations (et de poad db diff) et SQL effectif de chaque entrée. Pure.
134
+ * known : identités des routines (actuelles et de la référence), pour reconnaître les objets du journal
135
+ * since : id du journal à partir duquel la référence vaut (null : engine sans référence, texte gardé partout)
136
+ */
137
+ const capture = (entries, changes, known, since) => {
138
+ const knownFull = new Set(known);
139
+ const knownShort = new Set(known.map(exports.shortOf));
140
+ const isRoutineObj = (e, o) => knownFull.has(o) || knownShort.has(o) || (o.includes('(') && e.commands.some((c) => /^(CREATE|ALTER|DROP) (FUNCTION|PROCEDURE|ROUTINE)$/i.test(c)));
141
+ const sql = new Map();
142
+ const routineEntries = [];
143
+ const normal = [];
144
+ for (const e of entries) {
145
+ const objs = e.objects.filter((o) => Boolean(o));
146
+ const routines = since === null || e.id <= since ? [] : objs.filter((o) => isRoutineObj(e, o));
147
+ const parts = routines.length ? (0, exports.splitStatements)(e.statement) : null;
148
+ if (!parts) {
149
+ normal.push(e);
150
+ continue;
151
+ }
152
+ routineEntries.push({ e, routines: routines.map(exports.shortOf), residue: parts.filter((p) => !(0, exports.isRoutineStatement)(p)), others: objs.filter((o) => !routines.includes(o)) });
153
+ }
154
+ // Groupes : entrées qui citent une même routine (par schéma.nom : les surcharges vont ensemble)
155
+ const parent = routineEntries.map((_, i) => i);
156
+ const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
157
+ const owner = new Map();
158
+ routineEntries.forEach((r, i) => {
159
+ for (const k of r.routines) {
160
+ const j = owner.get(k);
161
+ if (j === undefined)
162
+ owner.set(k, i);
163
+ else
164
+ parent[find(i)] = find(j);
165
+ }
166
+ });
167
+ const groups = new Map();
168
+ routineEntries.forEach((r, i) => groups.set(find(i), [...(groups.get(find(i)) ?? []), r]));
169
+ const units = [];
170
+ for (const g of groups.values()) {
171
+ const names = new Set(g.flatMap((r) => r.routines));
172
+ const rows = changes.filter((c) => names.has((0, exports.shortOf)(c.identity)));
173
+ const ids = g.map((r) => r.e.id);
174
+ const last = ids[ids.length - 1];
175
+ const keep = [];
176
+ for (const r of g) {
177
+ const own = r.residue.map((s) => s.replace(/;?\s*$/, ';'));
178
+ if (r.e.id === last)
179
+ own.push(...rows.map((c) => c.sql));
180
+ const text = own.join('\n\n');
181
+ sql.set(r.e.id, text);
182
+ if (text.trim())
183
+ keep.push(r.e.id);
184
+ }
185
+ const items = rows.map((c) => ({ type: c.kind, schema: c.schema_name, name: c.name, change: c.change, aspects: c.aspects, identity: c.identity, lines: c.sql.split('\n').length }));
186
+ for (const r of g)
187
+ if (r.residue.length) {
188
+ const d = (0, exports.describeEntry)({ ...r.e, statement: r.residue.join('\n') }, r.others);
189
+ if (d)
190
+ items.push(d);
191
+ }
192
+ units.push({
193
+ ids,
194
+ keep,
195
+ kind: 'routine',
196
+ target: shortList([...names].map((n) => (0, exports.splitIdentity)(n).name)),
197
+ effect: !keep.length ? 'none' : ids.length === 1 ? 'one' : 'merged',
198
+ // Groupe de plusieurs entrées : ce qu'il en reste (« 2 objets changés »)
199
+ result: ids.length > 1 && items.length ? `${items.length} objet${items.length > 1 ? 's' : ''} changé${items.length > 1 ? 's' : ''}` : null,
200
+ items,
201
+ at: keep[keep.length - 1] ?? last,
202
+ });
203
+ }
204
+ const byId = new Map(entries.map((e) => [e.id, e]));
205
+ for (const u of (0, compact_1.compact)(normal)) {
206
+ const items = u.keep.map((id) => (0, exports.describeEntry)(byId.get(id))).filter((x) => Boolean(x));
207
+ for (const id of u.ids)
208
+ sql.set(id, u.keep.includes(id) ? String(byId.get(id).statement).trim().replace(/;?\s*$/, ';') : '');
209
+ units.push({ ...u, items, at: u.keep[u.keep.length - 1] ?? u.ids[u.ids.length - 1] });
210
+ }
211
+ const sorted = units.sort((a, b) => a.at - b.at).map(({ at: _at, ...u }) => u);
212
+ return { units: sorted, sql };
213
+ };
214
+ exports.capture = capture;
215
+ /** Objets d'une sélection, comptés par type et motif (journal migration_captured). Pure. */
216
+ const countItems = (items) => {
217
+ const byType = {};
218
+ const byChange = {};
219
+ for (const i of items) {
220
+ byType[i.type] = (byType[i.type] ?? 0) + 1;
221
+ byChange[i.change] = (byChange[i.change] ?? 0) + 1;
222
+ }
223
+ return { objects: items.length, by_type: byType, by_change: byChange };
224
+ };
225
+ exports.countItems = countItems;
226
+ // ------------------------------------------------------------ nom
227
+ const VERB = { created: 'cree', modified: 'modifie', dropped: 'supprime' };
228
+ const TYPE = {
229
+ function: ['', 'fonctions'],
230
+ procedure: ['procedure', 'procedures'],
231
+ table: ['table', 'tables'],
232
+ view: ['vue', 'vues'],
233
+ 'materialized view': ['vue_materialisee', 'vues_materialisees'],
234
+ 'foreign table': ['table_distante', 'tables_distantes'],
235
+ index: ['index', 'index'],
236
+ policy: ['politique', 'politiques'],
237
+ extension: ['extension', 'extensions'],
238
+ schema: ['schema', 'schemas'],
239
+ type: ['type', 'types'],
240
+ domain: ['domaine', 'domaines'],
241
+ trigger: ['declencheur', 'declencheurs'],
242
+ sequence: ['sequence', 'sequences'],
243
+ grants: ['droits', 'droits'],
244
+ comment: ['commentaire', 'commentaires'],
245
+ };
246
+ const snake = (s) => s
247
+ .normalize('NFD')
248
+ .replace(/[̀-ͯ]/g, '')
249
+ .replace(/[^A-Za-z0-9]+/g, '_')
250
+ .replace(/^_+|_+$/g, '')
251
+ .toLowerCase();
252
+ /** Tronque à max caractères sans couper un mot (sauf s'il est seul). Pure. */
253
+ const cut = (s, max) => {
254
+ if (s.length <= max)
255
+ return s;
256
+ const at = s.lastIndexOf('_', max);
257
+ return (at > 10 ? s.slice(0, at) : s.slice(0, max)).replace(/_+$/, '');
258
+ };
259
+ /**
260
+ * Nom proposé d'après ce qui a changé (jamais d'après les premiers objets vus) : modifie_observation_enregistrer,
261
+ * cree_table_releves, supprime_mx_calcul_07, modifie_droits_auteur_invitable, modifie_3_fonctions, modifie_5_objets.
262
+ * snake_case, sans schéma public ni pg_catalog, 60 caractères au plus. Pure.
263
+ */
264
+ const suggestName = (items, max = 60) => {
265
+ if (!items.length)
266
+ return '';
267
+ const changes = new Set(items.map((i) => i.change));
268
+ const verb = changes.size === 1 ? VERB[items[0].change] : 'modifie';
269
+ const label = (i) => (i.schema && i.schema !== 'public' ? `${i.schema}_${i.name}` : i.name);
270
+ const names = new Set(items.map(label));
271
+ const types = new Set(items.map((i) => i.type));
272
+ if (names.size === 1) {
273
+ const i = items[0];
274
+ // Seulement les droits ou le commentaire d'une fonction : dit tel quel
275
+ const only = items.length === 1 && i.change === 'modified' && i.aspects?.length === 1 && i.aspects[0] !== 'definition' ? { grants: 'droits', comment: 'commentaire', owner: 'proprietaire' }[i.aspects[0]] : '';
276
+ const word = only || (TYPE[i.type]?.[0] ?? snake(i.type));
277
+ const over = items.length > 1 && types.size === 1 ? `_${items.length}_surcharges` : '';
278
+ return cut(snake([verb, word, label(i)].filter(Boolean).join('_')) + over, max);
279
+ }
280
+ const plural = types.size === 1 ? (TYPE[[...types][0]]?.[1] ?? 'objets') : 'objets';
281
+ return cut(snake(`${verb}_${items.length}_${plural}`), max);
282
+ };
283
+ exports.suggestName = suggestName;
@@ -19,7 +19,7 @@ const fs = require('fs');
19
19
  const path = require('path');
20
20
  const zlib = require('zlib');
21
21
 
22
- const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'variables', 'types'];
22
+ const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'connections', 'variables', 'types'];
23
23
  const FILES = ['seed.sql', 'config.toml'];
24
24
  const NEVER = [/^secrets\.toml$/i, /^\.env$/i, /^\.env\..*/i, /^\.DS_Store$/, /^Thumbs\.db$/i, /^desktop\.ini$/i, /~$/, /\.swp$/];
25
25
  const SKIP_DIRS = new Set(['node_modules', '.git', 'data', 'backups', '.cache']);
@@ -0,0 +1,30 @@
1
+ // Service de sortie de l'engine (poad-egress, engine 0.69.0+) : [egress] de poad/config.toml
2
+ //
3
+ // [egress]
4
+ // mode = "free" # défaut en local : tout hôte public ; "declared" : allow et les hôtes des connexions seulement
5
+ // allow = ["api.github.com", "*.data.gouv.fr"]
6
+ //
7
+ // Les adresses internes sont toujours refusées, quel que soit le mode.
8
+ const MODES = ['free', 'declared'];
9
+ const HOST_RE = /^(\*\.)?[a-z0-9]([a-z0-9-]{0,62}\.)*[a-z0-9-]{1,63}$/i;
10
+
11
+ /** Réglage [egress] lu et vérifié : { mode, allow } ou { error }. Pure. */
12
+ const settings = (config) => {
13
+ const e = (config && config.egress) || {};
14
+ const mode = e.mode === undefined ? 'free' : String(e.mode);
15
+ if (!MODES.includes(mode)) return { error: `[egress] mode: "free" or "declared" (got "${mode}")` };
16
+ const allow = e.allow === undefined ? [] : Array.isArray(e.allow) ? e.allow.map(String) : null;
17
+ if (!allow) return { error: '[egress] allow: a list of host names, like ["api.github.com", "*.data.gouv.fr"]' };
18
+ const bad = allow.find((h) => !HOST_RE.test(h));
19
+ if (bad) return { error: `[egress] allow: "${bad}" is not a host name` };
20
+ return { mode, allow };
21
+ };
22
+
23
+ /** Variables de l'engine ; un réglage invalide : mode declared sans liste (sûr), le message est donné par start */
24
+ const engineEnv = (config) => {
25
+ const s = settings(config);
26
+ if (s.error) return ['EGRESS_MODE=declared'];
27
+ return [`EGRESS_MODE=${s.mode}`, ...(s.allow.length ? [`EGRESS_ALLOW=${s.allow.join(',')}`] : [])];
28
+ };
29
+
30
+ module.exports = { settings, engineEnv, MODES };