poad 2.63.0 → 2.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ // poad auth import : lecture du fichier, doublons, lots, envoi, bilan (utils/auth-import.js)
2
+ const { test } = require('node:test');
3
+ const assert = require('node:assert');
4
+ const imp = require('../utils/auth-import');
5
+
6
+ const HASH = '$2a$10$' + 'a'.repeat(53);
7
+
8
+ test('parseFile: CSV with header, quotes, semicolons, JSON cells; empty cells left out', () => {
9
+ const f = imp.parseFile('users.csv', `email;password_hash;user_metadata;email_verified\r\nA@x.test;${HASH};"{""name"":""A; B""}";true\r\n\r\nb@x.test;;;\n`);
10
+ assert.strictEqual(f.format, 'csv');
11
+ assert.deepStrictEqual(f.rows, [{ email: 'A@x.test', password_hash: HASH, user_metadata: '{"name":"A; B"}', email_verified: 'true' }, { email: 'b@x.test' }]);
12
+ assert.deepStrictEqual(f.lines, [2, 4]);
13
+ });
14
+
15
+ test('parseFile: JSON list, { users }, JSON Lines', () => {
16
+ assert.strictEqual(imp.parseFile('a.json', '[{"email":"a@x.test"}]').rows.length, 1);
17
+ assert.strictEqual(imp.parseFile('a.json', '{"users":[{"email":"a@x.test"},{"email":"b@x.test"}]}').rows.length, 2);
18
+ assert.deepStrictEqual(imp.parseFile('a.jsonl', '{"email":"a@x.test"}\n\n{"email":"b@x.test"}').lines, [1, 3]);
19
+ });
20
+
21
+ test('parseFile: readable errors that never quote the file (a hash may be in it)', () => {
22
+ const bad = [
23
+ ['a.json', `[{"email":"a@x.test","password_hash":"${HASH}"`],
24
+ ['a.jsonl', `{"email":"a@x.test"}\n{"password_hash":"${HASH}"`],
25
+ ['a.csv', `email,password_hash\na@x.test,"${HASH}`],
26
+ ];
27
+ for (const [name, text] of bad) {
28
+ assert.throws(() => imp.parseFile(name, text), (e) => !e.message.includes(HASH) && e.exit === 2);
29
+ }
30
+ assert.throws(() => imp.parseFile('a.csv', 'mail\nx'), /"email" column/);
31
+ assert.throws(() => imp.parseFile('a.json', '{"rows":[]}'), /list of accounts/);
32
+ assert.throws(() => imp.parseFile('a.csv', ' '), /empty/);
33
+ });
34
+
35
+ test('splitDuplicates: the first line counts, whatever the case', () => {
36
+ const { keep, duplicates } = imp.splitDuplicates({ rows: [{ email: 'A@x.test' }, { email: 'b@x.test' }, { email: 'a@X.test ' }], lines: [2, 3, 4] });
37
+ assert.deepStrictEqual(keep.map((k) => k.line), [2, 3]);
38
+ assert.deepStrictEqual(duplicates, [{ line: 4, email: 'a@x.test', status: 'invalid', reason: 'duplicate email in the file' }]);
39
+ });
40
+
41
+ test('run: batches of BATCH lines, results mapped back to file lines, summary', async () => {
42
+ const rows = Array.from({ length: imp.BATCH + 2 }, (_, i) => ({ email: `u${i}@x.test` }));
43
+ const sent = [];
44
+ const send = async (body) => {
45
+ sent.push(body);
46
+ return { results: body.users.map((u, index) => ({ index, email: u.email, status: u.email === 'u1@x.test' ? 'exists' : 'created', email_verified: body.trust_verified })) };
47
+ };
48
+ const { results, summary } = await imp.run({ rows, lines: rows.map((_, i) => i + 2) }, { send, trustVerified: true });
49
+ assert.deepStrictEqual(sent.map((b) => b.users.length), [imp.BATCH, 2]);
50
+ assert.ok(sent.every((b) => b.dry_run === false && b.trust_verified === true && b.send_confirmation === false));
51
+ assert.strictEqual(results[imp.BATCH].line, imp.BATCH + 2);
52
+ assert.deepStrictEqual(summary, { total: imp.BATCH + 2, created: imp.BATCH + 1, would_create: 0, exists: 1, invalid: 0, failed: 0, verified: imp.BATCH + 1, verified_ignored: 0, confirmations_sent: 0, confirmations_failed: 0, confirmations_to_send: 0 });
53
+ });
54
+
55
+ test('run: a refused batch marks its lines and the following ones failed, with the reason', async () => {
56
+ const rows = Array.from({ length: imp.BATCH * 2 }, (_, i) => ({ email: `u${i}@x.test` }));
57
+ let calls = 0;
58
+ const send = async () => {
59
+ calls++;
60
+ throw new Error('HTTP 401');
61
+ };
62
+ const { summary, results } = await imp.run({ rows, lines: rows.map((_, i) => i + 1) }, { send });
63
+ assert.strictEqual(calls, 1);
64
+ assert.strictEqual(summary.failed, imp.BATCH * 2);
65
+ assert.match(results[0].reason, /HTTP 401/);
66
+ assert.match(results[imp.BATCH].reason, /not sent: HTTP 401/);
67
+ });
68
+
69
+ test('authClient: posts to /auth/v1/admin/users/import with the key; 404 means an older engine', async () => {
70
+ const calls = [];
71
+ const fake = async (url, init) => {
72
+ calls.push({ url, init });
73
+ return { status: 200, text: async () => JSON.stringify({ results: [] }) };
74
+ };
75
+ const send = imp.authClient({ base: 'http://localhost:8000', key: 'service-key' }, { fetch: fake });
76
+ await send({ users: [], dry_run: true });
77
+ assert.strictEqual(calls[0].url, 'http://localhost:8000/auth/v1/admin/users/import');
78
+ assert.strictEqual(calls[0].init.headers.authorization, 'Bearer service-key');
79
+ assert.strictEqual(calls[0].init.headers.apikey, 'service-key');
80
+ const old = imp.authClient({ base: 'http://x', key: 'k' }, { fetch: async () => ({ status: 404, text: async () => '{}' }) });
81
+ await assert.rejects(old({ users: [] }), /auth 0\.13\.0 or later/);
82
+ const refused = imp.authClient({ base: 'http://x', key: 'k' }, { fetch: async () => ({ status: 400, text: async () => '{"msg":"users must be an array of accounts"}' }) });
83
+ await assert.rejects(refused({}), /refused the import: users must be an array/);
84
+ });
85
+
86
+ test('authClient: a poad.io token is renewed a minute before it expires', async () => {
87
+ let renewed = 0;
88
+ const renew = { first: new Date(Date.now() + 30000).toISOString(), next: async () => (renewed++, { token: 't2', anon_key: 'anon', expires_at: new Date(Date.now() + 900000).toISOString() }) };
89
+ const seen = [];
90
+ const send = imp.authClient({ base: 'https://p.poad.io', key: 't1', apikey: 'anon', renew }, { fetch: async (u, i) => (seen.push(i.headers.authorization), { status: 200, text: async () => '{"results":[]}' }) });
91
+ await send({ users: [] });
92
+ await send({ users: [] });
93
+ assert.strictEqual(renewed, 1);
94
+ assert.deepStrictEqual(seen, ['Bearer t2', 'Bearer t2']);
95
+ });
96
+
97
+ test('run: --send-confirmation is passed on; sent, failed and ignored verified columns are counted', async () => {
98
+ const rows = [{ email: 'a@x.test', email_verified: 'true' }, { email: 'b@x.test' }, { email: 'c@x.test' }];
99
+ const seen = [];
100
+ const send = async (body) => {
101
+ seen.push(body.send_confirmation);
102
+ return { results: [
103
+ { index: 0, email: 'a@x.test', status: 'created', email_verified: false, verified_ignored: true, confirmation: 'sent' },
104
+ { index: 1, email: 'b@x.test', status: 'created', email_verified: false, confirmation: 'sent' },
105
+ { index: 2, email: 'c@x.test', status: 'created', email_verified: false, confirmation: 'failed' },
106
+ ] };
107
+ };
108
+ const { summary } = await imp.run({ rows, lines: [2, 3, 4] }, { send, sendConfirmation: true });
109
+ assert.deepStrictEqual(seen, [true]);
110
+ assert.strictEqual(summary.confirmations_sent, 2);
111
+ assert.strictEqual(summary.confirmations_failed, 1);
112
+ assert.strictEqual(summary.verified_ignored, 1);
113
+ });
@@ -616,3 +616,4 @@ test('options : valeur manquante et option inconnue -> code 2', async (t) => {
616
616
  assert.strictEqual(u.status, 2);
617
617
  assert.strictEqual(jsonOf(u).error.code, 'usage');
618
618
  });
619
+
@@ -0,0 +1,24 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const { serviceRoleTimeout, engineEnv } = require('../utils/data');
4
+
5
+ test('data : sans réglage, rien n’est passé (défaut de l’engine, 120 s)', () => {
6
+ assert.deepStrictEqual(engineEnv({}), []);
7
+ assert.deepStrictEqual(engineEnv({ data: { schemas: ['public'] } }), []);
8
+ });
9
+
10
+ test('data : service_role_statement_timeout de config.toml, normalisé', () => {
11
+ assert.deepStrictEqual(engineEnv({ data: { service_role_statement_timeout: 300 } }), ['POAD_DATA_STATEMENT_TIMEOUT_SERVICE_ROLE=300s', 'POAD_GATEWAY_SERVICE_ROLE_TIMEOUT=300s']);
12
+ assert.deepStrictEqual(engineEnv({ data: { service_role_statement_timeout: 0 } }), ['POAD_DATA_STATEMENT_TIMEOUT_SERVICE_ROLE=0s', 'POAD_GATEWAY_SERVICE_ROLE_TIMEOUT=0s']);
13
+ assert.deepStrictEqual(serviceRoleTimeout({ data: { service_role_statement_timeout: ' 2MIN ' } }), { value: '2min' });
14
+ assert.deepStrictEqual(serviceRoleTimeout({ data: { service_role_statement_timeout: '500ms' } }), { value: '500ms' });
15
+ });
16
+
17
+ test('data : une valeur qui n’est pas une durée est écartée, avec un avertissement', () => {
18
+ for (const bad of ['-1', '1.5', '2 days', '25h', 'vite', '10s; drop table x']) {
19
+ const r = serviceRoleTimeout({ data: { service_role_statement_timeout: bad } });
20
+ assert.strictEqual(r.value, null, bad);
21
+ assert.match(r.warning, /is not a duration/);
22
+ assert.deepStrictEqual(engineEnv({ data: { service_role_statement_timeout: bad } }), []);
23
+ }
24
+ });
@@ -0,0 +1,108 @@
1
+ // Dépendances npm des fonctions envoyées par poad deploy : seuls les fichiers atteints
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { traceDependencies, importsOf, targetsOf } = require('../utils/cloud/deps');
8
+
9
+ const write = (p, s) => {
10
+ fs.mkdirSync(path.dirname(p), { recursive: true });
11
+ fs.writeFileSync(p, s);
12
+ };
13
+
14
+ function fixture(t) {
15
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-deps-'));
16
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
17
+ const fn = path.join(root, 'poad', 'functions');
18
+ const nm = path.join(fn, 'node_modules');
19
+ // CommonJS à un fichier principal, qui requiert un fichier voisin ; README et tests jamais envoyés
20
+ write(path.join(nm, 'cjs', 'package.json'), JSON.stringify({ name: 'cjs', version: '1.0.0', main: 'index.js', scripts: { postinstall: 'x' }, devDependencies: { a: '1' } }));
21
+ write(path.join(nm, 'cjs', 'index.js'), "module.exports = require('./lib/a');");
22
+ write(path.join(nm, 'cjs', 'lib', 'a.js'), "const b = require('nested'); module.exports = 1;");
23
+ write(path.join(nm, 'cjs', 'lib', 'unused.js'), 'module.exports = 2;');
24
+ write(path.join(nm, 'cjs', 'README.md'), '#');
25
+ write(path.join(nm, 'cjs', 'bin', 'tool.sh'), '#!/bin/sh');
26
+ // Version imbriquée (conflit de versions) : prise dans node_modules du paquet
27
+ write(path.join(nm, 'cjs', 'node_modules', 'nested', 'package.json'), JSON.stringify({ name: 'nested', version: '2.0.0', main: 'n.js' }));
28
+ write(path.join(nm, 'cjs', 'node_modules', 'nested', 'n.js'), 'module.exports = 2;');
29
+ write(path.join(nm, 'nested', 'package.json'), JSON.stringify({ name: 'nested', version: '1.0.0', main: 'n.js' }));
30
+ write(path.join(nm, 'nested', 'n.js'), 'module.exports = 1;');
31
+ // exports conditionnels, sous-chemin, motif, import « # » et module WebAssembly
32
+ write(path.join(nm, '@s', 'multi', 'package.json'), JSON.stringify({
33
+ name: '@s/multi', version: '1.0.0', type: 'module',
34
+ exports: { '.': { node: './node.js', workerd: './workerd.js', default: './default.js' }, './sub': { worker: './sub-w.js', default: './sub-d.js' }, './util/*': './lib/util/*.js', './codec.wasm': './codec.wasm' },
35
+ imports: { '#internal': './lib/internal.js' },
36
+ }));
37
+ write(path.join(nm, '@s', 'multi', 'workerd.js'), "import x from '#internal'; import m from './codec.wasm'; export default x;");
38
+ write(path.join(nm, '@s', 'multi', 'node.js'), 'export default 0;');
39
+ write(path.join(nm, '@s', 'multi', 'default.js'), 'export default 0;');
40
+ write(path.join(nm, '@s', 'multi', 'sub-w.js'), 'export default 1;');
41
+ write(path.join(nm, '@s', 'multi', 'sub-d.js'), 'export default 1;');
42
+ write(path.join(nm, '@s', 'multi', 'lib', 'util', 'pad.js'), 'export default 1;');
43
+ write(path.join(nm, '@s', 'multi', 'lib', 'util', 'other.js'), 'export default 1;');
44
+ write(path.join(nm, '@s', 'multi', 'lib', 'internal.js'), 'export default 1;');
45
+ write(path.join(nm, '@s', 'multi', 'codec.wasm'), Buffer.from([0, 0x61, 0x73, 0x6d]));
46
+ write(path.join(nm, '@s', 'multi', 'native.node'), 'ELF');
47
+ // Paquet installé mais jamais importé : rien n'en part
48
+ write(path.join(nm, 'unused-pkg', 'package.json'), JSON.stringify({ name: 'unused-pkg', main: 'i.js' }));
49
+ write(path.join(nm, 'unused-pkg', 'i.js'), '1');
50
+ write(path.join(nm, '.bin', 'tool'), 'x');
51
+ // Les fonctions
52
+ write(path.join(fn, 'a', 'index.ts'), "import cjs from 'cjs';\nimport { x } from '../_shared/util.ts';\nimport { poadFromRequest } from '@poadio/functions';\nimport { Buffer } from 'node:buffer';\nexport default { fetch: () => new Response(String(cjs + x)) };");
53
+ write(path.join(fn, '_shared', 'util.ts'), "export { default as x } from '@s/multi';\nexport * from '@s/multi/sub';\nimport pad from '@s/multi/util/pad';\nimport w from '@s/multi/codec.wasm';");
54
+ write(path.join(fn, 'b', 'index.js'), "const missing = require('not-installed'); import('events');");
55
+ return { root, fn };
56
+ }
57
+
58
+ test('deps : seuls les fichiers atteints (conditions workerd d’abord, comme l’engine), package.json réduits, versions imbriquées, wasm', (t) => {
59
+ const { fn } = fixture(t);
60
+ const r = traceDependencies(fn);
61
+ assert.deepStrictEqual(r.files.map((f) => f.rel), [
62
+ 'node_modules/@s/multi/codec.wasm',
63
+ 'node_modules/@s/multi/lib/internal.js',
64
+ 'node_modules/@s/multi/lib/util/pad.js',
65
+ 'node_modules/@s/multi/package.json',
66
+ 'node_modules/@s/multi/sub-w.js',
67
+ 'node_modules/@s/multi/workerd.js',
68
+ 'node_modules/cjs/index.js',
69
+ 'node_modules/cjs/lib/a.js',
70
+ 'node_modules/cjs/node_modules/nested/n.js',
71
+ 'node_modules/cjs/node_modules/nested/package.json',
72
+ 'node_modules/cjs/package.json',
73
+ ]);
74
+ assert.deepStrictEqual(r.packages, ['@s/multi', 'cjs', 'nested']);
75
+ const pkg = JSON.parse(r.files.find((f) => f.rel === 'node_modules/cjs/package.json').data);
76
+ assert.deepStrictEqual(pkg, { name: 'cjs', version: '1.0.0', main: 'index.js' });
77
+ // Paquet absent : nommé avec le fichier qui l'importe ; module de Node.js : jamais signalé
78
+ assert.deepStrictEqual(r.missing, [{ spec: 'not-installed', from: 'b/index.js' }]);
79
+ });
80
+
81
+ test('deps : paquet installé au-dessus de poad/functions : signalé, pas envoyé', (t) => {
82
+ const { root, fn } = fixture(t);
83
+ write(path.join(root, 'node_modules', 'up', 'package.json'), JSON.stringify({ name: 'up', main: 'i.js' }));
84
+ write(path.join(root, 'node_modules', 'up', 'i.js'), '1');
85
+ write(path.join(fn, 'c', 'index.ts'), "import up from 'up';");
86
+ const r = traceDependencies(fn);
87
+ assert.deepStrictEqual(r.outside, ['up']);
88
+ assert.ok(!r.files.some((f) => f.rel.includes('up/')));
89
+ });
90
+
91
+ test('deps : archive de poad deploy, rien d’autre de node_modules', (t) => {
92
+ const { root } = fixture(t);
93
+ fs.writeFileSync(path.join(root, 'poad', 'config.toml'), 'project_id = "x"\n');
94
+ const b = require('../utils/cloud/bundle').build(path.join(root, 'poad'));
95
+ const nmFiles = b.files.map((f) => f.path).filter((p) => p.includes('node_modules'));
96
+ assert.strictEqual(nmFiles.length, 11);
97
+ assert.ok(nmFiles.every((p) => p.startsWith('functions/node_modules/')));
98
+ assert.ok(!nmFiles.some((p) => /README|\.sh$|\.node$|unused|\.bin/.test(p)));
99
+ assert.deepStrictEqual(b.deps.packages, ['@s/multi', 'cjs', 'nested']);
100
+ });
101
+
102
+ test('deps : relevé des imports et cibles d’exports', () => {
103
+ assert.deepStrictEqual(importsOf("import a from 'a'; import type { B } from \"b\"; export * from './c'; import './d'; const e = await import('e'); require('f');").map((i) => i.spec), ['a', 'b', './c', './d', 'e', 'f']);
104
+ assert.deepStrictEqual(targetsOf({ '.': [{ worker: './w.js' }, './d.js'] }, '.', ['worker']), ['./w.js']);
105
+ assert.deepStrictEqual(targetsOf('./main.js', '.', []), ['./main.js']);
106
+ assert.deepStrictEqual(targetsOf({ import: './m.js', require: './c.js' }, '.', ['require']), ['./c.js']);
107
+ assert.deepStrictEqual(targetsOf({ './x/*.js': './dist/x/*.js' }, './x/a/b.js', []), ['./dist/x/a/b.js']);
108
+ });
@@ -0,0 +1,226 @@
1
+ // poad source import, poad db import, et l'envoi des fichiers d'import (TUS reprenable, sinon simple), contre un
2
+ // faux engine (stockage + meta + flows) ; --project : la cible est donnée par deps.cloudTarget (pas de poad.io).
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const fs = require('fs');
6
+ const http = require('http');
7
+ const path = require('path');
8
+ const { tmpdir } = require('./helpers');
9
+ const { uploadImportFile } = require('../utils/import-upload');
10
+ const dbImport = require('../project/db/import');
11
+ const source = require('../project/source');
12
+
13
+ // Envois en cours gardés pour reprise : dans un dossier jetable, jamais ~/.poad
14
+ process.env.POAD_UPLOADS_FILE = path.join(require('os').tmpdir(), `poad-import-test-${process.pid}.json`);
15
+
16
+ const KEY = 'service-role-key-NEVER-SHOWN';
17
+ const RUN = '7c2e1d90-4b3a-4f1e-8d2c-5a6b7c8d9e0f';
18
+
19
+ /** Faux engine : tus (bool), failOnce (un PATCH en 500), et les routes meta/flows utiles */
20
+ function fakeEngine(t, opts = {}) {
21
+ const state = { requests: [], objects: new Map(), uploads: new Map(), failed: false, polls: 0, imported: false };
22
+ const send = (res, status, body, headers = {}) => {
23
+ res.writeHead(status, { 'content-type': 'application/json', ...headers });
24
+ res.end(body === undefined ? '' : JSON.stringify(body));
25
+ };
26
+ const server = http.createServer((req, res) => {
27
+ const chunks = [];
28
+ req.on('data', (c) => chunks.push(c));
29
+ req.on('end', () => {
30
+ const raw = Buffer.concat(chunks);
31
+ const url = new URL(req.url, 'http://x');
32
+ const p = url.pathname;
33
+ state.requests.push({ method: req.method, path: p, headers: req.headers, size: raw.length });
34
+ if (req.headers.authorization !== `Bearer ${KEY}`) return send(res, 401, { error: { message: 'bad key' } });
35
+ const body = req.headers['content-type'] === 'application/json' && raw.length ? JSON.parse(raw.toString('utf8')) : null;
36
+ // Stockage
37
+ if (p === '/storage/v1/upload/resumable' && req.method === 'POST') {
38
+ if (!opts.tus) return send(res, 404, { error: { message: 'not found' } });
39
+ const meta = Object.fromEntries(req.headers['upload-metadata'].split(',').map((x) => x.split(' ')).map(([k, v]) => [k, Buffer.from(v, 'base64').toString('utf8')]));
40
+ const id = `0f8fad5b-d9cb-469f-a165-${String(708677289500 + state.uploads.size).padStart(12, '0')}`;
41
+ state.uploads.set(id, { meta, length: Number(req.headers['upload-length']), data: Buffer.alloc(0) });
42
+ return send(res, 201, undefined, { location: `http://elsewhere:9999/storage/v1/upload/resumable/${id}`, 'tus-resumable': '1.0.0' });
43
+ }
44
+ const m = /^\/storage\/v1\/upload\/resumable\/([\w-]+)$/.exec(p);
45
+ if (m) {
46
+ const u = state.uploads.get(m[1]);
47
+ if (req.method === 'HEAD') return send(res, 200, undefined, { 'upload-offset': String(u.data.length), 'upload-length': String(u.length) });
48
+ if (opts.failOnce && !state.failed && u.data.length > 0) {
49
+ // Coupure au milieu : la moitié du morceau est gardée, la réponse perdue
50
+ state.failed = true;
51
+ u.data = Buffer.concat([u.data, raw.subarray(0, raw.length >> 1)]);
52
+ return send(res, 500, { error: { message: 'boom' } });
53
+ }
54
+ if (Number(req.headers['upload-offset']) !== u.data.length) return send(res, 409, { error: { message: 'offset' } });
55
+ u.data = Buffer.concat([u.data, raw]);
56
+ if (u.data.length === u.length) state.objects.set(`${u.meta.bucketName}/${u.meta.objectName}`, u.data);
57
+ return send(res, 204, undefined, { 'upload-offset': String(u.data.length) });
58
+ }
59
+ if (p.startsWith('/storage/v1/object/') && req.method === 'PUT') {
60
+ state.objects.set(decodeURIComponent(p.slice('/storage/v1/object/'.length)), raw);
61
+ return send(res, 200, { Key: p });
62
+ }
63
+ // meta
64
+ if (p === '/meta/v1/sources/uploads') return send(res, 200, { bucket: 'poad-sources', object: `${body.kind === 'sql' ? 'sql' : 'sources'}/x/${body.file_name || 'communes.csv'}`, path: `poad-sources/${body.kind === 'sql' ? 'sql' : 'sources'}/x/${body.file_name || 'communes.csv'}`, max_bytes: null });
65
+ if (p === '/meta/v1/sql/import/preview') {
66
+ const refused = opts.refused ? [{ line: 3, code: 'role_change', message: 'CREATE ROLE : refusé' }] : [];
67
+ return send(res, 200, { path: body.path, bytes: 1000, statements: 4, by_kind: { data: 2, structure: 2, session: 0, query: 0, ignored: 0 }, copy_rows: 2, tables: [{ name: 'public.villes', actions: ['create table', 'copy'], statements: 2, rows: 2 }], tables_more: 0, structure: true, refused, refused_total: refused.length, ignored: [] });
68
+ }
69
+ if (p === '/meta/v1/sql/import' && req.method === 'POST') {
70
+ state.imported = true;
71
+ return send(res, 202, { id: 'job1', status: 'analyzing', statements_done: 0, statements_total: null, rows_copied: 0 });
72
+ }
73
+ if (p === '/meta/v1/sql/import/job1') return send(res, 200, ++state.polls < 2 ? { id: 'job1', status: 'running', statements_done: 1, statements_total: 4, rows_copied: 0 } : { id: 'job1', status: 'completed', statements_done: 4, statements_total: 4, rows_copied: 2, structure: true, duration_ms: 1200, error: null });
74
+ if (p === '/meta/v1/sources' && req.method === 'GET') return send(res, 200, { sources: opts.known ? [{ name: 'communes', origin: { kind: 'upload', path: 'poad-sources/sources/x/communes.csv' } }] : [] });
75
+ if (p === '/meta/v1/sources/sample') return send(res, 200, { url: '', path: body.path, format: 'csv', root: null, csv: { delimiter: ';', header: true }, fields: [{ path: 'code', type: 'text' }, { path: 'nom', type: 'text' }], rows: [], total: 2, sampled: 2 });
76
+ if (p === '/meta/v1/sources/propose') return send(res, 200, { kind: 'new', table: `public.${body.table}`, table_exists: false, columns: [{ name: 'code', from: 'code', type: 'text', include: true }, { name: 'nom', from: 'nom', type: 'text', include: true }], key: ['code'] });
77
+ if (p === '/meta/v1/sources' && req.method === 'POST') {
78
+ state.draft = body.draft;
79
+ const n = body.draft.name || body.draft.table.replace(/^public\./, '');
80
+ return send(res, 201, { name: n, file: `poad/sources/${n}.yaml`, run_id: RUN });
81
+ }
82
+ if (p === '/meta/v1/sources/communes/refresh') return send(res, 202, { run_id: RUN, flow: 'source-communes' });
83
+ if (p === `/flows/v1/runs/${RUN}`) return send(res, 200, { status: 'completed', duration_ms: 3000, steps: [{ step_id: 'appliquer', name: 'appliquer', status: 'done', output: { rows: [{ bilan: { received: 2, inserted: 2, updated: 0, deleted: 0, rows: 2 } }] } }] });
84
+ return send(res, 404, { error: { message: `no route ${req.method} ${p}` } });
85
+ });
86
+ });
87
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => {
88
+ t.after(() => server.close());
89
+ resolve({ base: `http://127.0.0.1:${server.address().port}`, state });
90
+ }));
91
+ }
92
+
93
+ const auth = async () => ({ apikey: KEY, authorization: `Bearer ${KEY}` });
94
+ const capture = async (fn) => {
95
+ const lines = [];
96
+ const log = console.log;
97
+ console.log = (...a) => lines.push(a.join(' '));
98
+ const code = process.exitCode;
99
+ process.exitCode = 0;
100
+ try {
101
+ await fn();
102
+ } finally {
103
+ console.log = log;
104
+ }
105
+ const exit = process.exitCode;
106
+ process.exitCode = code;
107
+ return { out: lines.join('\n').replace(/\x1b\[[0-9;]*m/g, ''), exit };
108
+ };
109
+
110
+ test('envoi reprenable : morceaux de 6 Mo, coupure au milieu reprise à l’octet (HEAD), fichier identique', async (t) => {
111
+ const { base, state } = await fakeEngine(t, { tus: true, failOnce: true });
112
+ const dir = tmpdir(t);
113
+ const file = path.join(dir, 'gros.csv');
114
+ const content = Buffer.alloc(14 * 1024 * 1024 + 123, 'a');
115
+ for (let i = 0; i < content.length; i += 4096) content[i] = 0x30 + ((i >> 12) % 10);
116
+ fs.writeFileSync(file, content);
117
+ const r = await uploadImportFile({ base, auth, file, target: { bucket: 'poad-sources', object: 'sources/x/gros.csv' }, sleep: async () => {} });
118
+ assert.strictEqual(r.method, 'tus');
119
+ assert.ok(state.objects.get('poad-sources/sources/x/gros.csv').equals(content));
120
+ assert.ok(state.requests.some((q) => q.method === 'HEAD'));
121
+ assert.ok(state.requests.filter((q) => q.method === 'PATCH').every((q) => q.size <= 6 * 1024 * 1024));
122
+ // Location absolue vers un autre hôte : seul l'identifiant compte, l'envoi reste sur le stockage visé
123
+ assert.ok(state.requests.filter((q) => q.method === 'PATCH').length >= 3);
124
+ const created = state.requests.find((q) => q.method === 'POST' && q.path === '/storage/v1/upload/resumable');
125
+ assert.match(created.headers['upload-metadata'], /^bucketName cG9hZC1zb3VyY2Vz,objectName c291cmNlcy94L2dyb3MuY3N2,contentType dGV4dC9jc3Y=,cacheControl /);
126
+ });
127
+
128
+ test('sans envoi reprenable sur le stockage : envoi simple en flux (PUT)', async (t) => {
129
+ const { base, state } = await fakeEngine(t, { tus: false });
130
+ const file = path.join(tmpdir(t), 'petit.json');
131
+ fs.writeFileSync(file, '[{"a":1}]');
132
+ const r = await uploadImportFile({ base, auth, file, target: { bucket: 'poad-sources', object: 'sources/x/petit.json' } });
133
+ assert.strictEqual(r.method, 'simple');
134
+ assert.strictEqual(state.objects.get('poad-sources/sources/x/petit.json').toString(), '[{"a":1}]');
135
+ assert.strictEqual(state.requests.find((q) => q.method === 'PUT').headers['content-type'], 'application/json');
136
+ });
137
+
138
+ const cloudDeps = (base) => ({ cloudTarget: async () => ({ base, key: KEY, apikey: KEY, label: 'test engine' }), sleep: async () => {} });
139
+
140
+ test('poad db import : aperçu refusé → rien n’est lancé, code 1', async (t) => {
141
+ const { base, state } = await fakeEngine(t, { tus: true, refused: true });
142
+ const file = path.join(tmpdir(t), 'mauvais.sql');
143
+ fs.writeFileSync(file, 'create role x;');
144
+ const { out, exit } = await capture(() => dbImport.main({}, [file, '--project', 'p1', '--yes'], cloudDeps(base)));
145
+ assert.strictEqual(exit, 1);
146
+ assert.match(out, /line 3: CREATE ROLE : refusé/);
147
+ assert.match(out, /Refused before running anything/);
148
+ assert.strictEqual(state.imported, false);
149
+ });
150
+
151
+ test('poad db import --yes : envoi, aperçu, import suivi jusqu’au bilan ; la clé n’est jamais affichée', async (t) => {
152
+ const { base, state } = await fakeEngine(t, { tus: true });
153
+ const file = path.join(tmpdir(t), 'villes.sql');
154
+ fs.writeFileSync(file, 'create table villes(id int);');
155
+ const { out, exit } = await capture(() => dbImport.main({}, [file, '--project', 'p1', '--yes'], cloudDeps(base)));
156
+ assert.strictEqual(exit, 0, out);
157
+ assert.match(out, /4 statement\(s\): 2 data, 2 structure · 2 row\(s\) by COPY/);
158
+ assert.match(out, /completed .*4 statement\(s\), 2 row\(s\) by COPY/);
159
+ assert.match(out, /Structure was created/);
160
+ assert.ok(state.imported);
161
+ assert.ok(!out.includes(KEY));
162
+ });
163
+
164
+ test('poad db import hors d’un terminal sans --yes : refus, rien n’est lancé', async (t) => {
165
+ const { base, state } = await fakeEngine(t, { tus: true });
166
+ const file = path.join(tmpdir(t), 'v.sql');
167
+ fs.writeFileSync(file, 'select 1;');
168
+ const tty = process.stdin.isTTY;
169
+ process.stdin.isTTY = false;
170
+ try {
171
+ const { out, exit } = await capture(() => dbImport.main({}, [file, '--project', 'p1'], cloudDeps(base)));
172
+ assert.strictEqual(exit, 2);
173
+ assert.match(out, /confirm with --yes/);
174
+ } finally {
175
+ process.stdin.isTTY = tty;
176
+ }
177
+ assert.strictEqual(state.imported, false);
178
+ });
179
+
180
+ test('poad source import : nouvelle source (échantillon, colonnes, clé), déclaration upload importée, chargement suivi', async (t) => {
181
+ const { base, state } = await fakeEngine(t, { tus: true });
182
+ const file = path.join(tmpdir(t), 'Communes 2026.csv');
183
+ fs.writeFileSync(file, 'code;nom\n01001;A\n01002;B\n');
184
+ const { out, exit } = await capture(() => source.main({}, ['import', file, '--project', 'p1'], cloudDeps(base)));
185
+ assert.strictEqual(exit, 0, out);
186
+ assert.deepStrictEqual(state.draft, {
187
+ mode: 'imported',
188
+ origin: { kind: 'upload', path: 'poad-sources/sources/x/Communes 2026.csv', format: 'csv', csv: { delimiter: ';' } },
189
+ table: 'public.communes_2026',
190
+ existing: false,
191
+ key: ['code'],
192
+ columns: [
193
+ { name: 'code', from: 'code', type: 'text' },
194
+ { name: 'nom', from: 'nom', type: 'text' },
195
+ ],
196
+ });
197
+ assert.match(out, /source communes_2026 poad\/sources\/communes_2026\.yaml/);
198
+ assert.match(out, /completed/);
199
+ });
200
+
201
+ test('poad source import --name : nouvelle version d’une source envoyée (même chemin), puis chargement', async (t) => {
202
+ const { base, state } = await fakeEngine(t, { tus: false, known: true });
203
+ const file = path.join(tmpdir(t), 'communes-v2.csv');
204
+ fs.writeFileSync(file, 'code;nom\n01001;A\n');
205
+ const { out, exit } = await capture(() => source.main({}, ['import', file, '--name', 'communes', '--project', 'p1'], cloudDeps(base)));
206
+ assert.strictEqual(exit, 0, out);
207
+ assert.ok(state.objects.has('poad-sources/sources/x/communes.csv') || [...state.objects.keys()].some((k) => k.endsWith('communes-v2.csv')));
208
+ assert.ok(state.requests.some((q) => q.path === '/meta/v1/sources/communes/refresh'));
209
+ assert.ok(!state.requests.some((q) => q.path === '/meta/v1/sources/sample'));
210
+ });
211
+
212
+ test('poad source import --key-generated : clé générée (sans clé naturelle), refus des combinaisons', async (t) => {
213
+ const { base, state } = await fakeEngine(t, { tus: true });
214
+ const file = path.join(tmpdir(t), 'films.csv');
215
+ fs.writeFileSync(file, ',Title\n0,A\n1,A\n');
216
+ const { out, exit } = await capture(() => source.main({}, ['import', file, '--key-generated', 'hash', '--project', 'p1'], cloudDeps(base)));
217
+ assert.strictEqual(exit, 0, out);
218
+ assert.deepStrictEqual(state.draft.key, { generated: 'hash' });
219
+ assert.match(out, /generated key hash/);
220
+ const bad = await capture(() => source.main({}, ['import', file, '--key-generated', 'random', '--project', 'p1'], cloudDeps(base)));
221
+ assert.strictEqual(bad.exit, 2);
222
+ assert.match(bad.out, /--key-generated: uuid, identity or hash/);
223
+ const both = await capture(() => source.main({}, ['import', file, '--key-generated', 'uuid', '--key', 'Title', '--project', 'p1'], cloudDeps(base)));
224
+ assert.strictEqual(both.exit, 2);
225
+ assert.match(both.out, /not with --key nor --existing/);
226
+ });
package/test/logs.test.js CHANGED
@@ -209,3 +209,15 @@ test('poad logs run=<identifiant qui ressemble à un nombre> : la valeur telle q
209
209
  assert.ok(read.values.includes('3488e382%'), `préfixe passé tel quel : ${JSON.stringify(read.values)}`);
210
210
  assert.strictEqual(process.exitCode || 0, 0);
211
211
  });
212
+
213
+ test('supportsLogs: 0.8.1 and later; an engine that is not a number (local development image) has the log sink', () => {
214
+ const { supportsLogs } = require('../utils/logs');
215
+ assert.strictEqual(supportsLogs({ engine: '0.8.0' }), false);
216
+ assert.strictEqual(supportsLogs({ engine: '0.8.1' }), true);
217
+ assert.strictEqual(supportsLogs({ engine: '0.63.9' }), true);
218
+ assert.strictEqual(supportsLogs({ engine: '0.64.0-authimport' }), true);
219
+ assert.strictEqual(supportsLogs({ engine: 'auth-import-dev' }), true);
220
+ assert.strictEqual(supportsLogs({ engine: 'latest' }), true);
221
+ assert.strictEqual(supportsLogs({ engine: '' }), false);
222
+ assert.strictEqual(supportsLogs({}), false);
223
+ });
@@ -0,0 +1,18 @@
1
+ // Nettoyage des noms (utils/naming.js), même règle que meta (services/meta/src/naming.ts)
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const { cleanIdent } = require('../utils/naming');
5
+
6
+ test('noms nettoyés : accents, espaces, chiffre en tête, mots réservés, 63 octets', () => {
7
+ assert.strictEqual(cleanIdent('Liste des gares'), 'liste_des_gares');
8
+ assert.strictEqual(cleanIdent('Communes Été 2026'), 'communes_ete_2026');
9
+ assert.strictEqual(cleanIdent('Code UIC', 'column'), 'code_uic');
10
+ assert.strictEqual(cleanIdent('Libellé gare', 'column'), 'libelle_gare');
11
+ assert.strictEqual(cleanIdent('2026 mesures'), 't_2026_mesures');
12
+ assert.strictEqual(cleanIdent('2026', 'column'), 'c_2026');
13
+ assert.strictEqual(cleanIdent('User'), 'user_t');
14
+ assert.strictEqual(cleanIdent('order', 'column'), 'order_c');
15
+ assert.strictEqual(cleanIdent(''), 'donnees');
16
+ assert.ok(cleanIdent('é'.repeat(80)).length <= 63);
17
+ assert.strictEqual(cleanIdent('ma-table -- spéciale'), 'ma_table_speciale');
18
+ });