@prenta/cli 1.0.1 → 1.1.1
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 +47 -34
- package/CHANGELOG.md +27 -0
- package/dist/commands/chrome.d.ts +74 -0
- package/dist/commands/chrome.d.ts.map +1 -0
- package/dist/commands/chrome.js +274 -0
- package/dist/commands/chrome.js.map +1 -0
- package/dist/commands/upgrade.d.ts +27 -0
- package/dist/commands/upgrade.d.ts.map +1 -1
- package/dist/commands/upgrade.js +81 -45
- package/dist/commands/upgrade.js.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/utils/workspaces.d.ts +25 -0
- package/dist/utils/workspaces.d.ts.map +1 -0
- package/dist/utils/workspaces.js +143 -0
- package/dist/utils/workspaces.js.map +1 -0
- package/package.json +4 -4
- package/src/__tests__/chrome.test.ts +258 -0
- package/src/__tests__/upgrade-workspaces.test.ts +215 -0
- package/src/commands/chrome.ts +362 -0
- package/src/commands/upgrade.ts +117 -46
- package/src/index.ts +11 -1
- package/src/utils/workspaces.ts +140 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { Command } from 'commander'
|
|
5
|
+
import type {
|
|
6
|
+
ChromeSchemaReadResult,
|
|
7
|
+
ChromeSyncStatus,
|
|
8
|
+
RegionDefinition,
|
|
9
|
+
RegionSchema,
|
|
10
|
+
} from '@prenta/core'
|
|
11
|
+
import { importProjectTypescript } from '../utils/import-typescript.js'
|
|
12
|
+
import { logger } from '../utils/logger.js'
|
|
13
|
+
|
|
14
|
+
const DEFAULT_SCHEMA_FILE = '.prenta/chrome.json'
|
|
15
|
+
const DEFAULT_TYPES_FILE = '.prenta/chrome.d.ts'
|
|
16
|
+
const REQUEST_TIMEOUT_MS = 20_000
|
|
17
|
+
|
|
18
|
+
/** Load core only for the chrome commands, so the rest of the CLI doesn't pay for it. */
|
|
19
|
+
async function chromeCore() {
|
|
20
|
+
const core = await import('@prenta/core')
|
|
21
|
+
if (typeof core.chromeTypesSource !== 'function' || typeof core.serializeRegion !== 'function') {
|
|
22
|
+
throw new Error('The chrome commands need a newer @prenta/core. Update it, then try again.')
|
|
23
|
+
}
|
|
24
|
+
return core
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CmsConnection {
|
|
28
|
+
url?: string
|
|
29
|
+
key?: string
|
|
30
|
+
fetch?: typeof fetch
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What `prenta pull chrome` writes and `prenta types` reads. */
|
|
34
|
+
export interface PulledChrome {
|
|
35
|
+
pulledAt: string
|
|
36
|
+
cms: string
|
|
37
|
+
sync: ChromeSyncStatus
|
|
38
|
+
regions: RegionSchema[]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The CMS API base for `--url` / `PRENTA_CMS_URL`, with or without `/api/cms` on the end. */
|
|
42
|
+
export function cmsApiBase(url: string): string {
|
|
43
|
+
const origin = url.trim().replace(/\/+$/, '')
|
|
44
|
+
return /\/api\/cms(\/v1)?$/.test(origin) ? origin : `${origin}/api/cms`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function connection(options: CmsConnection): { base: string; key: string; fetch: typeof fetch } {
|
|
48
|
+
const url = options.url ?? process.env.PRENTA_CMS_URL
|
|
49
|
+
const key = options.key ?? process.env.PRENTA_API_KEY
|
|
50
|
+
if (!url) throw new Error('Set the CMS URL with --url or PRENTA_CMS_URL.')
|
|
51
|
+
if (!key) throw new Error('Set an API key with --key or PRENTA_API_KEY.')
|
|
52
|
+
return { base: cmsApiBase(url), key, fetch: options.fetch ?? fetch }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function cmsRequest<T>(
|
|
56
|
+
conn: { base: string; key: string; fetch: typeof fetch },
|
|
57
|
+
method: 'GET' | 'PUT',
|
|
58
|
+
route: string,
|
|
59
|
+
body?: unknown,
|
|
60
|
+
): Promise<T> {
|
|
61
|
+
const response = await conn.fetch(`${conn.base}${route}`, {
|
|
62
|
+
method,
|
|
63
|
+
headers: {
|
|
64
|
+
authorization: `Bearer ${conn.key}`,
|
|
65
|
+
accept: 'application/json',
|
|
66
|
+
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
67
|
+
},
|
|
68
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
69
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
70
|
+
})
|
|
71
|
+
const text = await response.text()
|
|
72
|
+
let parsed: { data?: T; error?: string } | null = null
|
|
73
|
+
try {
|
|
74
|
+
parsed = text ? (JSON.parse(text) as { data?: T; error?: string }) : null
|
|
75
|
+
} catch {
|
|
76
|
+
// Not JSON: report the status below.
|
|
77
|
+
}
|
|
78
|
+
if (!response.ok) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`${method} ${route} failed (${response.status}): ${parsed?.error ?? text.slice(0, 200)}`,
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
if (!parsed || parsed.data === undefined) throw new Error(`${method} ${route} returned no data`)
|
|
84
|
+
return parsed.data
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ─── pull ───────────────────────────────────────────────────────────────
|
|
88
|
+
|
|
89
|
+
/** Fetch the schema the CMS holds and write it to `.prenta/chrome.json`. */
|
|
90
|
+
export async function pullChrome(
|
|
91
|
+
options: CmsConnection & { out?: string; cwd?: string } = {},
|
|
92
|
+
): Promise<{ file: string; pulled: PulledChrome }> {
|
|
93
|
+
const conn = connection(options)
|
|
94
|
+
const view = await cmsRequest<{ regions: RegionSchema[]; sync: ChromeSyncStatus }>(
|
|
95
|
+
conn,
|
|
96
|
+
'GET',
|
|
97
|
+
'/chrome/schema',
|
|
98
|
+
)
|
|
99
|
+
const pulled: PulledChrome = {
|
|
100
|
+
pulledAt: new Date().toISOString(),
|
|
101
|
+
cms: conn.base,
|
|
102
|
+
sync: view.sync,
|
|
103
|
+
regions: view.regions,
|
|
104
|
+
}
|
|
105
|
+
const file = path.resolve(options.cwd ?? process.cwd(), options.out ?? DEFAULT_SCHEMA_FILE)
|
|
106
|
+
await mkdir(path.dirname(file), { recursive: true })
|
|
107
|
+
await writeFile(file, `${JSON.stringify(pulled, null, 2)}\n`)
|
|
108
|
+
return { file, pulled }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ─── types ──────────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
/** Generate `ChromeFields` from `.prenta/chrome.json`. With `out: '-'` the source is returned, not written. */
|
|
114
|
+
export async function writeChromeTypes(
|
|
115
|
+
options: { in?: string; out?: string; cwd?: string } = {},
|
|
116
|
+
): Promise<{ file: string | null; source: string }> {
|
|
117
|
+
const cwd = options.cwd ?? process.cwd()
|
|
118
|
+
const input = path.resolve(cwd, options.in ?? DEFAULT_SCHEMA_FILE)
|
|
119
|
+
let pulled: PulledChrome
|
|
120
|
+
try {
|
|
121
|
+
pulled = JSON.parse(await readFile(input, 'utf8')) as PulledChrome
|
|
122
|
+
} catch (err) {
|
|
123
|
+
const code = (err as NodeJS.ErrnoException).code
|
|
124
|
+
throw new Error(
|
|
125
|
+
code === 'ENOENT'
|
|
126
|
+
? `${path.relative(cwd, input) || input} doesn't exist yet. Run \`prenta pull chrome\` first.`
|
|
127
|
+
: `Couldn't read ${input}: ${err instanceof Error ? err.message : String(err)}`,
|
|
128
|
+
)
|
|
129
|
+
}
|
|
130
|
+
if (!Array.isArray(pulled.regions)) throw new Error(`${input} has no regions`)
|
|
131
|
+
const source = (await chromeCore()).chromeTypesSource(pulled.regions)
|
|
132
|
+
if (options.out === '-') return { file: null, source }
|
|
133
|
+
const file = path.resolve(cwd, options.out ?? DEFAULT_TYPES_FILE)
|
|
134
|
+
await mkdir(path.dirname(file), { recursive: true })
|
|
135
|
+
await writeFile(file, source)
|
|
136
|
+
return { file, source }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ─── push ───────────────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
/** Every `defineRegion` a config module exports, named or default. */
|
|
142
|
+
export async function collectRegions(mod: unknown): Promise<RegionDefinition[]> {
|
|
143
|
+
if (typeof mod !== 'object' || mod === null) return []
|
|
144
|
+
const { isRegionDefinition } = await chromeCore()
|
|
145
|
+
const found = new Map<string, RegionDefinition>()
|
|
146
|
+
for (const value of Object.values(mod as Record<string, unknown>)) {
|
|
147
|
+
if (isRegionDefinition(value)) {
|
|
148
|
+
if (found.has(value.region)) {
|
|
149
|
+
throw new Error(`The config defines the ${value.region} region twice.`)
|
|
150
|
+
}
|
|
151
|
+
found.set(value.region, value)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return [...found.values()]
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface SchemaSource {
|
|
158
|
+
repo: string
|
|
159
|
+
branch: string
|
|
160
|
+
commit: string
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
type Run = (file: string, args: string[], options: { cwd: string }) => string
|
|
164
|
+
|
|
165
|
+
const runGit: Run = (file, args, options) =>
|
|
166
|
+
execFileSync(file, args, {
|
|
167
|
+
cwd: options.cwd,
|
|
168
|
+
encoding: 'utf8',
|
|
169
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* `git@github.com:owner/repo.git` or `https://github.com/owner/repo` → `owner/repo`.
|
|
174
|
+
* Credentials in the remote (`https://oauth2:TOKEN@host/site.git`) are
|
|
175
|
+
* dropped: the CMS stores the source and shows it to everyone who signs in.
|
|
176
|
+
*/
|
|
177
|
+
export function repoFromRemote(remote: string): string {
|
|
178
|
+
const trimmed = remote.trim()
|
|
179
|
+
let path: string
|
|
180
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
|
|
181
|
+
try {
|
|
182
|
+
path = new URL(trimmed).pathname
|
|
183
|
+
} catch {
|
|
184
|
+
path = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, '')
|
|
185
|
+
}
|
|
186
|
+
} else {
|
|
187
|
+
// scp-like `[user[:password]@]host:owner/repo`.
|
|
188
|
+
path = trimmed.replace(/^[^@/]*@/, '').replace(/^[^:/]+:/, '/')
|
|
189
|
+
}
|
|
190
|
+
const segments = path
|
|
191
|
+
.replace(/\.git\/?$/, '')
|
|
192
|
+
.split('/')
|
|
193
|
+
.filter(Boolean)
|
|
194
|
+
return segments.slice(-2).join('/')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Where the schema comes from: CI variables first (Vercel, GitHub Actions), then git. */
|
|
198
|
+
export function detectSource(
|
|
199
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
200
|
+
cwd = process.cwd(),
|
|
201
|
+
run: Run = runGit,
|
|
202
|
+
): SchemaSource {
|
|
203
|
+
const git = (args: string[]) => {
|
|
204
|
+
try {
|
|
205
|
+
return run('git', args, { cwd }).trim()
|
|
206
|
+
} catch {
|
|
207
|
+
return ''
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const vercelRepo =
|
|
211
|
+
env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG
|
|
212
|
+
? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`
|
|
213
|
+
: ''
|
|
214
|
+
const repo =
|
|
215
|
+
vercelRepo || env.GITHUB_REPOSITORY || repoFromRemote(git(['remote', 'get-url', 'origin']))
|
|
216
|
+
const branch =
|
|
217
|
+
env.VERCEL_GIT_COMMIT_REF || env.GITHUB_REF_NAME || git(['rev-parse', '--abbrev-ref', 'HEAD'])
|
|
218
|
+
const commit = env.VERCEL_GIT_COMMIT_SHA || env.GITHUB_SHA || git(['rev-parse', 'HEAD'])
|
|
219
|
+
return { repo, branch, commit }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export interface PushChromeOptions extends CmsConnection {
|
|
223
|
+
config?: string
|
|
224
|
+
cwd?: string
|
|
225
|
+
dryRun?: boolean
|
|
226
|
+
source?: Partial<SchemaSource>
|
|
227
|
+
/** Loads the config module. Tests pass their own. */
|
|
228
|
+
load?: (file: string) => Promise<unknown>
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The deploy hook: send the regions a config defines to `PUT /chrome/schema`.
|
|
233
|
+
* Needs an admin-scoped API key. A region the config no longer defines loses
|
|
234
|
+
* its schema, and its values are kept as orphans for 30 days.
|
|
235
|
+
*/
|
|
236
|
+
export async function pushChrome(options: PushChromeOptions = {}): Promise<{
|
|
237
|
+
payload: { regions: unknown[]; source: SchemaSource }
|
|
238
|
+
result: ChromeSchemaReadResult | null
|
|
239
|
+
}> {
|
|
240
|
+
const cwd = options.cwd ?? process.cwd()
|
|
241
|
+
const configPath = path.resolve(cwd, options.config ?? 'prenta.config.ts')
|
|
242
|
+
const mod = await (options.load ?? importProjectTypescript)(configPath)
|
|
243
|
+
const regions = await collectRegions(mod)
|
|
244
|
+
if (regions.length === 0) {
|
|
245
|
+
throw new Error(
|
|
246
|
+
`${path.relative(cwd, configPath) || configPath} exports no regions. Export each one: export const header = defineRegion('header', { … }).`,
|
|
247
|
+
)
|
|
248
|
+
}
|
|
249
|
+
const source = { ...detectSource(process.env, cwd), ...options.source }
|
|
250
|
+
const { serializeRegion } = await chromeCore()
|
|
251
|
+
const payload = { regions: regions.map((region) => serializeRegion(region)), source }
|
|
252
|
+
if (options.dryRun) return { payload, result: null }
|
|
253
|
+
const result = await cmsRequest<ChromeSchemaReadResult>(
|
|
254
|
+
connection(options),
|
|
255
|
+
'PUT',
|
|
256
|
+
'/chrome/schema',
|
|
257
|
+
payload,
|
|
258
|
+
)
|
|
259
|
+
return { payload, result }
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function describeRead(result: ChromeSchemaReadResult): string[] {
|
|
263
|
+
return result.regions.map((region) => {
|
|
264
|
+
const parts: string[] = []
|
|
265
|
+
if (region.orphaned.length > 0) {
|
|
266
|
+
parts.push(`kept ${region.orphaned.join(', ')} as orphans for 30 days`)
|
|
267
|
+
}
|
|
268
|
+
for (const { from, to } of region.renamed) parts.push(`moved ${from} to ${to}`)
|
|
269
|
+
if (region.restored.length > 0) parts.push(`restored ${region.restored.join(', ')}`)
|
|
270
|
+
const what = parts.length > 0 ? parts.join('; ') : region.changed ? 'updated' : 'unchanged'
|
|
271
|
+
return `${region.region}: ${what}`
|
|
272
|
+
})
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ─── commands ───────────────────────────────────────────────────────────
|
|
276
|
+
|
|
277
|
+
function fail(err: unknown): void {
|
|
278
|
+
logger.error(err instanceof Error ? err.message : String(err))
|
|
279
|
+
process.exitCode = 1
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export function registerChromeCommand(program: Command): void {
|
|
283
|
+
const pull = program.command('pull').description('Read what the CMS holds into .prenta/')
|
|
284
|
+
pull
|
|
285
|
+
.command('chrome')
|
|
286
|
+
.description('Write the header and footer schema the CMS holds to .prenta/chrome.json')
|
|
287
|
+
.option('--url <url>', 'CMS origin (default: PRENTA_CMS_URL)')
|
|
288
|
+
.option('--key <key>', 'API key with the chrome scope (default: PRENTA_API_KEY)')
|
|
289
|
+
.option('--out <file>', 'Where to write it', DEFAULT_SCHEMA_FILE)
|
|
290
|
+
.action(async (options: { url?: string; key?: string; out?: string }) => {
|
|
291
|
+
try {
|
|
292
|
+
const { file, pulled } = await pullChrome(options)
|
|
293
|
+
const regions = pulled.regions.map((region) => region.region).join(', ') || 'no regions yet'
|
|
294
|
+
logger.success(`Wrote ${path.relative(process.cwd(), file)} (${regions})`)
|
|
295
|
+
} catch (err) {
|
|
296
|
+
fail(err)
|
|
297
|
+
}
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
const push = program.command('push').description('Send what the site defines to the CMS')
|
|
301
|
+
push
|
|
302
|
+
.command('chrome')
|
|
303
|
+
.description(
|
|
304
|
+
'Send the defineRegion schemas in prenta.config.ts to the CMS. Run it on every deploy.',
|
|
305
|
+
)
|
|
306
|
+
.option('--config <path>', 'Config that exports the regions', 'prenta.config.ts')
|
|
307
|
+
.option('--url <url>', 'CMS origin (default: PRENTA_CMS_URL)')
|
|
308
|
+
.option('--key <key>', 'Admin API key (default: PRENTA_API_KEY)')
|
|
309
|
+
.option('--repo <repo>', 'Repository shown as the source (default: from CI or git)')
|
|
310
|
+
.option('--branch <branch>', 'Branch shown as the source (default: from CI or git)')
|
|
311
|
+
.option('--commit <sha>', 'Commit shown as the source (default: from CI or git)')
|
|
312
|
+
.option('--dry-run', 'Print what would be sent, and send nothing')
|
|
313
|
+
.action(
|
|
314
|
+
async (options: {
|
|
315
|
+
config?: string
|
|
316
|
+
url?: string
|
|
317
|
+
key?: string
|
|
318
|
+
repo?: string
|
|
319
|
+
branch?: string
|
|
320
|
+
commit?: string
|
|
321
|
+
dryRun?: boolean
|
|
322
|
+
}) => {
|
|
323
|
+
try {
|
|
324
|
+
const source: Partial<SchemaSource> = {}
|
|
325
|
+
if (options.repo) source.repo = options.repo
|
|
326
|
+
if (options.branch) source.branch = options.branch
|
|
327
|
+
if (options.commit) source.commit = options.commit
|
|
328
|
+
const { payload, result } = await pushChrome({ ...options, source })
|
|
329
|
+
if (!result) {
|
|
330
|
+
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`)
|
|
331
|
+
return
|
|
332
|
+
}
|
|
333
|
+
logger.success(
|
|
334
|
+
`Schema read at ${payload.source.repo || 'unknown repo'}@${payload.source.commit || 'unknown'}`,
|
|
335
|
+
)
|
|
336
|
+
for (const line of describeRead(result)) logger.info(line)
|
|
337
|
+
} catch (err) {
|
|
338
|
+
fail(err)
|
|
339
|
+
}
|
|
340
|
+
},
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
program
|
|
344
|
+
.command('types')
|
|
345
|
+
.description(
|
|
346
|
+
'Generate ChromeFields types from .prenta/chrome.json (run prenta pull chrome first)',
|
|
347
|
+
)
|
|
348
|
+
.option('--in <file>', 'Pulled schema', DEFAULT_SCHEMA_FILE)
|
|
349
|
+
.option('--out <file>', 'Where to write the types ("-" prints them)', DEFAULT_TYPES_FILE)
|
|
350
|
+
.action(async (options: { in?: string; out?: string }) => {
|
|
351
|
+
try {
|
|
352
|
+
const { file, source } = await writeChromeTypes(options)
|
|
353
|
+
if (!file) {
|
|
354
|
+
process.stdout.write(source)
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
logger.success(`Wrote ${path.relative(process.cwd(), file)}`)
|
|
358
|
+
} catch (err) {
|
|
359
|
+
fail(err)
|
|
360
|
+
}
|
|
361
|
+
})
|
|
362
|
+
}
|
package/src/commands/upgrade.ts
CHANGED
|
@@ -5,6 +5,12 @@ import { resolve } from 'node:path'
|
|
|
5
5
|
import { createInterface } from 'node:readline/promises'
|
|
6
6
|
import ora from 'ora'
|
|
7
7
|
import { logger } from '../utils/logger.js'
|
|
8
|
+
import {
|
|
9
|
+
detectInstallCommand,
|
|
10
|
+
displayPath,
|
|
11
|
+
findEnclosingWorkspaceRoot,
|
|
12
|
+
findWorkspaceManifests,
|
|
13
|
+
} from '../utils/workspaces.js'
|
|
8
14
|
|
|
9
15
|
const UPDATE_SERVER_BASE = (
|
|
10
16
|
process.env.PRENTA_UPDATE_SERVER_URL ?? 'https://updates.prenta.io'
|
|
@@ -83,50 +89,125 @@ interface UpgradeOptions {
|
|
|
83
89
|
dryRun?: boolean
|
|
84
90
|
}
|
|
85
91
|
|
|
92
|
+
const DEPENDENCY_SECTIONS = ['dependencies', 'devDependencies', 'optionalDependencies'] as const
|
|
93
|
+
type DependencySection = (typeof DEPENDENCY_SECTIONS)[number]
|
|
94
|
+
|
|
95
|
+
/** A plain `x.y.z`, `^x.y.z` or `~x.y.z` range; anything else (tags, `workspace:`, `file:`) is left alone. */
|
|
96
|
+
const UPGRADABLE_SPEC = /^([\^~]?)(\d+\.\d+\.\d+\S*)$/
|
|
97
|
+
|
|
98
|
+
export interface Manifest {
|
|
99
|
+
path: string
|
|
100
|
+
json: Record<string, unknown>
|
|
101
|
+
indent: string
|
|
102
|
+
eol: string
|
|
103
|
+
trailingNewline: boolean
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface PrentaDependency {
|
|
107
|
+
manifest: Manifest
|
|
108
|
+
section: DependencySection
|
|
109
|
+
name: string
|
|
110
|
+
prefix: string
|
|
111
|
+
current: string
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface PlannedUpgrade extends PrentaDependency {
|
|
115
|
+
to: string
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function readManifest(path: string): Promise<Manifest> {
|
|
119
|
+
const raw = await readFile(path, 'utf-8')
|
|
120
|
+
return {
|
|
121
|
+
path,
|
|
122
|
+
json: JSON.parse(raw) as Record<string, unknown>,
|
|
123
|
+
indent: raw.match(/^([ \t]+)"/m)?.[1] ?? ' ',
|
|
124
|
+
eol: raw.includes('\r\n') ? '\r\n' : '\n',
|
|
125
|
+
trailingNewline: /\r?\n$/.test(raw),
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The root manifest followed by every workspace package manifest under it. */
|
|
130
|
+
export async function readProjectManifests(root: string): Promise<Manifest[]> {
|
|
131
|
+
const paths = [resolve(root, 'package.json'), ...(await findWorkspaceManifests(root))]
|
|
132
|
+
return Promise.all(paths.map(readManifest))
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function collectPrentaDependencies(manifests: Manifest[]): PrentaDependency[] {
|
|
136
|
+
const out: PrentaDependency[] = []
|
|
137
|
+
for (const manifest of manifests) {
|
|
138
|
+
for (const section of DEPENDENCY_SECTIONS) {
|
|
139
|
+
const deps = manifest.json[section]
|
|
140
|
+
if (!deps || typeof deps !== 'object') continue
|
|
141
|
+
for (const [name, spec] of Object.entries(deps as Record<string, unknown>)) {
|
|
142
|
+
if (!name.startsWith('@prenta/') || typeof spec !== 'string') continue
|
|
143
|
+
const match = spec.match(UPGRADABLE_SPEC)
|
|
144
|
+
if (!match) continue
|
|
145
|
+
out.push({ manifest, section, name, prefix: match[1] || '^', current: match[2]! })
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return out
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function planUpgrades(
|
|
153
|
+
deps: PrentaDependency[],
|
|
154
|
+
targets: Record<string, string>,
|
|
155
|
+
): PlannedUpgrade[] {
|
|
156
|
+
return deps
|
|
157
|
+
.filter((d) => targets[d.name] && compareVersions(d.current, targets[d.name]!) < 0)
|
|
158
|
+
.map((d) => ({ ...d, to: targets[d.name]! }))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Rewrites each touched manifest, keeping its indentation and line endings. */
|
|
162
|
+
export async function applyUpgrades(upgrades: PlannedUpgrade[]): Promise<Manifest[]> {
|
|
163
|
+
const touched = new Set<Manifest>()
|
|
164
|
+
for (const u of upgrades) {
|
|
165
|
+
;(u.manifest.json[u.section] as Record<string, string>)[u.name] = `${u.prefix}${u.to}`
|
|
166
|
+
touched.add(u.manifest)
|
|
167
|
+
}
|
|
168
|
+
for (const m of touched) {
|
|
169
|
+
let text = JSON.stringify(m.json, null, m.indent)
|
|
170
|
+
if (m.eol !== '\n') text = text.replace(/\n/g, m.eol)
|
|
171
|
+
await writeFile(m.path, text + (m.trailingNewline ? m.eol : ''), 'utf-8')
|
|
172
|
+
}
|
|
173
|
+
return [...touched]
|
|
174
|
+
}
|
|
175
|
+
|
|
86
176
|
async function runUpgrade(options: UpgradeOptions): Promise<void> {
|
|
87
|
-
const
|
|
177
|
+
const root = process.cwd()
|
|
178
|
+
const pkgPath = resolve(root, 'package.json')
|
|
88
179
|
if (!existsSync(pkgPath)) {
|
|
89
180
|
logger.error('No package.json found in the current directory.')
|
|
90
181
|
process.exit(1)
|
|
91
182
|
}
|
|
92
183
|
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
for (const section of ['dependencies', 'devDependencies'] as const) {
|
|
99
|
-
const deps = pkg[section]
|
|
100
|
-
if (!deps) continue
|
|
101
|
-
for (const [name, version] of Object.entries(deps)) {
|
|
102
|
-
if (name.startsWith('@prenta/') && typeof version === 'string') {
|
|
103
|
-
if (version.startsWith('workspace:')) continue
|
|
104
|
-
prentaPackages.push({
|
|
105
|
-
name,
|
|
106
|
-
current: version.replace(/^[\^~]/, ''),
|
|
107
|
-
section,
|
|
108
|
-
})
|
|
109
|
-
}
|
|
110
|
-
}
|
|
184
|
+
const enclosing = await findEnclosingWorkspaceRoot(root)
|
|
185
|
+
if (enclosing) {
|
|
186
|
+
logger.warn(
|
|
187
|
+
`This is a workspace package. Run "prenta upgrade" from ${enclosing} to upgrade every workspace together.`,
|
|
188
|
+
)
|
|
111
189
|
}
|
|
112
190
|
|
|
191
|
+
const manifests = await readProjectManifests(root)
|
|
192
|
+
const prentaPackages = collectPrentaDependencies(manifests)
|
|
193
|
+
|
|
113
194
|
if (prentaPackages.length === 0) {
|
|
114
|
-
logger.warn(
|
|
195
|
+
logger.warn(
|
|
196
|
+
'No @prenta/* packages found in package.json or its workspaces (excluding workspace: references).',
|
|
197
|
+
)
|
|
115
198
|
return
|
|
116
199
|
}
|
|
117
200
|
|
|
201
|
+
const names = [...new Set(prentaPackages.map((p) => p.name))]
|
|
118
202
|
const spinner = ora('Resolving target versions…').start()
|
|
119
203
|
|
|
120
204
|
let targetVersions: Record<string, string>
|
|
121
205
|
|
|
122
206
|
if (options.version) {
|
|
123
|
-
targetVersions =
|
|
124
|
-
for (const p of prentaPackages) {
|
|
125
|
-
targetVersions[p.name] = options.version
|
|
126
|
-
}
|
|
207
|
+
targetVersions = Object.fromEntries(names.map((name) => [name, options.version!]))
|
|
127
208
|
spinner.succeed(`Target version: ${options.version}`)
|
|
128
209
|
} else {
|
|
129
|
-
targetVersions = await fetchLatestVersions(
|
|
210
|
+
targetVersions = await fetchLatestVersions(names)
|
|
130
211
|
if (Object.keys(targetVersions).length === 0) {
|
|
131
212
|
spinner.fail('Could not resolve target versions.')
|
|
132
213
|
logger.error(
|
|
@@ -138,26 +219,20 @@ async function runUpgrade(options: UpgradeOptions): Promise<void> {
|
|
|
138
219
|
spinner.succeed('Resolved latest versions.')
|
|
139
220
|
}
|
|
140
221
|
|
|
141
|
-
const upgrades
|
|
142
|
-
|
|
143
|
-
for (const p of prentaPackages) {
|
|
144
|
-
const target = targetVersions[p.name]
|
|
145
|
-
if (!target) continue
|
|
146
|
-
if (compareVersions(p.current, target) < 0) {
|
|
147
|
-
upgrades.push({ name: p.name, from: p.current, to: target, section: p.section })
|
|
148
|
-
}
|
|
149
|
-
}
|
|
222
|
+
const upgrades = planUpgrades(prentaPackages, targetVersions)
|
|
150
223
|
|
|
151
224
|
if (upgrades.length === 0) {
|
|
152
225
|
logger.success('All @prenta/* packages are already up to date.')
|
|
153
226
|
return
|
|
154
227
|
}
|
|
155
228
|
|
|
229
|
+
const where = (u: PlannedUpgrade) => displayPath(root, u.manifest.path)
|
|
230
|
+
const fileWidth = Math.max('File'.length, ...upgrades.map((u) => where(u).length)) + 2
|
|
156
231
|
console.log('\n Proposed upgrades:\n')
|
|
157
|
-
console.log(' ' + 'Package'.padEnd(30) + 'From'.padEnd(14) + 'To')
|
|
158
|
-
console.log(' ' + '-'.repeat(54))
|
|
232
|
+
console.log(' ' + 'Package'.padEnd(30) + 'File'.padEnd(fileWidth) + 'From'.padEnd(14) + 'To')
|
|
233
|
+
console.log(' ' + '-'.repeat(54 + fileWidth))
|
|
159
234
|
for (const u of upgrades) {
|
|
160
|
-
console.log(` ${u.name.padEnd(30)}${u.
|
|
235
|
+
console.log(` ${u.name.padEnd(30)}${where(u).padEnd(fileWidth)}${u.current.padEnd(14)}${u.to}`)
|
|
161
236
|
}
|
|
162
237
|
console.log()
|
|
163
238
|
|
|
@@ -166,21 +241,17 @@ async function runUpgrade(options: UpgradeOptions): Promise<void> {
|
|
|
166
241
|
return
|
|
167
242
|
}
|
|
168
243
|
|
|
169
|
-
const
|
|
244
|
+
const files = [...new Set(upgrades.map(where))]
|
|
245
|
+
const proceed = await confirm(`Apply these upgrades to ${files.join(', ')}?`)
|
|
170
246
|
if (!proceed) {
|
|
171
247
|
logger.warn('Upgrade cancelled.')
|
|
172
248
|
return
|
|
173
249
|
}
|
|
174
250
|
|
|
175
|
-
|
|
176
|
-
const prefix = pkg[u.section][u.name]?.match(/^[\^~]/)?.[0] ?? '^'
|
|
177
|
-
pkg[u.section][u.name] = `${prefix}${u.to}`
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf-8')
|
|
251
|
+
await applyUpgrades(upgrades)
|
|
181
252
|
|
|
182
|
-
logger.success(`Updated ${upgrades.length}
|
|
183
|
-
logger.info(
|
|
253
|
+
logger.success(`Updated ${upgrades.length} dependency range(s) in ${files.join(', ')}.`)
|
|
254
|
+
logger.info(`Run "${detectInstallCommand(root)}" to apply the upgrade.`)
|
|
184
255
|
|
|
185
256
|
// A cms-core bump can introduce new models/migrations. Bumping the version
|
|
186
257
|
// alone leaves the consumer's Prisma schema stale, so point them at db:sync.
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
2
3
|
import { Command } from 'commander'
|
|
3
4
|
import { registerMigrateCommand } from './commands/migrate.js'
|
|
4
5
|
import { registerMigrateSectionsCommand } from './commands/migrate-sections.js'
|
|
@@ -26,13 +27,21 @@ import {
|
|
|
26
27
|
} from './commands/doctor.js'
|
|
27
28
|
import { registerVercelBlobLinkCommand } from './commands/vercel-blob-link.js'
|
|
28
29
|
import { registerMcpCommand } from './commands/mcp.js'
|
|
30
|
+
import { registerChromeCommand } from './commands/chrome.js'
|
|
31
|
+
|
|
32
|
+
const { version } = JSON.parse(
|
|
33
|
+
readFileSync(new URL('../package.json', import.meta.url), 'utf-8'),
|
|
34
|
+
) as { version: string }
|
|
29
35
|
|
|
30
36
|
const program = new Command()
|
|
31
37
|
|
|
32
38
|
program
|
|
33
39
|
.name('prenta')
|
|
34
40
|
.description('Prenta CMS — CLI toolkit for migrations, codegen, and more')
|
|
35
|
-
.version(
|
|
41
|
+
.version(version)
|
|
42
|
+
// Program options only before the subcommand, so `prenta upgrade --version <ver>`
|
|
43
|
+
// reaches upgrade instead of printing the CLI version.
|
|
44
|
+
.enablePositionalOptions()
|
|
36
45
|
|
|
37
46
|
registerMigrateCommand(program)
|
|
38
47
|
registerMigrateSectionsCommand(program)
|
|
@@ -58,5 +67,6 @@ registerDeployCheckCommand(program)
|
|
|
58
67
|
registerVerifyCommand(program)
|
|
59
68
|
registerVercelBlobLinkCommand(program)
|
|
60
69
|
registerMcpCommand(program)
|
|
70
|
+
registerChromeCommand(program)
|
|
61
71
|
|
|
62
72
|
program.parse()
|