@postxl/cli 1.8.3 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function register(program: Command): void;
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.register = register;
37
+ const fs = __importStar(require("node:fs/promises"));
38
+ const path = __importStar(require("node:path"));
39
+ const generator_1 = require("@postxl/generator");
40
+ const utils_1 = require("@postxl/utils");
41
+ const cli_helpers_1 = require("./helpers/cli-helpers");
42
+ function register(program) {
43
+ const cmd = program.command('custom-block').summary('List or validate custom code blocks across the project.');
44
+ cmd
45
+ .command('list')
46
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
47
+ .option('-j, --json', 'machine-readable output')
48
+ .action(async (inputPath, options) => {
49
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(inputPath, program);
50
+ const { blocks } = await scanProject(projectPath);
51
+ if (options.json) {
52
+ process.stdout.write(JSON.stringify({ blocks }, null, 2) + '\n');
53
+ return;
54
+ }
55
+ if (blocks.length === 0) {
56
+ console.log((0, utils_1.gray)('No custom blocks found.'));
57
+ return;
58
+ }
59
+ const grouped = new Map();
60
+ for (const b of blocks) {
61
+ if (!grouped.has(b.file)) {
62
+ grouped.set(b.file, []);
63
+ }
64
+ grouped.get(b.file).push(b);
65
+ }
66
+ for (const [file, list] of [...grouped.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
67
+ console.log(file);
68
+ for (const b of list) {
69
+ const name = b.name ?? (0, utils_1.gray)('(anonymous)');
70
+ const anchor = b.anchor ? ` anchor: ${(0, utils_1.gray)(b.anchor)}` : '';
71
+ console.log(` ${name.padEnd(24)} lines ${b.startLine}-${b.endLine}${anchor}`);
72
+ }
73
+ console.log();
74
+ }
75
+ });
76
+ cmd
77
+ .command('check')
78
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
79
+ .option('-j, --json', 'machine-readable output')
80
+ .action(async (inputPath, options) => {
81
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(inputPath, program);
82
+ const { blocks, errors } = await scanProject(projectPath);
83
+ // Validate name uniqueness per file (the extractor catches start/end pairing
84
+ // and name mismatch, but not duplicate names within a file).
85
+ const dupeErrors = [];
86
+ const byFile = new Map();
87
+ for (const b of blocks) {
88
+ if (!byFile.has(b.file)) {
89
+ byFile.set(b.file, []);
90
+ }
91
+ byFile.get(b.file).push(b);
92
+ }
93
+ for (const [file, list] of byFile) {
94
+ const seen = new Map();
95
+ for (const b of list) {
96
+ if (b.name === null) {
97
+ continue;
98
+ }
99
+ const prior = seen.get(b.name);
100
+ if (prior !== undefined) {
101
+ dupeErrors.push({
102
+ file,
103
+ type: 'duplicate_name',
104
+ message: `Duplicate custom block name "${b.name}" in this file (also at line ${prior})`,
105
+ line: b.startLine,
106
+ });
107
+ }
108
+ else {
109
+ seen.set(b.name, b.startLine);
110
+ }
111
+ }
112
+ }
113
+ const allErrors = [...errors, ...dupeErrors];
114
+ if (options.json) {
115
+ process.stdout.write(JSON.stringify({ ok: allErrors.length === 0, errors: allErrors }, null, 2) + '\n');
116
+ process.exit(allErrors.length === 0 ? 0 : 1);
117
+ }
118
+ if (allErrors.length === 0) {
119
+ console.log((0, utils_1.green)(`✓ All custom blocks are healthy (${blocks.length} blocks across ${byFile.size} files).`));
120
+ return;
121
+ }
122
+ console.log((0, utils_1.red)(`✗ Found ${allErrors.length} problem${allErrors.length === 1 ? '' : 's'}:`));
123
+ const groupedErr = new Map();
124
+ for (const e of allErrors) {
125
+ if (!groupedErr.has(e.file)) {
126
+ groupedErr.set(e.file, []);
127
+ }
128
+ groupedErr.get(e.file).push(e);
129
+ }
130
+ for (const [file, list] of [...groupedErr.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
131
+ console.log();
132
+ console.log((0, utils_1.yellow)(file));
133
+ for (const e of list) {
134
+ console.log(` line ${e.line}: ${e.message} ${(0, utils_1.gray)(`(${e.type})`)}`);
135
+ }
136
+ }
137
+ process.exit(1);
138
+ });
139
+ }
140
+ /**
141
+ * Scan all files known to the lock file (i.e., generated paths) for custom blocks.
142
+ * We restrict the scan to lock-file paths to avoid accidentally pulling in
143
+ * dependencies' files or otherwise blowing up on huge directories.
144
+ */
145
+ async function scanProject(projectPath) {
146
+ const lockFile = await (0, generator_1.readLockFile)(path.join(projectPath, 'postxl-lock.json'));
147
+ const blocks = [];
148
+ const errors = [];
149
+ if (!lockFile) {
150
+ return { blocks, errors };
151
+ }
152
+ for (const [lockPath] of lockFile) {
153
+ const absPath = path.join(projectPath, lockPath);
154
+ let content;
155
+ try {
156
+ const raw = await fs.readFile(absPath);
157
+ // Skip binary files (custom blocks are line-based).
158
+ if ((0, cli_helpers_1.looksBinary)(raw)) {
159
+ continue;
160
+ }
161
+ content = raw.toString('utf8');
162
+ }
163
+ catch {
164
+ continue;
165
+ }
166
+ if (!(0, generator_1.hasCustomBlockMarkers)(content)) {
167
+ continue;
168
+ }
169
+ const result = (0, generator_1.extractCustomBlocks)(content);
170
+ const display = String(lockPath).replace(/^\/+/, '').replace(/^\.\//, '');
171
+ for (const b of result.blocks) {
172
+ blocks.push({
173
+ file: display,
174
+ name: b.name ?? null,
175
+ startLine: b.startLineIndex + 1,
176
+ endLine: b.endLineIndex + 1,
177
+ anchor: b.enclosingMemberName ?? null,
178
+ });
179
+ }
180
+ for (const e of result.errors) {
181
+ errors.push({ file: display, type: e.type, message: e.message, line: e.lineIndex + 1 });
182
+ }
183
+ }
184
+ return { blocks, errors };
185
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function register(program: Command): void;
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.register = register;
37
+ const fs = __importStar(require("node:fs/promises"));
38
+ const path = __importStar(require("node:path"));
39
+ const generator_1 = require("@postxl/generator");
40
+ const schema_1 = require("@postxl/schema");
41
+ const utils_1 = require("@postxl/utils");
42
+ const cli_helpers_1 = require("./helpers/cli-helpers");
43
+ const load_project_schema_1 = require("./helpers/load-project-schema");
44
+ const project_status_1 = require("./helpers/project-status");
45
+ function register(program) {
46
+ program
47
+ .command('doctor')
48
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
49
+ .summary('Composite preflight: schema, drift, custom blocks, env, migrations.')
50
+ .description(`Bundles validate + lockfile sanity + custom-block check + .env presence + Prisma migration drift detection into one command.`)
51
+ .option('-j, --json', 'machine-readable output')
52
+ .action(async (inputPath, options) => {
53
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(inputPath, program);
54
+ const checks = [];
55
+ checks.push(await checkSchemaValidates(projectPath, program));
56
+ const status = await (0, project_status_1.computeProjectStatus)({ projectPath });
57
+ checks.push(checkNoDrift(status));
58
+ checks.push(checkNoOrphans(status));
59
+ checks.push(checkNoUntracked(status));
60
+ checks.push(await checkCustomBlocks(projectPath));
61
+ checks.push(await checkEnvPresent(projectPath));
62
+ checks.push(await checkPrismaMigrations(projectPath));
63
+ checks.push(await checkLockfileSorted(projectPath));
64
+ const exitCode = computeExitCode(checks);
65
+ if (options.json) {
66
+ process.stdout.write(JSON.stringify({ checks, exitCode }, null, 2) + '\n');
67
+ process.exit(exitCode);
68
+ }
69
+ for (const c of checks) {
70
+ const tag = c.severity === 'pass'
71
+ ? (0, utils_1.green)('PASS')
72
+ : c.severity === 'warn'
73
+ ? (0, utils_1.yellow)('WARN')
74
+ : c.severity === 'fail'
75
+ ? (0, utils_1.red)('FAIL')
76
+ : (0, utils_1.gray)('INFO');
77
+ console.log(`${tag} ${c.name.padEnd(36)} ${(0, utils_1.gray)(c.detail)}`);
78
+ }
79
+ process.exit(exitCode);
80
+ });
81
+ }
82
+ function computeExitCode(checks) {
83
+ if (checks.some((c) => c.severity === 'fail')) {
84
+ return 1;
85
+ }
86
+ // warns don't fail the run.
87
+ return 0;
88
+ }
89
+ async function checkSchemaValidates(projectPath, program) {
90
+ try {
91
+ const raw = await (0, load_project_schema_1.loadAndMergeRawSchema)({ projectPath, program });
92
+ const result = schema_1.zProjectSchema.safeParse(raw);
93
+ if (result.success) {
94
+ return {
95
+ name: 'Schema validates',
96
+ severity: 'pass',
97
+ detail: `${result.data.modelNames.length} models, ${result.data.enumNames.length} enums`,
98
+ };
99
+ }
100
+ return {
101
+ name: 'Schema validates',
102
+ severity: 'fail',
103
+ detail: `${result.error.issues.length} issue${result.error.issues.length === 1 ? '' : 's'}`,
104
+ };
105
+ }
106
+ catch (e) {
107
+ return { name: 'Schema validates', severity: 'fail', detail: e.message };
108
+ }
109
+ }
110
+ function checkNoDrift(status) {
111
+ const n = status.counts.modified ?? 0;
112
+ if (n === 0) {
113
+ return { name: 'No drift', severity: 'pass', detail: 'no modified files' };
114
+ }
115
+ return {
116
+ name: 'No drift',
117
+ severity: 'warn',
118
+ detail: `${n} modified file${n === 1 ? '' : 's'} (run \`pxl status -m\`)`,
119
+ };
120
+ }
121
+ function checkNoOrphans(status) {
122
+ const n = status.counts.orphan ?? 0;
123
+ if (n === 0) {
124
+ return { name: 'No orphans', severity: 'pass', detail: 'no orphan lockfile entries' };
125
+ }
126
+ return { name: 'No orphans', severity: 'warn', detail: `${n} orphan entr${n === 1 ? 'y' : 'ies'}` };
127
+ }
128
+ function checkNoUntracked(status) {
129
+ const n = status.counts['untracked-generated'] ?? 0;
130
+ if (n === 0) {
131
+ return { name: 'No untracked-generated files', severity: 'pass', detail: 'all files in generated dirs are tracked' };
132
+ }
133
+ return { name: 'No untracked-generated files', severity: 'warn', detail: `${n} untracked file${n === 1 ? '' : 's'}` };
134
+ }
135
+ async function checkCustomBlocks(projectPath) {
136
+ const lockFile = await (0, generator_1.readLockFile)(path.join(projectPath, 'postxl-lock.json'));
137
+ if (!lockFile) {
138
+ return { name: 'Custom blocks healthy', severity: 'pass', detail: 'no lockfile to scan' };
139
+ }
140
+ let totalErrors = 0;
141
+ let totalBlocks = 0;
142
+ for (const [lockPath] of lockFile) {
143
+ let content;
144
+ try {
145
+ const buf = await fs.readFile(path.join(projectPath, String(lockPath)));
146
+ if ((0, cli_helpers_1.looksBinary)(buf)) {
147
+ continue;
148
+ }
149
+ content = buf.toString('utf8');
150
+ }
151
+ catch {
152
+ continue;
153
+ }
154
+ if (!(0, generator_1.hasCustomBlockMarkers)(content)) {
155
+ continue;
156
+ }
157
+ const result = (0, generator_1.extractCustomBlocks)(content);
158
+ totalBlocks += result.blocks.length;
159
+ totalErrors += result.errors.length;
160
+ }
161
+ if (totalErrors === 0) {
162
+ return {
163
+ name: 'Custom blocks healthy',
164
+ severity: 'pass',
165
+ detail: `${totalBlocks} block${totalBlocks === 1 ? '' : 's'} verified`,
166
+ };
167
+ }
168
+ return {
169
+ name: 'Custom blocks healthy',
170
+ severity: 'fail',
171
+ detail: `${totalErrors} error${totalErrors === 1 ? '' : 's'} (run \`pxl custom-block check\`)`,
172
+ };
173
+ }
174
+ async function checkEnvPresent(projectPath) {
175
+ // Same candidate list as `pxl info`. Pass when any candidate exists, warn
176
+ // when none do — projects with non-standard layouts won't always have
177
+ // `backend/apps/api/.env`, so we don't want to hard-fail.
178
+ const candidates = ['backend/apps/api/.env', 'backend/.env', '.env'];
179
+ const present = [];
180
+ for (const rel of candidates) {
181
+ if (await (0, cli_helpers_1.fileExists)(path.join(projectPath, rel))) {
182
+ present.push(rel);
183
+ }
184
+ }
185
+ if (present.length > 0) {
186
+ return { name: 'Backend .env present', severity: 'pass', detail: present.join(', ') };
187
+ }
188
+ return {
189
+ name: 'Backend .env present',
190
+ severity: 'warn',
191
+ detail: `no .env found at any of: ${candidates.join(', ')}`,
192
+ };
193
+ }
194
+ async function checkPrismaMigrations(projectPath) {
195
+ const migrationsDir = path.join(projectPath, 'migrations');
196
+ const prismaDir = path.join(projectPath, 'prisma');
197
+ const hasMigrations = (await (0, cli_helpers_1.fileExists)(migrationsDir)) || (await (0, cli_helpers_1.fileExists)(prismaDir));
198
+ if (!hasMigrations) {
199
+ return { name: 'Prisma migrations applied', severity: 'info', detail: 'no migrations/ directory' };
200
+ }
201
+ // We can't run prisma here (it requires a DB). Use heuristic: presence of
202
+ // schema.prisma + migrations directory is "info"; running `prisma migrate
203
+ // status` is left to CI.
204
+ return {
205
+ name: 'Prisma migrations applied',
206
+ severity: 'info',
207
+ detail: 'run `pnpm prisma migrate status` to verify against the DB',
208
+ };
209
+ }
210
+ async function checkLockfileSorted(projectPath) {
211
+ const lockPath = path.join(projectPath, 'postxl-lock.json');
212
+ let raw;
213
+ try {
214
+ raw = await fs.readFile(lockPath, 'utf8');
215
+ }
216
+ catch {
217
+ return { name: 'Lockfile sorted', severity: 'info', detail: 'no postxl-lock.json' };
218
+ }
219
+ let parsed;
220
+ try {
221
+ parsed = JSON.parse(raw);
222
+ }
223
+ catch {
224
+ return { name: 'Lockfile sorted', severity: 'fail', detail: 'cannot parse postxl-lock.json' };
225
+ }
226
+ const keys = Object.keys(parsed);
227
+ const sorted = [...keys].sort((a, b) => a.localeCompare(b));
228
+ for (let i = 0; i < keys.length; i++) {
229
+ if (keys[i] !== sorted[i]) {
230
+ return { name: 'Lockfile sorted', severity: 'info', detail: 'keys are not sorted (cosmetic)' };
231
+ }
232
+ }
233
+ return { name: 'Lockfile sorted', severity: 'pass', detail: `${keys.length} entries` };
234
+ }
@@ -59,6 +59,7 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
59
59
  .option('-e, --ejected', 'lists ejected files')
60
60
  .option('-f, --force', 'overwrites ejected files')
61
61
  .option('-i, --ignore-errors', 'ignores errors during generation')
62
+ .option('--dry-run', 'compute the changes that would be made without writing or updating the lockfile')
62
63
  .option('-m, --model <names...>', 'regenerate only for the given models (accepts multiple, e.g. -m Country City)')
63
64
  .option('-n, --no-fix', 'does not attempt to fix linting errors')
64
65
  .option('-p, --pattern <glob>', 'filters files by glob pattern (e.g., "**/*.ts" or "backend/libs/**")')
@@ -87,10 +88,14 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
87
88
  projectType: schema.projectType,
88
89
  });
89
90
  await fs.mkdir(targetPath, { recursive: true });
90
- console.log(`Generating project from ${projectPath} to ${targetPath}`);
91
+ const verb = options.dryRun ? 'Would generate' : 'Generating';
92
+ console.log(`${verb} project from ${projectPath} to ${targetPath}`);
91
93
  if (options.force) {
92
94
  console.log((0, utils_1.yellow)('Warning: Forcing generation of ejected files!'));
93
95
  }
96
+ if (options.dryRun) {
97
+ console.log((0, utils_1.yellow)('Dry run: no files will be written and the lockfile will not be updated.'));
98
+ }
94
99
  if (options.pattern) {
95
100
  console.log(`Filtering files by pattern: ${options.pattern}`);
96
101
  }
@@ -132,6 +137,7 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
132
137
  diskFilePath: targetPath,
133
138
  force: options.force ?? false,
134
139
  ...(targetModelNames ? { selectiveGeneration: true } : {}),
140
+ ...(options.dryRun ? { dryRun: true } : {}),
135
141
  });
136
142
  (0, generator_1.logSyncResult)(result, {
137
143
  showEjectedStats: options.ejected ?? false,
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function register(program: Command): void;