poad 2.76.0 → 2.76.2

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.
@@ -154,7 +154,7 @@ test('code: mirrored paths, plan keeps uncommitted or untracked local files', ()
154
154
 
155
155
  // --- La commande entière : faux poad.io (HTTP) et fausse base (deps.pg) ------------------------------------
156
156
 
157
- function fakeCloud(t, seen) {
157
+ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, events = 200 } = {}) {
158
158
  return new Promise((resolve) => {
159
159
  const server = http.createServer((req, res) => {
160
160
  let body = '';
@@ -162,10 +162,14 @@ function fakeCloud(t, seen) {
162
162
  seen.push({ method: req.method, url: req.url, body });
163
163
  const send = (s, o) => (res.writeHead(s, { 'content-type': 'application/json' }), res.end(JSON.stringify(o)));
164
164
  if (/\/branches$/.test(req.url)) return send(200, [{ name: 'main', kind: 'production' }, { name: 'dev' }]);
165
- if (/\/seeds$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
166
- if (/\/sync-plan$/.test(req.url)) return send(200, { space: { limit: 1024 ** 3, used: 1024 ** 2 } });
165
+ if (/\/seeds(\?.*)?$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
166
+ if (/\/sync-plan$/.test(req.url)) return send(200, { space });
167
167
  if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
168
- if (/\/sync-events$/.test(req.url)) return send(200, { written: JSON.parse(body).lines.length });
168
+ if (/\/sync-events$/.test(req.url)) {
169
+ // poad.io d'avant la 2.76.1 : refuse les lignes par fichier
170
+ if (events === 'old' && JSON.parse(body).lines.some((l) => l.file)) return send(400, { error: { code: 'invalid_events', message: 'ligne : part et outcome attendus' } });
171
+ return send(200, { written: JSON.parse(body).lines.length });
172
+ }
169
173
  send(404, { error: { code: 'not_found', message: 'route inconnue' } });
170
174
  });
171
175
  });
@@ -177,7 +181,7 @@ function fakeCloud(t, seen) {
177
181
  }
178
182
 
179
183
  /** Fausse base : inventaires de la source et de la cible, empreintes, transfert enregistré */
180
- function fakePg(scripts) {
184
+ function fakePg(scripts, { same = false, queries = [] } = {}) {
181
185
  const real = require('../utils/project-sync/pg');
182
186
  const inv = (rows) => ({
183
187
  tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')])],
@@ -191,8 +195,9 @@ function fakePg(scripts) {
191
195
  return {
192
196
  localSide: real.localSide,
193
197
  cloudSide: real.cloudSide,
194
- json: async (container, side, sql) => (sql === P.PROBE_SQL ? { history: true, variables: true, credentials: true, vault: true, auth: ['users'] } : inv(side.kind === 'local' ? 3 : 2)),
198
+ json: async (container, side, sql) => (sql === P.PROBE_SQL ? { history: true, variables: true, credentials: true, vault: true, auth: ['users'] } : inv(side.kind === 'local' || same ? 3 : 2)),
195
199
  query: async (container, side, sql) => {
200
+ queries.push(sql);
196
201
  // Empreintes : la source a trois livres, la cible deux (un remplacé) ; un compte identique
197
202
  const local = side.kind === 'local';
198
203
  const parts = sql.split(/\\echo @@T (\d+)\n/).filter(Boolean);
@@ -200,7 +205,7 @@ function fakePg(scripts) {
200
205
  for (let i = 0; i < parts.length; i += 2) {
201
206
  out += `@@T ${parts[i]}\n`;
202
207
  if (/"auth"\."users"/.test(parts[i + 1])) out += 'u1 h\n';
203
- else out += local ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
208
+ else out += local || same ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
204
209
  }
205
210
  return out;
206
211
  },
@@ -212,14 +217,14 @@ function fakePg(scripts) {
212
217
  };
213
218
  }
214
219
 
215
- async function runCmd(t, args, { tty = false } = {}) {
220
+ async function runCmd(t, args, { tty = false, deps = {}, cloud = {}, pg = {} } = {}) {
216
221
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-pp-'));
217
222
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
218
223
  fs.mkdirSync(path.join(dir, 'poad'));
219
224
  fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "t"\nproject_uuid = "ppuuid1"\nengine = "0.73.1"\n[db]\nport = 1\n[web]\nport = 2\n[cloud]\nproject = "pptest123456"\n');
220
225
  const seen = [];
221
226
  const scripts = [];
222
- const base = await fakeCloud(t, seen);
227
+ const base = await fakeCloud(t, seen, cloud);
223
228
  const saved = { cwd: process.cwd(), api: process.env.POAD_CLOUD_API, tok: process.env.POAD_ACCESS_TOKEN, log: console.log, err: console.error, code: process.exitCode };
224
229
  const printed = [];
225
230
  process.chdir(dir);
@@ -232,8 +237,9 @@ async function runCmd(t, args, { tty = false } = {}) {
232
237
  try {
233
238
  process.exitCode = 0;
234
239
  await require('../utils/project-sync/run').run(args[0], args.slice(1), {
235
- pg: fakePg(scripts),
240
+ pg: fakePg(scripts, pg),
236
241
  started: async () => true,
242
+ ...deps,
237
243
  credentials: async () => ({ user: 'postgres.pptest123456--dev', password: 'pw-never-shown', host: 'db.poad.io', port: () => 5432 }),
238
244
  });
239
245
  return { code: process.exitCode, out: printed.join('\n'), seen, scripts };
@@ -295,3 +301,113 @@ test('poad pull --tables of an unknown table: stopped before anything is written
295
301
  assert.match(r.out, /public\.inconnue not in the source/);
296
302
  assert.strictEqual(r.scripts.length, 0);
297
303
  });
304
+
305
+ // --- 2.76.1 : reprise, place, sauvegarde seulement si la base est écrite --------------------------------------
306
+
307
+ const { fakeStorage, md5 } = require('./fake-storage');
308
+ const storage = require('../utils/storage');
309
+
310
+ async function sides(t, cloudOpts = {}) {
311
+ const local = await fakeStorage(t);
312
+ const cloud = await fakeStorage(t, cloudOpts);
313
+ const deps = {
314
+ localTarget: async () => ({ base: local.base, key: 'svc', label: 'local engine' }),
315
+ cloudTarget: async () => ({ base: cloud.base, key: 'svc', label: 'poad.io pptest123456 (dev)' }),
316
+ client: (x) => storage.client({ base: x.base, key: x.key }),
317
+ sleep: async () => {},
318
+ };
319
+ return { local, cloud, deps };
320
+ }
321
+
322
+ test('poad push: files cut in the middle → summary folded, exit 5, logs per file; run again → only the rest is sent', async (t) => {
323
+ process.env.POAD_UPLOADS_FILE = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'poad-up-')), 'uploads.json');
324
+ const { local, cloud, deps } = await sides(t, { cutAfter: 6 * 1024 * 1024 });
325
+ const big = Buffer.alloc(14 * 1024 * 1024, 7);
326
+ local.put('ressources', 'video.mp4', big, 'video/mp4');
327
+ for (let i = 0; i < 7; i++) local.put('ressources', `doc${i}.txt`, `document ${i}`, 'text/plain');
328
+ // Sept petits fichiers refusés (413), un gros coupé : 8 échecs, 5 montrés
329
+ const client = deps.client;
330
+ deps.client = (x) => {
331
+ const c = client(x);
332
+ if (x.base !== cloud.base) return c;
333
+ const put = c.put;
334
+ c.put = async (b, n, ...rest) => {
335
+ if (/^doc/.test(n) && cloud.cutting !== false) throw Object.assign(new (require('../utils/cloud/api').CloudError)('taille maximale : 4 octets', { status: 413 }), { retriable: false });
336
+ return put(b, n, ...rest);
337
+ };
338
+ return c;
339
+ };
340
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 's3', '--yes'], { deps });
341
+ assert.strictEqual(r.code, 5, r.out);
342
+ const plain = r.out.replace(/\x1b\[[0-9;]*m/g, '');
343
+ assert.match(plain, /✖ 8 file\(s\) failed/);
344
+ assert.match(plain, /and 3 other\(s\)/);
345
+ assert.match(plain, /Run poad push --env dev again \(or poad push --env dev --only s3\) to resume/);
346
+ const ev = JSON.parse(r.seen.find((x) => /sync-events/.test(x.url)).body);
347
+ const files = ev.lines.filter((l) => l.file && l.outcome === 'failed');
348
+ assert.strictEqual(files.length, 8, JSON.stringify(files.slice(0, 12)));
349
+ assert.ok(ev.lines.filter((l) => l.outcome === 'resumed').length <= 1, 'one resume line per file and offset');
350
+ assert.deepStrictEqual(files.find((l) => l.file === 'ressources/video.mp4').reason, 'network');
351
+ assert.ok(files.every((l) => !('error' in l)));
352
+ assert.ok(!cloud.objects.has('ressources/video.mp4'));
353
+
354
+ // Relance : la panne est passée ; le gros fichier reprend à 6 Mio, les petits partent
355
+ cloud.heal();
356
+ cloud.cutting = false;
357
+ const before = cloud.stats.patchBytes;
358
+ const again = await runCmd(t, ['push', '--env', 'dev', '--only', 's3', '--yes'], { deps });
359
+ assert.strictEqual(again.code, 0, again.out);
360
+ assert.strictEqual(cloud.stats.patchBytes - before, 8 * 1024 * 1024, 'only the 8 MiB left');
361
+ assert.match(again.out.replace(/\x1b\[[0-9;]*m/g, ''), /ressources\/video\.mp4: resumed at 6\.0 MB of 14\.0 MB/);
362
+ assert.strictEqual(md5(cloud.objects.get('ressources/video.mp4').body), md5(big));
363
+ const ev2 = JSON.parse(again.seen.find((x) => /sync-events/.test(x.url)).body);
364
+ assert.deepStrictEqual(ev2.lines.filter((l) => l.file).map((l) => [l.file, l.outcome, l.offset]), [['ressources/video.mp4', 'resumed', 6 * 1024 * 1024]]);
365
+ });
366
+
367
+ test('poad push: an older poad.io refusing the lines per file still gets the others', async (t) => {
368
+ const { local, cloud, deps } = await sides(t, { truncate: true });
369
+ local.put('docs', 'a.txt', 'contenu');
370
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 's3', '--yes'], { deps, cloud: { events: 'old' } });
371
+ assert.strictEqual(r.code, 5);
372
+ const posts = r.seen.filter((x) => /sync-events/.test(x.url)).map((x) => JSON.parse(x.body));
373
+ assert.strictEqual(posts.length, 2);
374
+ assert.ok(!posts[1].lines.some((l) => l.file || l.reason));
375
+ assert.doesNotMatch(r.out, /logs not written on poad\.io/);
376
+ });
377
+
378
+ test('poad push: room — files counted apart from the base, a volume over its size never shows negative bytes', async (t) => {
379
+ const { local, deps } = await sides(t);
380
+ local.put('ressources', 'gros.bin', Buffer.alloc(300 * 1024, 1));
381
+ const space = { limit: 2 * 1024 ** 2, used: 3 * 1024 ** 2, storage: 2.5 * 1024 ** 2 };
382
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 'base,s3', '--yes'], { deps, cloud: { space } });
383
+ assert.strictEqual(r.code, 5);
384
+ const plain = r.out.replace(/\x1b\[[0-9;]*m/g, '');
385
+ assert.match(plain, /to write on dev: base \S+ KB, files 300\.0 KB/);
386
+ assert.match(plain, /volume 2\.0 MB: 3\.0 MB used \(base 512\.0 KB, files 2\.5 MB\), exceeded by 1\.0 MB/);
387
+ assert.match(plain, /not enough room on the target/);
388
+ assert.doesNotMatch(plain, /-\d[\d.]* ?[KMG]?B/);
389
+ assert.strictEqual(r.scripts.length, 0);
390
+ });
391
+
392
+ test('poad push --clean: the tables to rewrite are emptied first (TRUNCATE, own transaction), their room counted as freed', async (t) => {
393
+ const queries = [];
394
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 'base', '--clean', '--yes', '--json'], { pg: { queries }, cloud: { space: { limit: 1024 ** 3, used: 1024 ** 2 } } });
395
+ assert.strictEqual(r.code, 0, r.out);
396
+ const trunc = queries.findIndex((q) => /truncate table "public"\."livres"/.test(q));
397
+ assert.ok(trunc >= 0);
398
+ assert.match(queries[trunc], /begin;[\s\S]*commit;/);
399
+ assert.strictEqual(r.scripts.length, 1);
400
+ const j = JSON.parse(r.out.slice(r.out.indexOf('{')));
401
+ assert.ok(j.preview.space.freed.base > 0);
402
+ const ev = JSON.parse(r.seen.find((x) => /sync-events/.test(x.url)).body);
403
+ assert.ok(ev.lines.some((l) => l.part === 'base' && l.outcome === 'done' && !l.table));
404
+ });
405
+
406
+ test('poad push to production: no backup when the base has nothing to write (a relaunch with files only)', async (t) => {
407
+ const { local, deps } = await sides(t);
408
+ local.put('docs', 'a.txt', 'contenu');
409
+ const r = await runCmd(t, ['push', '--env', 'main', '--only', 'base,auth,s3', '--yes', '--confirm', 'pptest123456'], { deps, pg: { same: true } });
410
+ assert.strictEqual(r.code, 0, r.out);
411
+ assert.ok(!r.seen.some((x) => /\/backup$/.test(x.url)), 'no backup');
412
+ assert.strictEqual(r.scripts.length, 0, 'nothing written in the base');
413
+ });
@@ -0,0 +1,179 @@
1
+ // poad push / pull, partie fichiers : gros fichiers, reprise, objets tronqués, place (CLI 2.76.1).
2
+ // Contre un vrai serveur HTTP (test/fake-storage.js) et le vrai client du Stockage (utils/storage.js).
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const crypto = require('crypto');
9
+ const s = require('../utils/storage');
10
+ const ss = require('../utils/storage-sync');
11
+ const P = require('../utils/project-sync/plan');
12
+ const { fakeStorage, md5 } = require('./fake-storage');
13
+
14
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-resume-'));
15
+ process.env.POAD_UPLOADS_FILE = path.join(tmp, 'uploads.json');
16
+ test.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
17
+
18
+ const noSleep = async () => {};
19
+ const MiB = 1024 * 1024;
20
+ const bytes = (n, seed = 1) => {
21
+ const b = Buffer.alloc(n);
22
+ let x = seed;
23
+ for (let i = 0; i < n; i += 4) b.writeUInt32LE((x = (x * 1103515245 + 12345) >>> 0), i);
24
+ return b;
25
+ };
26
+ const client = (side, timeout) => s.client({ base: side.base, key: 'service-role-test', ...(timeout ? { timeout } : {}) });
27
+ const sync = (from, to, extra = {}) => ss.sync(from, to, { prune: true, concurrency: 2, sleep: noSleep, fromLabel: 'local engine', toLabel: 'poad.io', ...extra });
28
+
29
+ // --- Place ----------------------------------------------------------------------------------------------
30
+
31
+ test('room: never a negative number; a volume already over its size says "exceeded by"', () => {
32
+ const r = P.room({ need: { files: 3.1e9 }, space: { limit: 2 * 1024 ** 3, used: 3.3e9, storage: 3.2e9 } });
33
+ assert.strictEqual(r.ok, false);
34
+ assert.strictEqual(r.free, 0);
35
+ assert.strictEqual(r.available, 0);
36
+ assert.strictEqual(r.over, 3.3e9 - 2 * 1024 ** 3);
37
+ assert.deepStrictEqual([r.used_files, r.used_base], [3.2e9, 0.1e9]);
38
+ assert.ok(r.missing > 0);
39
+ for (const v of Object.values(r)) if (typeof v === 'number') assert.ok(v >= 0, `negative: ${v}`);
40
+ });
41
+
42
+ test('room: files replaced or removed free their room; base only with --clean; journal reserve only if the base writes', () => {
43
+ const space = { limit: 1000, used: 900 };
44
+ const files = P.room({ need: { files: 300 }, freed: { files: 250 }, space });
45
+ assert.deepStrictEqual([files.ok, files.required, files.available, files.reserve], [true, 300, 350, 0]);
46
+ const base = P.room({ need: { base: 100 }, space: { ...space, reserve: 10 } });
47
+ assert.deepStrictEqual([base.ok, base.required], [false, 120]);
48
+ const clean = P.room({ need: { base: 100 }, freed: { base: 200 }, space: { ...space, reserve: 10 } });
49
+ assert.strictEqual(clean.ok, true);
50
+ assert.deepStrictEqual(P.room({ need: { base: 1 } }).known, false);
51
+ });
52
+
53
+ // --- Nouvelles tentatives, concurrence ------------------------------------------------------------------
54
+
55
+ test('adaptive: a passing error is retried after a growing wait; concurrency halves, then comes back; a refusal is not retried', async () => {
56
+ const { CloudError } = require('../utils/cloud/api');
57
+ const waits = [];
58
+ const levels = [];
59
+ const tries = new Map();
60
+ const errs = await ss.adaptive(
61
+ ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'refus'],
62
+ async (x) => {
63
+ tries.set(x, (tries.get(x) || 0) + 1);
64
+ if (x === 'refus') throw new CloudError('too large', { status: 413 });
65
+ if (x === 'b' && tries.get(x) < 3) throw Object.assign(new CloudError('timeout', { code: 'timeout' }), { retriable: true });
66
+ },
67
+ { concurrency: 4, sleep: async (ms) => waits.push(ms), onConcurrency: (n) => levels.push(n) },
68
+ );
69
+ assert.deepStrictEqual(errs.map((e) => [e.item, e.attempts]), [['refus', 1]]);
70
+ assert.strictEqual(tries.get('b'), 3);
71
+ assert.strictEqual(waits.length, 2);
72
+ assert.ok(waits[0] >= 750 && waits[0] <= 1250 && waits[1] >= 1500 && waits[1] <= 2500, String(waits));
73
+ assert.strictEqual(levels[0], 2);
74
+ assert.ok(levels.length > 2 && levels[levels.length - 1] > 1, `goes back up: ${levels}`);
75
+ assert.strictEqual(ss.retriable(new CloudError('x', { status: 503 })), true);
76
+ assert.strictEqual(ss.retriable(new CloudError('x', { status: 403 })), false);
77
+ });
78
+
79
+ // --- Délai : d'inactivité, pas total ------------------------------------------------------------------------
80
+
81
+ test('client: a slow upload that keeps moving is never cut by the timeout; a stuck one is', async (t) => {
82
+ const slow = await fakeStorage(t, { slowPut: 25, buckets: ['b'] });
83
+ const body = bytes(6 * MiB);
84
+ const t0 = Date.now();
85
+ const pieces = [];
86
+ for (let i = 0; i < body.length; i += 64 * 1024) pieces.push(body.subarray(i, i + 64 * 1024));
87
+ await client(slow, 1000).put('b', 'lent.bin', require('stream').Readable.from(pieces), { length: body.length });
88
+ assert.ok(Date.now() - t0 > 1000, `the upload took longer than the timeout (${Date.now() - t0} ms)`);
89
+ assert.strictEqual(md5(slow.objects.get('b/lent.bin').body), md5(body));
90
+
91
+ const stuck = await fakeStorage(t, { stallPut: true, buckets: ['b'] });
92
+ await assert.rejects(client(stuck, 300).put('b', 'x.bin', require('stream').Readable.from([bytes(8 * MiB)])), (e) => e.code === 'timeout' && e.retriable === true && /did not answer within/.test(e.message));
93
+ });
94
+
95
+ // --- Gros fichier : en morceaux, reprise d'une commande à l'autre ------------------------------------------
96
+
97
+ test('sync: a large file goes in resumable chunks read by ranges; cut in the middle, the next run sends only the rest', async (t) => {
98
+ const local = await fakeStorage(t);
99
+ const cloud = await fakeStorage(t, { cutAfter: 12 * MiB });
100
+ const big = bytes(20 * MiB, 7);
101
+ local.put('videos', 'film.mp4', big, 'video/mp4');
102
+ local.put('videos', 'petit.txt', 'bonjour', 'text/plain');
103
+
104
+ const first = await sync(client(local), client(cloud), { retries: 1 });
105
+ assert.strictEqual(first.totals.failed, 1);
106
+ assert.strictEqual(first.errors[0].name, 'film.mp4');
107
+ assert.ok(!cloud.objects.has('videos/film.mp4'), 'never a partial object');
108
+ assert.ok(cloud.objects.has('videos/petit.txt'));
109
+ assert.strictEqual(cloud.stats.patchBytes, 12 * MiB);
110
+ assert.ok(local.stats.rangeReads >= 2, 'the source is read by ranges');
111
+
112
+ // Nouvelle commande (nouveaux clients) : rien de ce qui est arrivé n'est renvoyé
113
+ cloud.heal();
114
+ const events = [];
115
+ const again = await sync(client(local), client(cloud), { onItem: (e) => events.push(e) });
116
+ assert.strictEqual(again.totals.failed, 0);
117
+ assert.deepStrictEqual([again.totals.added, again.totals.unchanged], [1, 1]);
118
+ assert.strictEqual(cloud.stats.patchBytes, 20 * MiB, 'only the 8 MiB left were sent');
119
+ assert.deepStrictEqual(events.filter((e) => e.action === 'resume').map((e) => [e.name, e.offset]), [['film.mp4', 12 * MiB]]);
120
+ assert.strictEqual(md5(cloud.objects.get('videos/film.mp4').body), md5(big));
121
+ assert.strictEqual(cloud.objects.get('videos/film.mp4').type, 'video/mp4');
122
+
123
+ // Troisième fois : tout est là, rien ne part
124
+ const third = await sync(client(local), client(cloud));
125
+ assert.deepStrictEqual([third.totals.added, third.totals.updated, third.totals.unchanged], [0, 0, 2]);
126
+ });
127
+
128
+ test('sync: a source that does not serve ranges still sends a large file in chunks (from the stream)', async (t) => {
129
+ const local = await fakeStorage(t, { ranges: false });
130
+ const cloud = await fakeStorage(t);
131
+ const big = bytes(7 * MiB, 3);
132
+ local.put('docs', 'gros.pdf', big, 'application/pdf');
133
+ const r = await sync(client(local), client(cloud));
134
+ assert.strictEqual(r.totals.failed, 0);
135
+ assert.strictEqual(cloud.stats.put, 0);
136
+ assert.strictEqual(md5(cloud.objects.get('docs/gros.pdf').body), md5(big));
137
+ });
138
+
139
+ // --- Objets tronqués -----------------------------------------------------------------------------------
140
+
141
+ test('sync: a truncated object on the target is never "unchanged" (size + checksum), and is sent again', async (t) => {
142
+ const local = await fakeStorage(t);
143
+ const cloud = await fakeStorage(t);
144
+ const body = bytes(64 * 1024, 5);
145
+ local.put('docs', 'a.bin', body);
146
+ cloud.put('docs', 'a.bin', body.subarray(0, 32 * 1024));
147
+ const dry = await sync(client(local), client(cloud), { dryRun: true });
148
+ assert.deepStrictEqual([dry.totals.updated, dry.totals.unchanged], [1, 0]);
149
+ assert.strictEqual(dry.buckets[0].update[0].targetSize, 32 * 1024);
150
+ await sync(client(local), client(cloud));
151
+ assert.strictEqual(md5(cloud.objects.get('docs/a.bin').body), md5(body));
152
+ });
153
+
154
+ test('sync: an object that arrives different (faulty target) is a failure, never counted as done', async (t) => {
155
+ const local = await fakeStorage(t);
156
+ const cloud = await fakeStorage(t, { truncate: true });
157
+ local.put('docs', 'a.txt', 'contenu entier');
158
+ const r = await sync(client(local), client(cloud));
159
+ assert.strictEqual(r.totals.added, 0);
160
+ assert.strictEqual(r.totals.failed, 1);
161
+ assert.match(r.errors[0].error, /different on the target after the upload/);
162
+ });
163
+
164
+ test('sync --clean (freeFirst): what will be replaced is removed before the uploads; removals always come first', async (t) => {
165
+ const local = await fakeStorage(t);
166
+ const cloud = await fakeStorage(t);
167
+ local.put('docs', 'a.txt', 'nouveau');
168
+ cloud.put('docs', 'a.txt', 'ancien');
169
+ cloud.put('docs', 'vieux.txt', 'à retirer');
170
+ const order = [];
171
+ const to = client(cloud);
172
+ const [remove, put] = [to.remove, to.put];
173
+ to.remove = async (...a) => (order.push(['remove', ...a[1]]), remove(...a));
174
+ to.put = async (...a) => (order.push(['put', a[1]]), put(...a));
175
+ const r = await sync(client(local), to, { freeFirst: true });
176
+ assert.deepStrictEqual(order, [['remove', 'vieux.txt', 'a.txt'], ['put', 'a.txt']]);
177
+ assert.deepStrictEqual([r.totals.updated, r.totals.removed], [1, 1]);
178
+ assert.strictEqual(cloud.objects.get('docs/a.txt').body.toString(), 'nouveau');
179
+ });
@@ -44,7 +44,7 @@ test('envoyée, jamais chargée dans cet environnement → chargée au deploy su
44
44
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
45
45
  let polls = 0;
46
46
  const calls = fakeApi(t, [
47
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { dev: { 'public.commune': { sha256: SHA } } } })],
47
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { dev: { 'public.commune': { sha256: SHA } } } })],
48
48
  [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l1', targets: ['public.commune'], plan: { mode: 'together', order: ['public.commune'] } })],
49
49
  [/^GET .*\/seeds\/loads\/l1$/, () => (++polls < 2 ? { status: 'running', steps: [{ target: 'public.commune', status: 'running' }] } : { status: 'done', steps: [{ target: 'public.commune', status: 'done', written: 4, deleted: 0, duration_ms: 1200 }] })],
50
50
  ]);
@@ -61,7 +61,7 @@ test('envoyée, jamais chargée dans cet environnement → chargée au deploy su
61
61
  test('déjà chargée dans cet environnement : ni envoi ni chargement', async (t) => {
62
62
  const { dir, files } = project();
63
63
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
64
- const calls = fakeApi(t, [[/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { main: { 'public.commune': { sha256: SHA } } } })]]);
64
+ const calls = fakeApi(t, [[/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { main: { 'public.commune': { sha256: SHA } } } })]]);
65
65
  const { out } = output();
66
66
  const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
67
67
  assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['unchanged', 'loaded']]);
@@ -73,7 +73,7 @@ test('poad.io refuse faute de place (aucun ordre ne tient) : chaque table dite,
73
73
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
74
74
  const message = 'place insuffisante, même table par table : public.commune demande à elle seule environ 700.0 Mio, + 10 % de marge = 770.0 Mio, plus 256.0 Mio pour le journal (il manquerait 76.3 Mio). Pour passer : poad ref inspect public.commune, --exclude, ou une offre plus grande.';
75
75
  fakeApi(t, [
76
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
76
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
77
77
  [/^POST .*\/seeds\/load$/, () => {
78
78
  throw new api.CloudError(`reference load: ${message} (seed_no_space)`, { status: 413, code: 'seed_no_space', details: { code: 'seed_no_space', message, margin: 1.1, required: 1100, free: 1000, limit: 1024, tables: [{ target: 'public.commune', need: 734003200, status: 'refused' }, { target: 'public.region', need: 1, status: 'pending' }] } });
79
79
  }],
@@ -93,7 +93,7 @@ test('chargement table par table : annoncé, puis une table refusée en cours et
93
93
  const { dir, files } = project();
94
94
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
95
95
  fakeApi(t, [
96
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
96
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
97
97
  [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l2', targets: ['public.commune'], plan: { mode: 'stepwise', order: ['public.a', 'public.commune', 'public.c'] } })],
98
98
  [/^GET .*\/seeds\/loads\/l2$/, () => ({ status: 'failed', steps: [
99
99
  { target: 'public.a', status: 'done', written: 1, deleted: 0, duration_ms: 10, warnings: ['place restante faible sur l’engine main : 200.0 Mio libres sur 1.00 Gio (20 %)'] },
@@ -111,3 +111,93 @@ test('chargement table par table : annoncé, puis une table refusée en cours et
111
111
  assert.match(text, /public\.commune: refusée : place insuffisante/);
112
112
  assert.match(text, /public\.c: pending, not loaded into main; the next "poad deploy" loads it/);
113
113
  });
114
+
115
+ // --- État réel lu dans la base de l'environnement (poad.io : GET seeds?verify) : seed_applied n'est qu'un cache ---
116
+
117
+ const doneLoad = (written) => [
118
+ [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l2', targets: ['public.commune'], plan: { mode: 'together', order: ['public.commune'] } })],
119
+ [/^GET .*\/seeds\/loads\/l2$/, () => ({ status: 'done', steps: [{ target: 'public.commune', status: 'done', written, deleted: 0, duration_ms: 900 }] })],
120
+ ];
121
+
122
+ test('volume recréé vide : le registre dit « chargée », la base dit vide → rechargée, ligne « to load (table empty) »', async (t) => {
123
+ const { dir, files } = project();
124
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
125
+ const calls = fakeApi(t, [
126
+ [/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA, rows: 4 } } }, state: { main: { 'public.commune': { state: 'empty', rows: null, mark_rows: null, sha256: null } } } })],
127
+ ...doneLoad(4),
128
+ ]);
129
+ const { lines, out } = output();
130
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
131
+ assert.deepStrictEqual(r.tables.map((x) => [x.target, x.action, x.state, x.reason]), [['public.commune', 'load', 'loaded', 'empty']]);
132
+ assert.ok(calls.some(([m, route]) => m === 'POST' && /seeds\/load$/.test(route)), 'rechargée');
133
+ assert.ok(!calls.some(([, route]) => /seeds\/upload/.test(route)), 'pas renvoyée');
134
+ assert.match(lines.join('\n'), /○ public\.commune to load in main \(table empty; 4 rows to load\)/);
135
+ });
136
+
137
+ test('déjà chargée, lu dans la base : ni envoi ni chargement, ligne avec lignes et empreinte', async (t) => {
138
+ const { dir, files } = project();
139
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
140
+ const calls = fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: {}, state: { main: { 'public.commune': { state: 'loaded', rows: 4, mark_rows: 4, sha256: SHA } } } })]]);
141
+ const { lines, out } = output();
142
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
143
+ assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['unchanged', 'loaded']]);
144
+ assert.strictEqual(calls.length, 1);
145
+ assert.match(lines.join('\n'), /✔ public\.commune already loaded in main \(4 rows, sha256 aaaaaaaaaaaa\)/);
146
+ assert.ok(!/not checked/.test(lines.join('\n')));
147
+ });
148
+
149
+ test('table vidée à la main : moins de lignes qu’à la pose de la marque → rechargée', async (t) => {
150
+ const { dir, files } = project();
151
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
152
+ fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA } } }, state: { main: { 'public.commune': { state: 'incomplete', rows: 0, mark_rows: 4, sha256: SHA } } } })], ...doneLoad(4)]);
153
+ const { lines, out } = output();
154
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
155
+ assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['load', 'loaded']]);
156
+ assert.match(lines.join('\n'), /to load in main \(0 of 4 rows/);
157
+ });
158
+
159
+ test('--dry-run : une ligne par table (déjà chargée / à charger / à envoyer puis charger), rien d’envoyé ni de chargé', async (t) => {
160
+ const { dir } = project();
161
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
162
+ fs.writeFileSync(path.join(dir, 'reference', 'public.region.jsonl'), '{"id":1}\n'.repeat(8));
163
+ fs.writeFileSync(path.join(dir, 'reference', 'public.zone.jsonl'), '{"id":1}\n'.repeat(8));
164
+ const files = store.largeFiles(dir, 5);
165
+ const cache = JSON.parse(fs.readFileSync(path.join(dir, 'data', 'reference-store.json'), 'utf8'));
166
+ const reg = files.find((f) => f.target === 'public.region');
167
+ cache[reg.file] = { size: reg.size, mtimeMs: reg.mtimeMs, sha256: 'b'.repeat(64), target: reg.target };
168
+ fs.writeFileSync(path.join(dir, 'data', 'reference-store.json'), JSON.stringify(cache));
169
+ const calls = fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({
170
+ store: true,
171
+ items: [{ target: 'public.commune', sha256: SHA, rows: 4 }, { target: 'public.region', sha256: 'b'.repeat(64), rows: 8 }],
172
+ applied: {},
173
+ state: { main: { 'public.commune': { state: 'loaded', rows: 4, mark_rows: 4, sha256: SHA }, 'public.region': { state: 'unmarked', rows: null, sha256: null } } },
174
+ })]]);
175
+ const { lines, out } = output();
176
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out, { dryRun: true });
177
+ assert.strictEqual(calls.length, 1, 'une lecture, rien d’autre');
178
+ assert.deepStrictEqual(r.tables.map((x) => [x.target, x.action]), [['public.commune', 'unchanged'], ['public.region', 'load'], ['public.zone', 'send']]);
179
+ const text = lines.join('\n');
180
+ assert.match(text, /✔ public\.commune already loaded in main \(4 rows, sha256 aaaaaaaaaaaa\)/);
181
+ assert.match(text, /○ public\.region would be loaded in main \(rows without the load mark; 8 rows to load\)/);
182
+ assert.match(text, /○ public\.zone would be sent, then loaded in main \(never sent\)/);
183
+ assert.ok(!/loaded if not yet loaded/.test(text), 'plus de message générique');
184
+ });
185
+
186
+ test('poad.io d’avant la vérification (pas de state) : le registre, dit « not checked »', async (t) => {
187
+ const { dir, files } = project();
188
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
189
+ fakeApi(t, [[/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA, rows: 4 } } } })]]);
190
+ const { lines, out } = output();
191
+ await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out, { dryRun: true });
192
+ assert.match(lines.join('\n'), /already loaded in main \(4 rows, sha256 aaaaaaaaaaaa, as recorded by poad\.io: not checked in the database\)/);
193
+ });
194
+
195
+ test('verdict partagé avec poad.io (seed-format.mjs) : marque, empreinte, lignes', () => {
196
+ const A = require('../utils/seed/apply');
197
+ assert.strictEqual(A.referenceState(SHA, { exists: true, empty: true }), 'empty');
198
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: SHA, rows: 3, mark_rows: 4 }), 'incomplete');
199
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: 'b'.repeat(64), rows: 4, mark_rows: 4 }), 'outdated');
200
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: SHA, rows: 4, mark_rows: 4 }), 'loaded');
201
+ assert.ok(A.tail('public.commune', ['id'], SHA).includes("insert into _poad.reference_loads (target, sha256, rows) select 'public.commune'"));
202
+ assert.ok(!A.tail('public.commune', ['id']).includes('reference_loads'));
203
+ });
@@ -16,7 +16,15 @@ select json_build_object(
16
16
  select 'function' as kind, n.nspname as schema, p.proname as name, p.oid::regprocedure::text as signature,
17
17
  'security_definer' as reason,
18
18
  has_function_privilege('anon', p.oid, 'execute') as anon,
19
- has_function_privilege('authenticated', p.oid, 'execute') as authenticated
19
+ has_function_privilege('authenticated', p.oid, 'execute') as authenticated,
20
+ -- Appelée par des politiques RLS (motif classique contre leur récursion) : normal, pas de correctif
21
+ -- « security invoker » (il casserait les politiques). Directement (pg_depend de pg_policy : USING,
22
+ -- WITH CHECK), ou par une fonction qu'une politique appelle et dont le corps la nomme (un niveau).
23
+ (select count(distinct d.objid) from pg_depend d
24
+ where d.classid = 'pg_policy'::regclass and d.refclassid = 'pg_proc'::regclass and d.refobjid = p.oid) as policies,
25
+ (select count(distinct d.objid) from pg_depend d join pg_proc f on f.oid = d.refobjid
26
+ where d.classid = 'pg_policy'::regclass and d.refclassid = 'pg_proc'::regclass and f.oid <> p.oid
27
+ and f.prosrc ~* ('\m' || regexp_replace(p.proname, '([^A-Za-z0-9_])', '\\\1', 'g') || '\M')) as policies_indirect
20
28
  from pg_proc p join pg_namespace n on n.oid = p.pronamespace
21
29
  where n.nspname = any (s.names) and p.prokind = 'f' and p.prosecdef
22
30
  and p.prorettype not in ('trigger'::regtype, 'event_trigger'::regtype)
@@ -29,7 +37,8 @@ select json_build_object(
29
37
  select case c.relkind when 'm' then 'materialized_view' else 'view' end, n.nspname, c.relname, null,
30
38
  case c.relkind when 'm' then 'materialized_view' else 'view_owner_rights' end,
31
39
  has_table_privilege('anon', c.oid, 'select') or has_table_privilege('anon', c.oid, 'insert'),
32
- has_table_privilege('authenticated', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'insert')
40
+ has_table_privilege('authenticated', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'insert'),
41
+ 0, 0
33
42
  from pg_class c join pg_namespace n on n.oid = c.relnamespace
34
43
  where n.nspname = any (s.names)
35
44
  and (c.relkind = 'm' or (c.relkind = 'v' and not coalesce((select bool_or(lower(o) in ('security_invoker=true', 'security_invoker=on', 'security_invoker=yes', 'security_invoker=1')) from unnest(c.reloptions) o), false)))
@@ -45,10 +45,24 @@ function fixFor(i) {
45
45
  return 'read it through a SECURITY INVOKER function that returns only allowed rows, or replace it with a table and policies';
46
46
  }
47
47
 
48
- /** Ce que la version visée change ; { change: lost | regained_service_role | unchanged | none, items } */
49
- function impact({ current = null, target = null, items = [] } = {}) {
48
+ /**
49
+ * Fonction SECURITY DEFINER appelée par des politiques RLS (directement, ou par une fonction qu'une politique appelle) :
50
+ * le motif classique contre la récursion des politiques. Normal : l'API ne la sert pas en rpc, mais aucun correctif
51
+ * « security invoker » (il casserait les politiques). policies / policies_indirect : api-exposure.sql ; policy : scan
52
+ * des migrations en attente (poad.io).
53
+ */
54
+ const usedByPolicies = (i) => i.kind === 'function' && (Number(i.policies) > 0 || Number(i.policies_indirect) > 0 || i.policy === true);
55
+ const helperOf = (i) => ({ schema: i.schema, name: i.name, ...(i.signature ? { signature: i.signature } : {}), policies: Number(i.policies) || 0, policies_indirect: Number(i.policies_indirect) || 0, ...(i.source ? { source: i.source } : {}), ...(i.file ? { file: i.file } : {}) });
56
+
57
+ /**
58
+ * Ce que la version visée change ; { change: lost | regained_service_role | unchanged | none, items, policy_functions }.
59
+ * items : avec leur correctif ; policy_functions (appelées par des politiques RLS) : à part, sans correctif.
60
+ */
61
+ function impact({ current = null, target = null, items = [], policy_functions = [] } = {}) {
50
62
  const from = phaseOf(current);
51
63
  const to = phaseOf(target || current);
64
+ const helpers = [...policy_functions.map(helperOf), ...items.filter(usedByPolicies).map(helperOf)];
65
+ items = items.filter((i) => !usedByPolicies(i));
52
66
  const all = items.map((i) => ({ kind: i.kind, schema: i.schema, name: i.name, ...(i.signature ? { signature: i.signature } : {}), reason: i.reason, why: WHY[i.reason] || i.reason, roles: ['anon', 'authenticated'].filter((r) => i[r] !== false), fix: fixFor(i), ...(i.source ? { source: i.source } : {}), ...(i.file ? { file: i.file } : {}) }));
53
67
  let change = 'none';
54
68
  if (all.length && to !== 'served') {
@@ -56,7 +70,15 @@ function impact({ current = null, target = null, items = [] } = {}) {
56
70
  else if (from === 'refused_all' && to === 'service_role_only') change = 'regained_service_role';
57
71
  else change = 'unchanged';
58
72
  }
59
- return { current, target: target || current, phase: to, change, count: all.length, items: all };
73
+ return { current, target: target || current, phase: to, change, count: all.length, items: all, policy_count: helpers.length, policy_functions: helpers };
74
+ }
75
+
76
+ /** Mention courte, regroupée, des fonctions DEFINER des politiques RLS (--verbose) ; [] sinon */
77
+ function policyLines(x, chalk, { verbose = false } = {}) {
78
+ const h = (x && x.policy_functions) || [];
79
+ if (!verbose || !h.length || x.phase === 'served') return [];
80
+ const names = h.slice(0, 8).map((i) => `${i.schema}.${i.name}`).join(', ') + (h.length > 8 ? `, … (+${h.length - 8})` : '');
81
+ return [chalk.grey(` ℹ ${h.length} SECURITY DEFINER function(s) used by RLS policies: normal, not callable directly by the API (rpc) — ${names}`)];
60
82
  }
61
83
 
62
84
  /** La liste lue dans la base de l'engine local (lecture seule) ; null si illisible */
@@ -109,12 +131,12 @@ function afterMigrate({ engine = null, before = null, after = null } = {}) {
109
131
  const had = new Set((before || []).map(keyOf));
110
132
  const x = impact({ current: engine, target: engine, items: after });
111
133
  const items = x.items.map((i) => ({ ...i, created: Array.isArray(before) && !had.has(keyOf(i)) }));
112
- return { engine, phase: x.phase, count: items.length, created: items.filter((i) => i.created).map((i) => `${i.schema}.${i.name}`), items };
134
+ return { engine, phase: x.phase, count: items.length, created: items.filter((i) => i.created).map((i) => `${i.schema}.${i.name}`), items, policy_count: x.policy_count, policy_functions: x.policy_functions };
113
135
  }
114
136
 
115
137
  /** Lignes de poad migrate ; full : la liste (des migrations viennent d'être appliquées), sinon un rappel d'une ligne */
116
- function migrateLines(x, chalk, { full = true, max = 20 } = {}) {
117
- if (!x || !x.count) return [];
138
+ function migrateLines(x, chalk, { full = true, max = 20, verbose = false } = {}) {
139
+ if (!x || !x.count) return policyLines(x, chalk, { verbose });
118
140
  const n = `${x.count} function(s) or view(s)`;
119
141
  if (!full) return [chalk.yellowBright(` ⚠ ${n} granted to anon or authenticated are not served to them by the API (403 not_exposed): "poad migrate --json" or the Migrations screen of the console list them with their fix.`)];
120
142
  const out = [chalk.yellowBright(` ⚠ ${n} granted to anon or authenticated are not served to them by the API: they would bypass RLS, so a front end gets 403 not_exposed (service_role and SQL still work).`)];
@@ -123,12 +145,12 @@ function migrateLines(x, chalk, { full = true, max = 20 } = {}) {
123
145
  out.push(chalk.grey(` fix: ${i.fix}`));
124
146
  }
125
147
  if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (poad migrate --json lists them all)`));
126
- return out;
148
+ return [...out, ...policyLines(x, chalk, { verbose })];
127
149
  }
128
150
 
129
151
  /** Lignes à montrer (poad deploy, poad upgrade) ; [] si rien à dire */
130
- function lines(x, chalk, { max = 20 } = {}) {
131
- if (!x || !x.count || !x.change || x.change === 'none') return [];
152
+ function lines(x, chalk, { max = 20, verbose = false } = {}) {
153
+ if (!x || !x.count || !x.change || x.change === 'none') return policyLines(x, chalk, { verbose });
132
154
  const n = `${x.count} function(s) or view(s)`;
133
155
  const head =
134
156
  x.change === 'lost'
@@ -142,7 +164,7 @@ function lines(x, chalk, { max = 20 } = {}) {
142
164
  out.push(chalk.grey(` fix: ${i.fix}`));
143
165
  }
144
166
  if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (--json lists them all)`));
145
- return out;
167
+ return [...out, ...policyLines(x, chalk, { verbose })];
146
168
  }
147
169
 
148
- module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines, query, afterMigrate, migrateLines };
170
+ module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines, query, afterMigrate, migrateLines, policyLines, usedByPolicies };