@prenta/cli 1.1.0 → 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.
@@ -0,0 +1,143 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile, readdir } from 'node:fs/promises';
3
+ import { dirname, join, relative, resolve, sep } from 'node:path';
4
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.next', '.turbo']);
5
+ /**
6
+ * Workspace package patterns declared by `root`: npm/yarn/bun `workspaces`
7
+ * (array or `{ packages }`) and pnpm's `pnpm-workspace.yaml` `packages` list.
8
+ */
9
+ export async function readWorkspacePatterns(root) {
10
+ const patterns = [];
11
+ const pkgPath = join(root, 'package.json');
12
+ if (existsSync(pkgPath)) {
13
+ const pkg = JSON.parse(await readFile(pkgPath, 'utf-8'));
14
+ const ws = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages;
15
+ if (Array.isArray(ws))
16
+ patterns.push(...ws.filter((p) => typeof p === 'string'));
17
+ }
18
+ const pnpmPath = join(root, 'pnpm-workspace.yaml');
19
+ if (existsSync(pnpmPath))
20
+ patterns.push(...parsePnpmWorkspacePackages(await readFile(pnpmPath, 'utf-8')));
21
+ return patterns;
22
+ }
23
+ function unquote(value) {
24
+ return value.trim().replace(/^(['"])(.*)\1$/, '$2');
25
+ }
26
+ /**
27
+ * The `packages:` list of a pnpm-workspace.yaml: a block sequence (indented
28
+ * or at column 0) or a flow sequence (`packages: [a, "b"]`).
29
+ */
30
+ export function parsePnpmWorkspacePackages(yaml) {
31
+ const out = [];
32
+ let inPackages = false;
33
+ for (const rawLine of yaml.split(/\r?\n/)) {
34
+ const line = rawLine.replace(/(^|\s)#.*$/, '').trimEnd();
35
+ const key = line.match(/^packages\s*:\s*(.*)$/);
36
+ if (key) {
37
+ const rest = key[1].trim();
38
+ const flow = rest.match(/^\[(.*)\]$/);
39
+ if (flow)
40
+ out.push(...flow[1].split(',').map(unquote).filter(Boolean));
41
+ inPackages = rest === '';
42
+ continue;
43
+ }
44
+ if (!inPackages || !line.trim())
45
+ continue;
46
+ const item = line.match(/^\s*-\s+(.+)$/);
47
+ if (item)
48
+ out.push(unquote(item[1]));
49
+ else if (!/^\s/.test(line))
50
+ inPackages = false;
51
+ }
52
+ return out;
53
+ }
54
+ /** Directories under `root` matching `pattern` (`*` one level, `**` any depth). */
55
+ async function expandPattern(root, pattern) {
56
+ const segments = pattern.replace(/^\.\//, '').replace(/\/+$/, '').split('/').filter(Boolean);
57
+ let current = [root];
58
+ for (const segment of segments) {
59
+ const next = [];
60
+ for (const dir of current) {
61
+ if (segment === '**')
62
+ next.push(dir, ...(await subdirectories(dir, Infinity)));
63
+ else if (segment.includes('*')) {
64
+ const re = new RegExp(`^${segment.split('*').map(escapeRegExp).join('[^/]*')}$`);
65
+ for (const child of await subdirectories(dir, 1)) {
66
+ if (re.test(child.slice(dir.length + 1)))
67
+ next.push(child);
68
+ }
69
+ }
70
+ else
71
+ next.push(join(dir, segment));
72
+ }
73
+ current = next;
74
+ }
75
+ return current;
76
+ }
77
+ async function subdirectories(dir, depth) {
78
+ if (depth <= 0)
79
+ return [];
80
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
81
+ const out = [];
82
+ for (const entry of entries) {
83
+ // Symlinked directories aren't followed (`isDirectory()` is false for links), so `**` can't loop.
84
+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name))
85
+ continue;
86
+ const child = join(dir, entry.name);
87
+ out.push(child, ...(await subdirectories(child, depth - 1)));
88
+ }
89
+ return out;
90
+ }
91
+ function escapeRegExp(value) {
92
+ return value.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
93
+ }
94
+ /**
95
+ * `package.json` paths of the workspace packages under `root` (not including
96
+ * the root manifest), sorted. `!pattern` entries exclude matches.
97
+ */
98
+ export async function findWorkspaceManifests(root) {
99
+ const patterns = await readWorkspacePatterns(root);
100
+ const include = new Set();
101
+ const exclude = new Set();
102
+ for (const pattern of patterns) {
103
+ const negated = pattern.startsWith('!');
104
+ for (const dir of await expandPattern(root, negated ? pattern.slice(1) : pattern)) {
105
+ const manifest = join(dir, 'package.json');
106
+ if (resolve(dir) === resolve(root) || !existsSync(manifest))
107
+ continue;
108
+ (negated ? exclude : include).add(resolve(manifest));
109
+ }
110
+ }
111
+ return [...include].filter((m) => !exclude.has(m)).sort();
112
+ }
113
+ /**
114
+ * The nearest ancestor of `cwd` that declares workspaces including `cwd`, or
115
+ * null. Lets `prenta upgrade` warn when it runs inside a workspace package.
116
+ */
117
+ export async function findEnclosingWorkspaceRoot(cwd) {
118
+ let dir = dirname(resolve(cwd));
119
+ while (dir !== dirname(dir)) {
120
+ if ((await readWorkspacePatterns(dir)).length > 0) {
121
+ const manifests = await findWorkspaceManifests(dir);
122
+ if (manifests.includes(resolve(cwd, 'package.json')))
123
+ return dir;
124
+ }
125
+ dir = dirname(dir);
126
+ }
127
+ return null;
128
+ }
129
+ /** Install command for the package manager whose lockfile is in `root`. */
130
+ export function detectInstallCommand(root) {
131
+ if (existsSync(join(root, 'pnpm-lock.yaml')))
132
+ return 'pnpm install';
133
+ if (existsSync(join(root, 'yarn.lock')))
134
+ return 'yarn install';
135
+ if (existsSync(join(root, 'bun.lock')) || existsSync(join(root, 'bun.lockb')))
136
+ return 'bun install';
137
+ return 'npm install';
138
+ }
139
+ /** `root`-relative display path using forward slashes. */
140
+ export function displayPath(root, file) {
141
+ return relative(root, file).split(sep).join('/');
142
+ }
143
+ //# sourceMappingURL=workspaces.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspaces.js","sourceRoot":"","sources":["../../src/utils/workspaces.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,W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AAC,IAAI,EAAE,WAAW,CAAC,CAAC;QAAE,OAAO,cAAc,CAAA;IAC9D,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QAC3E,OAAO,aAAa,CAAA;IACtB,OAAO,aAAa,CAAA;AACtB,CAAC;AAED,0DAA0D;AAC1D,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,IAAY;IACpD,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAClD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prenta/cli",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "license": "MIT",
5
5
  "description": "CLI for Prenta CMS — migrations, codegen, imports, exports, and upgrades",
6
6
  "repository": {
@@ -35,8 +35,8 @@
35
35
  "devDependencies": {
36
36
  "@vercel/blob": "^2.3.1",
37
37
  "typescript": "^5.7.0",
38
- "vitest": "^4.1.0",
39
- "@prenta/core": "8.10.0"
38
+ "vitest": "^4.1.12",
39
+ "@prenta/core": "8.16.1"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsc",
@@ -0,0 +1,215 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { readFileSync } from 'node:fs'
3
+ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
8
+
9
+ import {
10
+ applyUpgrades,
11
+ collectPrentaDependencies,
12
+ planUpgrades,
13
+ readProjectManifests,
14
+ } from '../commands/upgrade.js'
15
+ import {
16
+ detectInstallCommand,
17
+ findEnclosingWorkspaceRoot,
18
+ findWorkspaceManifests,
19
+ parsePnpmWorkspacePackages,
20
+ } from '../utils/workspaces.js'
21
+
22
+ let root: string
23
+
24
+ async function writeJson(path: string, value: unknown, indent: string | number = 2, eol = '\n') {
25
+ await mkdir(join(path, '..'), { recursive: true })
26
+ await writeFile(path, JSON.stringify(value, null, indent).replace(/\n/g, eol) + eol)
27
+ }
28
+
29
+ beforeEach(async () => {
30
+ root = await mkdtemp(join(tmpdir(), 'prenta-upgrade-'))
31
+ })
32
+ afterEach(async () => {
33
+ await rm(root, { recursive: true, force: true })
34
+ })
35
+
36
+ const TARGETS = {
37
+ '@prenta/admin': '2.11.1',
38
+ '@prenta/core': '8.16.1',
39
+ '@prenta/sections-react': '0.20.1',
40
+ }
41
+
42
+ describe('prenta upgrade in an npm workspace (#1096)', () => {
43
+ beforeEach(async () => {
44
+ await writeJson(join(root, 'package.json'), {
45
+ name: 'upchat',
46
+ workspaces: ['site'],
47
+ dependencies: {
48
+ '@prenta/admin': '^2.10.0',
49
+ '@prenta/core': '^8.15.0',
50
+ '@prenta/sections-react': '^0.19.0',
51
+ },
52
+ })
53
+ await writeJson(
54
+ join(root, 'site', 'package.json'),
55
+ {
56
+ name: 'site',
57
+ dependencies: {
58
+ '@prenta/core': '^8.13.3',
59
+ '@prenta/sections-react': '^0.18.11',
60
+ astro: '^5.0.0',
61
+ },
62
+ },
63
+ 4,
64
+ '\r\n',
65
+ )
66
+ })
67
+
68
+ it('upgrades the workspace manifest too, so every workspace lands on the same versions', async () => {
69
+ const manifests = await readProjectManifests(root)
70
+ const upgrades = planUpgrades(collectPrentaDependencies(manifests), TARGETS)
71
+ await applyUpgrades(upgrades)
72
+
73
+ const rootPkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf-8'))
74
+ const site = JSON.parse(await readFile(join(root, 'site', 'package.json'), 'utf-8'))
75
+ expect(rootPkg.dependencies).toEqual({
76
+ '@prenta/admin': '^2.11.1',
77
+ '@prenta/core': '^8.16.1',
78
+ '@prenta/sections-react': '^0.20.1',
79
+ })
80
+ expect(site.dependencies).toEqual({
81
+ '@prenta/core': '^8.16.1',
82
+ '@prenta/sections-react': '^0.20.1',
83
+ astro: '^5.0.0',
84
+ })
85
+ })
86
+
87
+ it('keeps each manifest’s indentation and line endings', async () => {
88
+ const manifests = await readProjectManifests(root)
89
+ await applyUpgrades(planUpgrades(collectPrentaDependencies(manifests), TARGETS))
90
+ const raw = await readFile(join(root, 'site', 'package.json'), 'utf-8')
91
+ expect(raw).toContain('\r\n "name": "site"')
92
+ expect(raw.endsWith('}\r\n')).toBe(true)
93
+ expect(raw.replace(/\r\n/g, '')).not.toContain('\n')
94
+ })
95
+
96
+ it('leaves workspace:, tag and file: specs alone', async () => {
97
+ await writeJson(join(root, 'site', 'package.json'), {
98
+ name: 'site',
99
+ dependencies: {
100
+ '@prenta/core': 'workspace:*',
101
+ '@prenta/sections-react': 'latest',
102
+ '@prenta/client': 'file:../client',
103
+ },
104
+ })
105
+ const deps = collectPrentaDependencies(await readProjectManifests(root))
106
+ expect(deps.map((d) => d.manifest.path)).not.toContain(join(root, 'site', 'package.json'))
107
+ })
108
+
109
+ it('warns from inside a workspace package', async () => {
110
+ expect(await findEnclosingWorkspaceRoot(join(root, 'site'))).toBe(root)
111
+ expect(await findEnclosingWorkspaceRoot(root)).toBeNull()
112
+ })
113
+
114
+ it('names the install command for the lockfile in use', async () => {
115
+ expect(detectInstallCommand(root)).toBe('npm install')
116
+ await writeFile(join(root, 'pnpm-lock.yaml'), '')
117
+ expect(detectInstallCommand(root)).toBe('pnpm install')
118
+ })
119
+ })
120
+
121
+ describe('the prenta CLI', () => {
122
+ const cli = fileURLToPath(new URL('../index.ts', import.meta.url))
123
+ // Resolved here: the fixture directory has no node_modules to find tsx in.
124
+ const tsx = import.meta.resolve('tsx')
125
+ const run = (args: string[], cwd: string) =>
126
+ execFileSync(process.execPath, ['--import', tsx, cli, ...args], { cwd, encoding: 'utf-8' })
127
+
128
+ it('passes `upgrade --version <ver>` to upgrade instead of printing the CLI version', async () => {
129
+ await writeJson(join(root, 'package.json'), {
130
+ workspaces: ['site'],
131
+ dependencies: { '@prenta/core': '^8.15.0' },
132
+ })
133
+ await writeJson(join(root, 'site', 'package.json'), {
134
+ dependencies: { '@prenta/core': '^8.13.3' },
135
+ })
136
+ const out = run(['upgrade', '--version', '9.0.0', '--dry-run'], root)
137
+ expect(out).toMatch(/@prenta\/core\s+site\/package\.json\s+8\.13\.3\s+9\.0\.0/)
138
+ expect(out).toContain('Dry run')
139
+ }, 60_000)
140
+
141
+ it('prints its own package version for `prenta --version`', () => {
142
+ const { version } = JSON.parse(
143
+ readFileSync(new URL('../../package.json', import.meta.url), 'utf-8'),
144
+ ) as { version: string }
145
+ expect(run(['--version'], root).trim()).toBe(version)
146
+ }, 60_000)
147
+ })
148
+
149
+ describe('workspace discovery', () => {
150
+ it('expands globs, the object form, and negations', async () => {
151
+ await writeJson(join(root, 'package.json'), {
152
+ workspaces: { packages: ['apps/*', 'packages/**', '!packages/private'] },
153
+ })
154
+ for (const dir of [
155
+ 'apps/web',
156
+ 'apps/docs',
157
+ 'packages/a',
158
+ 'packages/nested/b',
159
+ 'packages/private',
160
+ ]) {
161
+ await writeJson(join(root, dir, 'package.json'), { name: dir })
162
+ }
163
+ await mkdir(join(root, 'apps', 'no-manifest'), { recursive: true })
164
+ await writeJson(join(root, 'packages', 'a', 'node_modules', 'x', 'package.json'), { name: 'x' })
165
+
166
+ const found = (await findWorkspaceManifests(root)).map((p) =>
167
+ p.slice(root.length + 1).replace(/\\/g, '/'),
168
+ )
169
+ expect(found).toEqual([
170
+ 'apps/docs/package.json',
171
+ 'apps/web/package.json',
172
+ 'packages/a/package.json',
173
+ 'packages/nested/b/package.json',
174
+ ])
175
+ })
176
+
177
+ it('reads pnpm-workspace.yaml', async () => {
178
+ await writeJson(join(root, 'package.json'), { name: 'root' })
179
+ await writeFile(
180
+ join(root, 'pnpm-workspace.yaml'),
181
+ 'packages:\n - "apps/*"\n - \'site\' # the public site\ncatalog:\n react: ^19\n',
182
+ )
183
+ await writeJson(join(root, 'apps', 'admin', 'package.json'), { name: 'admin' })
184
+ await writeJson(join(root, 'site', 'package.json'), { name: 'site' })
185
+ expect(
186
+ parsePnpmWorkspacePackages(await readFile(join(root, 'pnpm-workspace.yaml'), 'utf-8')),
187
+ ).toEqual(['apps/*', 'site'])
188
+ expect(await findWorkspaceManifests(root)).toHaveLength(2)
189
+ })
190
+
191
+ it('reads pnpm lists at column 0 and flow sequences', () => {
192
+ expect(
193
+ parsePnpmWorkspacePackages(
194
+ 'packages:\n- site\n- "apps/*"\nonlyBuiltDependencies:\n- esbuild\n',
195
+ ),
196
+ ).toEqual(['site', 'apps/*'])
197
+ expect(parsePnpmWorkspacePackages('packages: [site, "apps/*", \'docs\']\n')).toEqual([
198
+ 'site',
199
+ 'apps/*',
200
+ 'docs',
201
+ ])
202
+ })
203
+
204
+ it('follows ** to any depth', async () => {
205
+ await writeJson(join(root, 'package.json'), { workspaces: ['packages/**'] })
206
+ const deep = join(root, 'packages', 'a', 'b', 'c', 'd', 'e', 'f', 'g')
207
+ await writeJson(join(deep, 'package.json'), { name: 'deep' })
208
+ expect(await findWorkspaceManifests(root)).toEqual([join(deep, 'package.json')])
209
+ })
210
+
211
+ it('treats a project without workspaces as a single manifest', async () => {
212
+ await writeJson(join(root, 'package.json'), { dependencies: { '@prenta/core': '^8.0.0' } })
213
+ expect(await readProjectManifests(root)).toHaveLength(1)
214
+ })
215
+ })
@@ -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 pkgPath = resolve(process.cwd(), 'package.json')
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 raw = await readFile(pkgPath, 'utf-8')
94
- const pkg = JSON.parse(raw)
95
-
96
- const prentaPackages: { name: string; current: string; section: string }[] = []
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('No @prenta/* packages found in package.json (excluding workspace: references).')
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(prentaPackages.map((p) => p.name))
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: { name: string; from: string; to: string; section: string }[] = []
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.from.padEnd(14)}${u.to}`)
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 proceed = await confirm('Apply these upgrades to package.json?')
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
- for (const u of upgrades) {
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} package(s) in package.json.`)
183
- logger.info('Run "pnpm install" to apply the upgrade.')
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'
@@ -28,12 +29,19 @@ import { registerVercelBlobLinkCommand } from './commands/vercel-blob-link.js'
28
29
  import { registerMcpCommand } from './commands/mcp.js'
29
30
  import { registerChromeCommand } from './commands/chrome.js'
30
31
 
32
+ const { version } = JSON.parse(
33
+ readFileSync(new URL('../package.json', import.meta.url), 'utf-8'),
34
+ ) as { version: string }
35
+
31
36
  const program = new Command()
32
37
 
33
38
  program
34
39
  .name('prenta')
35
40
  .description('Prenta CMS — CLI toolkit for migrations, codegen, and more')
36
- .version('0.1.0')
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()
37
45
 
38
46
  registerMigrateCommand(program)
39
47
  registerMigrateSectionsCommand(program)