@prenta/cli 0.17.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +30 -31
- package/CHANGELOG.md +16 -0
- package/dist/backup/common.d.ts +26 -0
- package/dist/backup/common.d.ts.map +1 -1
- package/dist/backup/common.js +31 -0
- package/dist/backup/common.js.map +1 -1
- package/dist/backup/manifest.d.ts +7 -0
- package/dist/backup/manifest.d.ts.map +1 -1
- package/dist/backup/manifest.js +21 -0
- package/dist/backup/manifest.js.map +1 -1
- package/dist/backup/pg-tools.d.ts +10 -2
- package/dist/backup/pg-tools.d.ts.map +1 -1
- package/dist/backup/pg-tools.js +12 -2
- package/dist/backup/pg-tools.js.map +1 -1
- package/dist/commands/db-backup.d.ts +2 -0
- package/dist/commands/db-backup.d.ts.map +1 -1
- package/dist/commands/db-backup.js +13 -2
- package/dist/commands/db-backup.js.map +1 -1
- package/dist/commands/db-restore.d.ts.map +1 -1
- package/dist/commands/db-restore.js +8 -0
- package/dist/commands/db-restore.js.map +1 -1
- package/dist/commands/migrate-content-hash.d.ts +3 -0
- package/dist/commands/migrate-content-hash.d.ts.map +1 -0
- package/dist/commands/migrate-content-hash.js +90 -0
- package/dist/commands/migrate-content-hash.js.map +1 -0
- package/dist/commands/migrate-media-optimize.d.ts.map +1 -1
- package/dist/commands/migrate-media-optimize.js +1 -30
- package/dist/commands/migrate-media-optimize.js.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/utils/load-project-config.d.ts +7 -0
- package/dist/utils/load-project-config.d.ts.map +1 -0
- package/dist/utils/load-project-config.js +37 -0
- package/dist/utils/load-project-config.js.map +1 -0
- package/package.json +2 -2
- package/src/__tests__/backup-common.test.ts +33 -1
- package/src/__tests__/backup-manifest.test.ts +13 -0
- package/src/__tests__/backup-pg-tools.test.ts +40 -3
- package/src/__tests__/db-backup.test.ts +47 -3
- package/src/__tests__/db-restore.test.ts +34 -0
- package/src/backup/common.ts +33 -0
- package/src/backup/manifest.ts +28 -0
- package/src/backup/pg-tools.ts +12 -1
- package/src/commands/db-backup.ts +25 -1
- package/src/commands/db-restore.ts +11 -0
- package/src/commands/migrate-content-hash.ts +108 -0
- package/src/commands/migrate-media-optimize.ts +1 -38
- package/src/index.ts +2 -0
- package/src/utils/load-project-config.ts +44 -0
|
@@ -115,6 +115,7 @@ async function makeBackup(
|
|
|
115
115
|
{ schema: 'public', name: 'prenta_documents', rows: 120 },
|
|
116
116
|
{ schema: 'public', name: 'prenta_users', rows: 3 },
|
|
117
117
|
],
|
|
118
|
+
excludedExtensions: ['prisma_postgres'],
|
|
118
119
|
}),
|
|
119
120
|
...overrides,
|
|
120
121
|
}
|
|
@@ -139,6 +140,7 @@ async function seedBlob(h: Harness, stamp: string, body = FAKE_DUMP): Promise<vo
|
|
|
139
140
|
sizeBytes: bytes.length,
|
|
140
141
|
sha256: await sha256File(enc),
|
|
141
142
|
tables: [{ schema: 'public', name: 'prenta_documents', rows: 120 }],
|
|
143
|
+
excludedExtensions: ['prisma_postgres'],
|
|
142
144
|
})
|
|
143
145
|
h.fakeBlob.seed(`backups/db/${stamp}.dump.enc`, bytes)
|
|
144
146
|
h.fakeBlob.seed(`backups/db/${stamp}.manifest.json`, JSON.stringify({ ...manifest, stamp }))
|
|
@@ -589,6 +591,37 @@ describe('prenta db:restore', () => {
|
|
|
589
591
|
expect(summary.sha256Verified).toBe(false)
|
|
590
592
|
expect(summary.tables).toEqual([])
|
|
591
593
|
})
|
|
594
|
+
|
|
595
|
+
it('names the platform-managed extensions the dump excluded, after a successful restore', async () => {
|
|
596
|
+
const { dumpPath } = await makeBackup(backups)
|
|
597
|
+
const h = harness(env(), cwd)
|
|
598
|
+
expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(0)
|
|
599
|
+
const info = h.logs.info.join('\n')
|
|
600
|
+
expect(info).toMatch(/prisma_postgres/)
|
|
601
|
+
expect(info).toMatch(/exclude/i)
|
|
602
|
+
})
|
|
603
|
+
|
|
604
|
+
it('says nothing about extensions when the dump excluded none', async () => {
|
|
605
|
+
const { dumpPath } = await makeBackup(backups, STAMP, { excludedExtensions: [] })
|
|
606
|
+
const h = harness(env(), cwd)
|
|
607
|
+
expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(0)
|
|
608
|
+
expect(h.logs.info.join('\n')).not.toMatch(/exclude/i)
|
|
609
|
+
})
|
|
610
|
+
|
|
611
|
+
// Manifests written before `excludedExtensions` existed have no such key;
|
|
612
|
+
// the reader must not assume it or crash on it.
|
|
613
|
+
it('restores a manifest predating excludedExtensions without a notice', async () => {
|
|
614
|
+
const { dumpPath, manifestPath } = await makeBackup(backups, STAMP, {
|
|
615
|
+
excludedExtensions: undefined,
|
|
616
|
+
})
|
|
617
|
+
expect(JSON.parse(await readFile(manifestPath, 'utf-8'))).not.toHaveProperty(
|
|
618
|
+
'excludedExtensions',
|
|
619
|
+
)
|
|
620
|
+
const h = harness(env(), cwd)
|
|
621
|
+
expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(0)
|
|
622
|
+
expect(h.logs.info.join('\n')).not.toMatch(/exclude/i)
|
|
623
|
+
expect(h.logs.error).toEqual([])
|
|
624
|
+
})
|
|
592
625
|
})
|
|
593
626
|
|
|
594
627
|
describe('blob sources', () => {
|
|
@@ -672,6 +705,7 @@ describe('prenta db:restore', () => {
|
|
|
672
705
|
sizeBytes: bytes.length,
|
|
673
706
|
sha256: await sha256File(enc),
|
|
674
707
|
tables: [],
|
|
708
|
+
excludedExtensions: [],
|
|
675
709
|
})
|
|
676
710
|
h.fakeBlob.seed('sites/acme/2026-09-18T033000Z.dump.enc', bytes)
|
|
677
711
|
h.fakeBlob.seed('sites/acme/2026-09-18T033000Z.manifest.json', JSON.stringify(manifest))
|
package/src/backup/common.ts
CHANGED
|
@@ -8,6 +8,39 @@ export const EXIT_OK = 0
|
|
|
8
8
|
export const EXIT_FAILED = 1
|
|
9
9
|
export const EXIT_PRECONDITION = 2
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* Extensions the managed host installs and owns, excluded from every dump.
|
|
13
|
+
*
|
|
14
|
+
* `prisma_postgres` only exists inside Prisma Postgres: it is already present
|
|
15
|
+
* in any database on that platform (so `CREATE EXTENSION IF NOT EXISTS` is a
|
|
16
|
+
* no-op there and nothing is lost), and it is unavailable in stock
|
|
17
|
+
* PostgreSQL, where `pg_restore` fails with `extension "prisma_postgres" is
|
|
18
|
+
* not available`. Under `--single-transaction --exit-on-error` that one
|
|
19
|
+
* statement aborts the whole restore — the first DR drill lost an entire
|
|
20
|
+
* restore of the real nightly dump to it. Excluding it at dump time is what
|
|
21
|
+
* makes a backup restorable into any PostgreSQL 17 server.
|
|
22
|
+
*
|
|
23
|
+
* Only platform-managed extensions belong here. Real contrib extensions the
|
|
24
|
+
* schema depends on (`pg_trgm`, migration 0015) must be dumped: they are
|
|
25
|
+
* available everywhere, and excluding one would silently drop the indexes
|
|
26
|
+
* that depend on it.
|
|
27
|
+
*/
|
|
28
|
+
export const DEFAULT_EXCLUDED_EXTENSIONS: readonly string[] = ['prisma_postgres']
|
|
29
|
+
|
|
30
|
+
/** `--exclude-extension none` opts out of excluding anything (same-platform dump). */
|
|
31
|
+
export const EXCLUDE_EXTENSIONS_NONE = 'none'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The effective exclude list for a run: `none` anywhere means "exclude
|
|
35
|
+
* nothing", blanks are dropped and duplicates collapse so the argv stays
|
|
36
|
+
* deterministic.
|
|
37
|
+
*/
|
|
38
|
+
export function resolveExcludedExtensions(values: readonly string[]): string[] {
|
|
39
|
+
const named = values.map((v) => v.trim()).filter((v) => v.length > 0)
|
|
40
|
+
if (named.some((v) => v.toLowerCase() === EXCLUDE_EXTENSIONS_NONE)) return []
|
|
41
|
+
return [...new Set(named)]
|
|
42
|
+
}
|
|
43
|
+
|
|
11
44
|
export interface ResolvedDatabaseUrl {
|
|
12
45
|
url: string
|
|
13
46
|
source: 'DIRECT_DATABASE_URL' | 'DATABASE_URL'
|
package/src/backup/manifest.ts
CHANGED
|
@@ -10,6 +10,11 @@
|
|
|
10
10
|
* Table row counts in the manifest come from `pg_class.reltuples` (planner
|
|
11
11
|
* estimates, no full scans); `rowCounts: 'estimate'` records that so the
|
|
12
12
|
* restore report compares like with like.
|
|
13
|
+
*
|
|
14
|
+
* Fields are added without bumping `version`, so readers must tolerate their
|
|
15
|
+
* absence: `excludedExtensions` (the platform-managed extensions kept out of
|
|
16
|
+
* the dump) is missing from every manifest written before it existed, and
|
|
17
|
+
* `parseManifest` leaves it undefined rather than inventing an empty list.
|
|
13
18
|
*/
|
|
14
19
|
import { createHash } from 'node:crypto'
|
|
15
20
|
import { createReadStream } from 'node:fs'
|
|
@@ -40,6 +45,12 @@ export interface BackupManifest {
|
|
|
40
45
|
/** Source of `tables[].rows`; always the planner estimate today. */
|
|
41
46
|
rowCounts: 'estimate'
|
|
42
47
|
tables: BackupTableRows[]
|
|
48
|
+
/**
|
|
49
|
+
* Platform-managed extensions excluded from the dump (`pg_dump
|
|
50
|
+
* --exclude-extension`). Absent in manifests written before this key
|
|
51
|
+
* existed; `[]` means the dump carries every extension of its source.
|
|
52
|
+
*/
|
|
53
|
+
excludedExtensions?: string[]
|
|
43
54
|
}
|
|
44
55
|
|
|
45
56
|
const STAMP_RE = /(\d{4}-\d{2}-\d{2}T\d{6}Z)/
|
|
@@ -140,6 +151,7 @@ export interface BuildManifestInput {
|
|
|
140
151
|
sizeBytes: number
|
|
141
152
|
sha256: string
|
|
142
153
|
tables: BackupTableRows[]
|
|
154
|
+
excludedExtensions: readonly string[]
|
|
143
155
|
}
|
|
144
156
|
|
|
145
157
|
export function buildManifest(input: BuildManifestInput): BackupManifest {
|
|
@@ -153,6 +165,7 @@ export function buildManifest(input: BuildManifestInput): BackupManifest {
|
|
|
153
165
|
sha256: input.sha256,
|
|
154
166
|
rowCounts: 'estimate',
|
|
155
167
|
tables: input.tables.map((t) => ({ schema: t.schema, name: t.name, rows: t.rows })),
|
|
168
|
+
excludedExtensions: [...input.excludedExtensions],
|
|
156
169
|
}
|
|
157
170
|
}
|
|
158
171
|
|
|
@@ -169,6 +182,7 @@ export function parseManifest(value: unknown): BackupManifest {
|
|
|
169
182
|
)
|
|
170
183
|
}
|
|
171
184
|
const { createdAt, stamp, database, pgDumpVersion, sizeBytes, sha256, tables } = value
|
|
185
|
+
const excludedExtensions = parseExcludedExtensions(value.excludedExtensions)
|
|
172
186
|
if (typeof createdAt !== 'string' || Number.isNaN(Date.parse(createdAt))) {
|
|
173
187
|
throw new Error('Backup manifest: createdAt must be an ISO-8601 string.')
|
|
174
188
|
}
|
|
@@ -213,5 +227,19 @@ export function parseManifest(value: unknown): BackupManifest {
|
|
|
213
227
|
sha256,
|
|
214
228
|
rowCounts: 'estimate',
|
|
215
229
|
tables: parsedTables,
|
|
230
|
+
...(excludedExtensions ? { excludedExtensions } : {}),
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* `excludedExtensions` for manifests that have it. Older manifests predate
|
|
236
|
+
* the key: `undefined` stays `undefined` so a reader can tell "not recorded"
|
|
237
|
+
* apart from "nothing was excluded".
|
|
238
|
+
*/
|
|
239
|
+
function parseExcludedExtensions(value: unknown): string[] | undefined {
|
|
240
|
+
if (value === undefined) return undefined
|
|
241
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
|
|
242
|
+
throw new Error('Backup manifest: excludedExtensions must be an array of strings.')
|
|
216
243
|
}
|
|
244
|
+
return value as string[]
|
|
217
245
|
}
|
package/src/backup/pg-tools.ts
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import { spawn } from 'node:child_process'
|
|
21
21
|
import type { Readable } from 'node:stream'
|
|
22
|
+
import { DEFAULT_EXCLUDED_EXTENSIONS } from './common.js'
|
|
22
23
|
import type { BackupTableRows } from './manifest.js'
|
|
23
24
|
|
|
24
25
|
export interface SpawnOptions {
|
|
@@ -234,10 +235,19 @@ async function runWithUrl(
|
|
|
234
235
|
return { ...result, stderr: redactText(result.stderr, [password]) }
|
|
235
236
|
}
|
|
236
237
|
|
|
237
|
-
/**
|
|
238
|
+
/**
|
|
239
|
+
* `pg_dump --format=custom --no-owner --no-privileges --file=<out>
|
|
240
|
+
* [--exclude-extension=<name>…] --dbname=<url>`
|
|
241
|
+
*
|
|
242
|
+
* `--exclude-extension` (PostgreSQL 17+, which `checkPgTool` already
|
|
243
|
+
* requires) keeps platform-managed extensions out of the dump so it restores
|
|
244
|
+
* into stock PostgreSQL — see `DEFAULT_EXCLUDED_EXTENSIONS`. The flags are
|
|
245
|
+
* emitted in list order, before `--dbname`, so the argv stays deterministic.
|
|
246
|
+
*/
|
|
238
247
|
export async function runPgDump(
|
|
239
248
|
databaseUrl: string,
|
|
240
249
|
outPath: string,
|
|
250
|
+
excludeExtensions: readonly string[] = DEFAULT_EXCLUDED_EXTENSIONS,
|
|
241
251
|
spawnImpl: SpawnImpl = defaultSpawn,
|
|
242
252
|
baseEnv: NodeJS.ProcessEnv = process.env,
|
|
243
253
|
): Promise<{ stderr: string }> {
|
|
@@ -249,6 +259,7 @@ export async function runPgDump(
|
|
|
249
259
|
'--no-owner',
|
|
250
260
|
'--no-privileges',
|
|
251
261
|
`--file=${outPath}`,
|
|
262
|
+
...excludeExtensions.map((name) => `--exclude-extension=${name}`),
|
|
252
263
|
`--dbname=${safeUrl}`,
|
|
253
264
|
],
|
|
254
265
|
databaseUrl,
|
|
@@ -19,6 +19,8 @@ import { dirname, join, resolve } from 'node:path'
|
|
|
19
19
|
import { createBlobStore, DEFAULT_BACKUP_PREFIX, type BlobModule } from '../backup/blob-store.js'
|
|
20
20
|
import {
|
|
21
21
|
BLOB_AUTH_HINT,
|
|
22
|
+
DEFAULT_EXCLUDED_EXTENSIONS,
|
|
23
|
+
EXCLUDE_EXTENSIONS_NONE,
|
|
22
24
|
EXIT_FAILED,
|
|
23
25
|
EXIT_OK,
|
|
24
26
|
EXIT_PRECONDITION,
|
|
@@ -28,6 +30,7 @@ import {
|
|
|
28
30
|
isPostgresUrl,
|
|
29
31
|
resolveBlobAuth,
|
|
30
32
|
resolveDatabaseUrl,
|
|
33
|
+
resolveExcludedExtensions,
|
|
31
34
|
} from '../backup/common.js'
|
|
32
35
|
import { BackupKeyError, encryptFile, parseBackupKey } from '../backup/crypto.js'
|
|
33
36
|
import {
|
|
@@ -63,6 +66,8 @@ export interface DbBackupOptions {
|
|
|
63
66
|
initWorkflow?: boolean
|
|
64
67
|
force?: boolean
|
|
65
68
|
allowLocal?: boolean
|
|
69
|
+
/** Repeatable `--exclude-extension`; `none` anywhere excludes nothing. */
|
|
70
|
+
excludeExtension?: readonly string[]
|
|
66
71
|
}
|
|
67
72
|
|
|
68
73
|
export interface DbBackupDeps {
|
|
@@ -190,6 +195,9 @@ export async function runDbBackup(opts: DbBackupOptions, deps: DbBackupDeps): Pr
|
|
|
190
195
|
}
|
|
191
196
|
|
|
192
197
|
// 6. Dump → encrypt → manifest.
|
|
198
|
+
const excludedExtensions = resolveExcludedExtensions(
|
|
199
|
+
opts.excludeExtension ?? DEFAULT_EXCLUDED_EXTENSIONS,
|
|
200
|
+
)
|
|
193
201
|
const stamp = stampFor(startedAt)
|
|
194
202
|
const outDir = resolve(deps.cwd, opts.out ?? join(tmpdir(), 'prenta-backups'))
|
|
195
203
|
await mkdir(outDir, { recursive: true })
|
|
@@ -201,7 +209,7 @@ export async function runDbBackup(opts: DbBackupOptions, deps: DbBackupDeps): Pr
|
|
|
201
209
|
let sizeBytes: number
|
|
202
210
|
try {
|
|
203
211
|
deps.log.info(`Dumping ${redactUrl(resolved.url)} with pg_dump ${pgDump.version}…`)
|
|
204
|
-
await runPgDump(resolved.url, rawDump, deps.spawnImpl, env)
|
|
212
|
+
await runPgDump(resolved.url, rawDump, excludedExtensions, deps.spawnImpl, env)
|
|
205
213
|
await encryptFile(rawDump, dumpPath, key)
|
|
206
214
|
sizeBytes = (await stat(dumpPath)).size
|
|
207
215
|
const sha256 = await sha256File(dumpPath)
|
|
@@ -212,6 +220,7 @@ export async function runDbBackup(opts: DbBackupOptions, deps: DbBackupDeps): Pr
|
|
|
212
220
|
sizeBytes,
|
|
213
221
|
sha256,
|
|
214
222
|
tables,
|
|
223
|
+
excludedExtensions,
|
|
215
224
|
})
|
|
216
225
|
await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
|
|
217
226
|
} catch (err) {
|
|
@@ -291,6 +300,15 @@ export async function runDbBackup(opts: DbBackupOptions, deps: DbBackupDeps): Pr
|
|
|
291
300
|
return EXIT_OK
|
|
292
301
|
}
|
|
293
302
|
|
|
303
|
+
/**
|
|
304
|
+
* Commander collector for the repeatable `--exclude-extension`. The first
|
|
305
|
+
* occurrence replaces the default list rather than appending to it, so
|
|
306
|
+
* `--exclude-extension none` really means "exclude nothing".
|
|
307
|
+
*/
|
|
308
|
+
function collectExcludeExtension(value: string, previous: readonly string[]): string[] {
|
|
309
|
+
return previous === DEFAULT_EXCLUDED_EXTENSIONS ? [value] : [...previous, value]
|
|
310
|
+
}
|
|
311
|
+
|
|
294
312
|
function parseRetention(value: string): number {
|
|
295
313
|
const n = Number(value)
|
|
296
314
|
if (!Number.isFinite(n)) throw new Error(`--retention-days expects a number, got "${value}".`)
|
|
@@ -325,6 +343,12 @@ export function registerDbBackupCommand(program: Command, deps?: DbBackupDeps):
|
|
|
325
343
|
)
|
|
326
344
|
.option('--prefix <path>', 'Blob pathname prefix', DEFAULT_BACKUP_PREFIX)
|
|
327
345
|
.option('--allow-local', 'Allow a localhost / 127.0.0.1 database URL')
|
|
346
|
+
.option(
|
|
347
|
+
'--exclude-extension <name>',
|
|
348
|
+
`Platform-managed extension to keep out of the dump so it restores into stock PostgreSQL (repeatable; "${EXCLUDE_EXTENSIONS_NONE}" excludes nothing, for a dump that only ever goes back to the same platform)`,
|
|
349
|
+
collectExcludeExtension,
|
|
350
|
+
DEFAULT_EXCLUDED_EXTENSIONS,
|
|
351
|
+
)
|
|
328
352
|
.option('--json', 'Print a machine-readable JSON summary')
|
|
329
353
|
.option('--init-workflow', `Write ${DB_BACKUP_WORKFLOW_PATH} into this repo and exit`)
|
|
330
354
|
.option('--force', 'Overwrite an existing workflow file (with --init-workflow)')
|
|
@@ -441,6 +441,17 @@ export async function runDbRestore(
|
|
|
441
441
|
}
|
|
442
442
|
deps.log.success('pg_restore completed.')
|
|
443
443
|
|
|
444
|
+
// Older manifests predate the key; only say something when there is
|
|
445
|
+
// something to say. The source database had these extensions installed,
|
|
446
|
+
// the dump deliberately does not carry them (they are managed by the
|
|
447
|
+
// platform it ran on), and a fresh non-Prisma target therefore has none.
|
|
448
|
+
const excluded = manifest?.excludedExtensions ?? []
|
|
449
|
+
if (excluded.length > 0) {
|
|
450
|
+
deps.log.info(
|
|
451
|
+
`The source database had platform-managed extension(s) excluded from this dump: ${excluded.join(', ')}. They are installed and owned by the managed host, so nothing is missing on that platform; on a stock PostgreSQL server they simply do not exist. Nothing to do unless your own schema starts depending on one.`,
|
|
452
|
+
)
|
|
453
|
+
}
|
|
454
|
+
|
|
444
455
|
// Post-restore counts.
|
|
445
456
|
const tables: DbRestoreTableReport[] = (manifest?.tables ?? []).map((t) => ({
|
|
446
457
|
schema: t.schema,
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { Command } from 'commander'
|
|
2
|
+
import ora from 'ora'
|
|
3
|
+
import { connectProjectDatabase } from '../utils/database.js'
|
|
4
|
+
import { loadProjectConfig } from '../utils/load-project-config.js'
|
|
5
|
+
import { loadProjectEnv } from '../utils/load-dotenv.js'
|
|
6
|
+
import { logger } from '../utils/logger.js'
|
|
7
|
+
|
|
8
|
+
interface MigrateContentHashOptions {
|
|
9
|
+
dryRun?: boolean
|
|
10
|
+
limit?: string
|
|
11
|
+
batchSize?: string
|
|
12
|
+
config?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function parsePositiveInt(raw: string | undefined, flag: string): number | undefined {
|
|
16
|
+
if (raw === undefined) return undefined
|
|
17
|
+
const value = Number.parseInt(raw, 10)
|
|
18
|
+
if (!Number.isFinite(value) || value <= 0 || String(value) !== raw.trim()) {
|
|
19
|
+
logger.error(`${flag} must be a positive integer.`)
|
|
20
|
+
process.exit(1)
|
|
21
|
+
}
|
|
22
|
+
return value
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `prenta migrate:content-hash` — fill Media.contentHash so upload dedupe can match legacy files. */
|
|
26
|
+
async function runMigrateContentHash(options: MigrateContentHashOptions): Promise<void> {
|
|
27
|
+
const dryRun = options.dryRun ?? false
|
|
28
|
+
const limit = parsePositiveInt(options.limit, '--limit')
|
|
29
|
+
const batchSize = parsePositiveInt(options.batchSize, '--batch-size')
|
|
30
|
+
|
|
31
|
+
await loadProjectEnv(process.cwd()).then((env) => {
|
|
32
|
+
for (const [key, value] of Object.entries(env)) {
|
|
33
|
+
if (value !== undefined && process.env[key] === undefined) {
|
|
34
|
+
process.env[key] = value
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
})
|
|
38
|
+
await loadProjectConfig(options.config ?? 'prenta.config.ts')
|
|
39
|
+
|
|
40
|
+
let connection: { db: unknown; disconnect: () => Promise<void> } | null = null
|
|
41
|
+
const spinner = ora(
|
|
42
|
+
dryRun ? 'Hashing media library (dry run)…' : 'Backfilling media content hashes…',
|
|
43
|
+
).start()
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
connection = await connectProjectDatabase()
|
|
47
|
+
const { backfillMediaContentHash } = await import('@prenta/core')
|
|
48
|
+
|
|
49
|
+
const result = await backfillMediaContentHash(connection.db as never, {
|
|
50
|
+
dryRun,
|
|
51
|
+
limit,
|
|
52
|
+
batchSize,
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
spinner.succeed(
|
|
56
|
+
dryRun
|
|
57
|
+
? `Dry run complete — ${result.hashed} asset(s) would be hashed.`
|
|
58
|
+
: `Hashed ${result.hashed} asset(s).`,
|
|
59
|
+
)
|
|
60
|
+
logger.info(` Scanned: ${result.scanned}`)
|
|
61
|
+
logger.info(` Hashed: ${result.hashed}`)
|
|
62
|
+
logger.info(` Failed: ${result.failed}`)
|
|
63
|
+
logger.info(` Remaining: ${result.remaining}`)
|
|
64
|
+
logger.info(` Collisions: ${result.collisions.length}`)
|
|
65
|
+
if (result.collisions.length > 0) {
|
|
66
|
+
logger.info('')
|
|
67
|
+
logger.info('Byte-identical groups (not merged — resolve these by hand):')
|
|
68
|
+
for (const group of result.collisions.slice(0, 20)) {
|
|
69
|
+
logger.info(` ${group.mediaIds.join(', ')}`)
|
|
70
|
+
}
|
|
71
|
+
if (result.collisions.length > 20) {
|
|
72
|
+
logger.info(` …and ${result.collisions.length - 20} more`)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (result.errors.length > 0) {
|
|
76
|
+
logger.info('')
|
|
77
|
+
for (const err of result.errors.slice(0, 10)) {
|
|
78
|
+
logger.info(` ${err.id}: ${err.message}`)
|
|
79
|
+
}
|
|
80
|
+
if (result.errors.length > 10) {
|
|
81
|
+
logger.info(` …and ${result.errors.length - 10} more`)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (result.remaining > 0 && !dryRun) {
|
|
85
|
+
logger.info('')
|
|
86
|
+
logger.info('Re-run to continue. Rows that already have a hash are skipped.')
|
|
87
|
+
}
|
|
88
|
+
} catch (err) {
|
|
89
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
90
|
+
spinner.fail(`Content hash backfill failed: ${message}`)
|
|
91
|
+
process.exit(1)
|
|
92
|
+
} finally {
|
|
93
|
+
await connection?.disconnect()
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function registerMigrateContentHashCommand(program: Command): void {
|
|
98
|
+
program
|
|
99
|
+
.command('migrate:content-hash')
|
|
100
|
+
.description(
|
|
101
|
+
'SHA-256 stored bytes onto media rows with a NULL contentHash so upload dedupe can match them. Idempotent. Reports collisions; does not merge or delete.',
|
|
102
|
+
)
|
|
103
|
+
.option('--dry-run', 'Download and report without writing hashes')
|
|
104
|
+
.option('--limit <n>', 'Max assets to download this run')
|
|
105
|
+
.option('--batch-size <n>', 'Media rows per DB page (default 50)')
|
|
106
|
+
.option('--config <path>', 'Path to prenta.config.ts (default: ./prenta.config.ts)')
|
|
107
|
+
.action(runMigrateContentHash)
|
|
108
|
+
}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { Command } from 'commander'
|
|
2
|
-
import { resolve } from 'node:path'
|
|
3
2
|
import ora from 'ora'
|
|
4
3
|
import { connectProjectDatabase } from '../utils/database.js'
|
|
5
|
-
import {
|
|
4
|
+
import { loadProjectConfig } from '../utils/load-project-config.js'
|
|
6
5
|
import { loadProjectEnv } from '../utils/load-dotenv.js'
|
|
7
6
|
import { logger } from '../utils/logger.js'
|
|
8
7
|
|
|
@@ -14,42 +13,6 @@ interface MigrateMediaOptimizeOptions {
|
|
|
14
13
|
config?: string
|
|
15
14
|
}
|
|
16
15
|
|
|
17
|
-
async function loadProjectConfig(configPath: string): Promise<void> {
|
|
18
|
-
try {
|
|
19
|
-
const { setPrentaConfig, setStorageAdapter, autoWireStorageAdapter } =
|
|
20
|
-
await import('@prenta/core')
|
|
21
|
-
const mod = (await importProjectTypescript(resolve(configPath))) as {
|
|
22
|
-
default?: unknown
|
|
23
|
-
config?: unknown
|
|
24
|
-
}
|
|
25
|
-
const config = mod.default ?? mod.config
|
|
26
|
-
if (!config || typeof config !== 'object') return
|
|
27
|
-
setPrentaConfig(config as never)
|
|
28
|
-
|
|
29
|
-
const platformStorage = (config as { platform?: { storage?: unknown } }).platform?.storage
|
|
30
|
-
if (
|
|
31
|
-
platformStorage &&
|
|
32
|
-
typeof platformStorage === 'object' &&
|
|
33
|
-
typeof (platformStorage as { upload?: unknown }).upload === 'function'
|
|
34
|
-
) {
|
|
35
|
-
setStorageAdapter(platformStorage as never)
|
|
36
|
-
return
|
|
37
|
-
}
|
|
38
|
-
const provider =
|
|
39
|
-
platformStorage &&
|
|
40
|
-
typeof platformStorage === 'object' &&
|
|
41
|
-
typeof (platformStorage as { provider?: unknown }).provider === 'string'
|
|
42
|
-
? (platformStorage as { provider: string }).provider
|
|
43
|
-
: undefined
|
|
44
|
-
if (provider) await autoWireStorageAdapter(provider)
|
|
45
|
-
} catch {
|
|
46
|
-
logger.warn(
|
|
47
|
-
`Could not load ${configPath} — will fetch public media URLs directly. ` +
|
|
48
|
-
'Pass --config if uploads go through a private storage adapter.',
|
|
49
|
-
)
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
16
|
/** `prenta migrate:media-optimize` — re-run WebP/dimension pipeline on existing media. */
|
|
54
17
|
async function runMigrateMediaOptimize(options: MigrateMediaOptimizeOptions): Promise<void> {
|
|
55
18
|
const dryRun = options.dryRun ?? false
|
package/src/index.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { registerMigrateSchemaCommand } from './commands/migrate-schema.js'
|
|
|
6
6
|
import { registerMigrateMetaCommand } from './commands/migrate-meta.js'
|
|
7
7
|
import { registerMigrateMediaUsageCommand } from './commands/migrate-media-usage.js'
|
|
8
8
|
import { registerMigrateMediaOptimizeCommand } from './commands/migrate-media-optimize.js'
|
|
9
|
+
import { registerMigrateContentHashCommand } from './commands/migrate-content-hash.js'
|
|
9
10
|
import { registerGenerateCommand } from './commands/generate.js'
|
|
10
11
|
import { registerSeedCommand } from './commands/seed.js'
|
|
11
12
|
import { registerImportCommand } from './commands/import.js'
|
|
@@ -39,6 +40,7 @@ registerMigrateSchemaCommand(program)
|
|
|
39
40
|
registerMigrateMetaCommand(program)
|
|
40
41
|
registerMigrateMediaUsageCommand(program)
|
|
41
42
|
registerMigrateMediaOptimizeCommand(program)
|
|
43
|
+
registerMigrateContentHashCommand(program)
|
|
42
44
|
registerGenerateCommand(program)
|
|
43
45
|
registerSeedCommand(program)
|
|
44
46
|
registerImportCommand(program)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { resolve } from 'node:path'
|
|
2
|
+
import { importProjectTypescript } from './import-typescript.js'
|
|
3
|
+
import { logger } from './logger.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Load `prenta.config.ts` and register its storage adapter so media commands
|
|
7
|
+
* can download private blobs. A missing or unloadable config falls through
|
|
8
|
+
* to a public-URL fetch.
|
|
9
|
+
*/
|
|
10
|
+
export async function loadProjectConfig(configPath: string): Promise<void> {
|
|
11
|
+
try {
|
|
12
|
+
const { setPrentaConfig, setStorageAdapter, autoWireStorageAdapter } =
|
|
13
|
+
await import('@prenta/core')
|
|
14
|
+
const mod = (await importProjectTypescript(resolve(configPath))) as {
|
|
15
|
+
default?: unknown
|
|
16
|
+
config?: unknown
|
|
17
|
+
}
|
|
18
|
+
const config = mod.default ?? mod.config
|
|
19
|
+
if (!config || typeof config !== 'object') return
|
|
20
|
+
setPrentaConfig(config as never)
|
|
21
|
+
|
|
22
|
+
const platformStorage = (config as { platform?: { storage?: unknown } }).platform?.storage
|
|
23
|
+
if (
|
|
24
|
+
platformStorage &&
|
|
25
|
+
typeof platformStorage === 'object' &&
|
|
26
|
+
typeof (platformStorage as { upload?: unknown }).upload === 'function'
|
|
27
|
+
) {
|
|
28
|
+
setStorageAdapter(platformStorage as never)
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
const provider =
|
|
32
|
+
platformStorage &&
|
|
33
|
+
typeof platformStorage === 'object' &&
|
|
34
|
+
typeof (platformStorage as { provider?: unknown }).provider === 'string'
|
|
35
|
+
? (platformStorage as { provider: string }).provider
|
|
36
|
+
: undefined
|
|
37
|
+
if (provider) await autoWireStorageAdapter(provider)
|
|
38
|
+
} catch {
|
|
39
|
+
logger.warn(
|
|
40
|
+
`Could not load ${configPath} — will fetch public media URLs directly. ` +
|
|
41
|
+
'Pass --config if uploads go through a private storage adapter.',
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
}
|