@postxl/cli 1.9.2 → 1.10.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.
@@ -43,7 +43,9 @@ const dotenv_1 = __importDefault(require("dotenv"));
43
43
  const fs = __importStar(require("node:fs/promises"));
44
44
  const path = __importStar(require("node:path"));
45
45
  const generator_1 = require("@postxl/generator");
46
+ const schema_1 = require("@postxl/schema");
46
47
  const utils_1 = require("@postxl/utils");
48
+ const base_snapshot_1 = require("./helpers/base-snapshot");
47
49
  const load_project_schema_1 = require("./helpers/load-project-schema");
48
50
  const execAsync = (0, util_1.promisify)(child_process_1.exec);
49
51
  function register(program) {
@@ -62,6 +64,7 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
62
64
  .option('--dry-run', 'compute the changes that would be made without writing or updating the lockfile')
63
65
  .option('-m, --model <names...>', 'regenerate only for the given models (accepts multiple, e.g. -m Country City)')
64
66
  .option('-n, --no-fix', 'does not attempt to fix linting errors')
67
+ .option('--no-three-way', 'skips reconstructing the previous generation for three-way merges (faster; ejected files fall back to the 2-way merge)')
65
68
  .option('-p, --pattern <glob>', 'filters files by glob pattern (e.g., "**/*.ts" or "backend/libs/**")')
66
69
  .option('-q, --quiet', 'does not print errors')
67
70
  .option('-s, --skip-lint', 'skips linting')
@@ -79,7 +82,7 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
79
82
  }
80
83
  const envConfig = dotenv_1.default.config({ path: path.join(projectPath, '.env') });
81
84
  const localGenerators = await getLocalGenerators({ program, projectPath });
82
- const schema = await (0, load_project_schema_1.loadProjectSchema)({ program, projectPath });
85
+ const { schema, raw: rawSchema } = await (0, load_project_schema_1.loadProjectSchemaWithRaw)({ program, projectPath });
83
86
  targetPath = await resolveTargetPath({
84
87
  projectPath,
85
88
  targetPath,
@@ -110,6 +113,15 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
110
113
  ...(targetModelNames ? { targetModelNames } : {}),
111
114
  });
112
115
  const generatedContext = await manager.generate(baseContext);
116
+ // Reconstruct the previous generation (B = G(schema_old)) from the stored
117
+ // snapshot so sync can perform a true three-way merge. Scoped to full,
118
+ // writing runs (see maybeReconstructBaseVfs for the gating rationale).
119
+ const baseVfs = await maybeReconstructBaseVfs({
120
+ manager,
121
+ targetPath,
122
+ options,
123
+ targetModelNames,
124
+ });
113
125
  return (new generator_1.Generator(generatedContext)
114
126
  // Not sure why we need this - but without the next line fails 💥
115
127
  .generate((g) => g)
@@ -138,11 +150,20 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
138
150
  force: options.force ?? false,
139
151
  ...(targetModelNames ? { selectiveGeneration: true } : {}),
140
152
  ...(options.dryRun ? { dryRun: true } : {}),
153
+ ...(baseVfs ? { baseVfs } : {}),
141
154
  });
142
155
  (0, generator_1.logSyncResult)(result, {
143
156
  showEjectedStats: options.ejected ?? false,
144
157
  showEjectedDiff: options.diff ?? false,
145
158
  });
159
+ // Persist the current schema as the base for the next generation's
160
+ // three-way merge. Skipped on dry runs (which must not touch disk).
161
+ if (!options.dryRun) {
162
+ await (0, base_snapshot_1.writeBaseSnapshot)(targetPath, {
163
+ schemaSnapshot: rawSchema,
164
+ generatorVersion: (0, base_snapshot_1.resolveGeneratorVersion)(),
165
+ });
166
+ }
146
167
  return g;
147
168
  })
148
169
  .then((g) => {
@@ -152,6 +173,71 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
152
173
  }));
153
174
  });
154
175
  }
176
+ /**
177
+ * Reconstructs the previous generation (`B = G(schema_old)`) to serve as the
178
+ * common ancestor for sync's three-way merge.
179
+ *
180
+ * Generation is deterministic, so rather than store every generated byte we
181
+ * re-run the pipeline with the schema captured in the last run's
182
+ * `.postxl/base-snapshot.json`. The base VFS is passed through the same
183
+ * lint/format transform as the fresh output, so formatting churn cannot
184
+ * manufacture false conflicts.
185
+ *
186
+ * Scoped to full, writing runs: skipped for dry runs (no disk effects),
187
+ * `-m`/selective runs and `-p`/pattern runs (narrowed output sets don't line up
188
+ * with a full-base comparison). Those fall back to the 2-way merge. Returns
189
+ * `undefined` whenever a base cannot be reconstructed (no snapshot, unparseable
190
+ * snapshot, or a generation error), in which case sync uses the 2-way path.
191
+ */
192
+ async function maybeReconstructBaseVfs(params) {
193
+ const { manager, targetPath, options, targetModelNames } = params;
194
+ // `--no-three-way` opts out of base reconstruction entirely (fast iteration);
195
+ // ejected files then fall back to the 2-way merge.
196
+ if (options.threeWay === false || options.dryRun || targetModelNames || options.pattern) {
197
+ return undefined;
198
+ }
199
+ const snapshot = await (0, base_snapshot_1.readBaseSnapshot)(targetPath);
200
+ if (!snapshot) {
201
+ return undefined;
202
+ }
203
+ // The base is only ever consulted to merge files that were edited on disk.
204
+ // When nothing is ejected, reconstructing it (a second full generation +
205
+ // lint + format) would be wasted work, so skip it — the common, clean-project
206
+ // case pays nothing.
207
+ if (!(await (0, base_snapshot_1.hasLocallyEditedFiles)(targetPath))) {
208
+ return undefined;
209
+ }
210
+ const parsed = schema_1.zProjectSchema.safeParse(snapshot.schemaSnapshot);
211
+ if (!parsed.success) {
212
+ return undefined;
213
+ }
214
+ const currentGeneratorVersion = (0, base_snapshot_1.resolveGeneratorVersion)();
215
+ if (snapshot.generatorVersion !== 'unknown' &&
216
+ currentGeneratorVersion !== 'unknown' &&
217
+ snapshot.generatorVersion !== currentGeneratorVersion) {
218
+ console.log((0, utils_1.yellow)(`Note: @postxl/generators changed since the last generation (${snapshot.generatorVersion} → ${currentGeneratorVersion}); the three-way merge base is approximate.`));
219
+ }
220
+ try {
221
+ const baseContext = (0, generator_1.prepareBaseContext)(parsed.data, { ...options });
222
+ const baseGenerated = await manager.generate(baseContext);
223
+ const baseG = await new generator_1.Generator(baseGenerated).generate((g) => g);
224
+ if (!options.skipTransform) {
225
+ await (0, generator_1.lint)(baseG.context.vfs, options);
226
+ await baseG.context.vfs.transform(generator_1.format, {
227
+ onError: ({ error }) => {
228
+ if (!options.ignoreErrors) {
229
+ throw error;
230
+ }
231
+ },
232
+ });
233
+ }
234
+ return baseG.context.vfs;
235
+ }
236
+ catch (error) {
237
+ console.log((0, utils_1.yellow)(`Could not reconstruct the previous generation for a three-way merge; falling back to 2-way. ${error instanceof Error ? error.message : String(error)}`));
238
+ return undefined;
239
+ }
240
+ }
155
241
  /**
156
242
  * This function compiles the generate.ts file into a JS file and then imports and returns it
157
243
  * via dynamic import.
@@ -0,0 +1,26 @@
1
+ export type BaseSnapshot = {
2
+ schemaSnapshot: Record<string, unknown>;
3
+ generatorVersion: string;
4
+ };
5
+ export declare function baseSnapshotPath(targetPath: string): string;
6
+ export declare function readBaseSnapshot(targetPath: string): Promise<BaseSnapshot | undefined>;
7
+ export declare function writeBaseSnapshot(targetPath: string, snapshot: BaseSnapshot): Promise<void>;
8
+ /**
9
+ * Returns true if any tracked generated file has been edited on disk (its content
10
+ * no longer matches its lock-file checksum) — i.e. the project has at least one
11
+ * "ejected" file that a regeneration could need to merge.
12
+ *
13
+ * The three-way merge base is only ever consulted for such files (the
14
+ * `MergeConflict` sync state requires a disk file that diverges from both the
15
+ * lock and the fresh output). When nothing is edited on disk, reconstructing the
16
+ * base would be pure wasted work, so the caller can skip the second generation
17
+ * pass entirely. Permanently-ejected entries (the `"ejected"` sentinel) are
18
+ * skipped because sync never merges them.
19
+ */
20
+ export declare function hasLocallyEditedFiles(targetPath: string): Promise<boolean>;
21
+ /**
22
+ * Best-effort read of the installed `@postxl/generators` version, used to detect
23
+ * generator drift between the snapshot and the current run. Falls back to
24
+ * `'unknown'` if it cannot be resolved (drift detection is advisory only).
25
+ */
26
+ export declare function resolveGeneratorVersion(): string;
@@ -0,0 +1,147 @@
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.baseSnapshotPath = baseSnapshotPath;
37
+ exports.readBaseSnapshot = readBaseSnapshot;
38
+ exports.writeBaseSnapshot = writeBaseSnapshot;
39
+ exports.hasLocallyEditedFiles = hasLocallyEditedFiles;
40
+ exports.resolveGeneratorVersion = resolveGeneratorVersion;
41
+ /**
42
+ * Base-snapshot management for the generator's three-way (diff3) merge.
43
+ *
44
+ * To attribute a divergence to "the developer changed this" vs. "the generator
45
+ * changed this", the merge needs a common ancestor: the *previous* generation,
46
+ * `B = G(schema_old)`. Rather than store every generated byte, we exploit the
47
+ * fact that generation is deterministic and persist only the inputs needed to
48
+ * reconstruct `B` on demand:
49
+ *
50
+ * - `schemaSnapshot` — the fully-merged raw schema (all inline + split
51
+ * `schema/*.model.json` / `*.enum.json` inputs collapsed into one object), so
52
+ * the base is reproducible regardless of how the project splits its schema.
53
+ * - `generatorVersion` — the `@postxl/generators` version that produced it, used
54
+ * to detect generator drift (when the generator itself changed, the
55
+ * reconstructed base is approximate — still strictly better than a 2-way diff).
56
+ *
57
+ * The snapshot lives next to the lock file under `.postxl/base-snapshot.json` and
58
+ * is committed to git so CI and fresh clones can reconstruct the base too.
59
+ */
60
+ const fs = __importStar(require("node:fs/promises"));
61
+ const node_module_1 = require("node:module");
62
+ const path = __importStar(require("node:path"));
63
+ const generator_1 = require("@postxl/generator");
64
+ const SNAPSHOT_DIR = '.postxl';
65
+ const SNAPSHOT_FILE = 'base-snapshot.json';
66
+ const LOCK_FILE = 'postxl-lock.json';
67
+ function baseSnapshotPath(targetPath) {
68
+ return path.join(targetPath, SNAPSHOT_DIR, SNAPSHOT_FILE);
69
+ }
70
+ async function readBaseSnapshot(targetPath) {
71
+ try {
72
+ const content = await fs.readFile(baseSnapshotPath(targetPath), 'utf-8');
73
+ const parsed = JSON.parse(content);
74
+ if (parsed && typeof parsed === 'object' && parsed.schemaSnapshot && typeof parsed.schemaSnapshot === 'object') {
75
+ return {
76
+ schemaSnapshot: parsed.schemaSnapshot,
77
+ generatorVersion: typeof parsed.generatorVersion === 'string' ? parsed.generatorVersion : 'unknown',
78
+ };
79
+ }
80
+ }
81
+ catch {
82
+ // No snapshot (legacy project / first run after upgrade) — caller falls back to 2-way.
83
+ }
84
+ return undefined;
85
+ }
86
+ async function writeBaseSnapshot(targetPath, snapshot) {
87
+ const filePath = baseSnapshotPath(targetPath);
88
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
89
+ await fs.writeFile(filePath, JSON.stringify(snapshot, null, 2) + '\n');
90
+ }
91
+ /**
92
+ * Returns true if any tracked generated file has been edited on disk (its content
93
+ * no longer matches its lock-file checksum) — i.e. the project has at least one
94
+ * "ejected" file that a regeneration could need to merge.
95
+ *
96
+ * The three-way merge base is only ever consulted for such files (the
97
+ * `MergeConflict` sync state requires a disk file that diverges from both the
98
+ * lock and the fresh output). When nothing is edited on disk, reconstructing the
99
+ * base would be pure wasted work, so the caller can skip the second generation
100
+ * pass entirely. Permanently-ejected entries (the `"ejected"` sentinel) are
101
+ * skipped because sync never merges them.
102
+ */
103
+ async function hasLocallyEditedFiles(targetPath) {
104
+ const lock = await (0, generator_1.readLockFile)(path.join(targetPath, LOCK_FILE));
105
+ if (!lock) {
106
+ return false;
107
+ }
108
+ for (const [relativePath, entry] of lock) {
109
+ if ((0, generator_1.isEjected)(entry)) {
110
+ continue;
111
+ }
112
+ let content;
113
+ try {
114
+ content = await fs.readFile(path.join(targetPath, relativePath));
115
+ }
116
+ catch {
117
+ // File was deleted on disk — not an edit that needs a merge base.
118
+ continue;
119
+ }
120
+ // The lock checksum was computed by `calculateChecksum` over the VFS content
121
+ // (UTF-8-normalized for text, raw/zip-aware for the rest). We hash the raw
122
+ // disk bytes through the same function, so for this project's output
123
+ // (LF, no BOM) the hashes match exactly. A CRLF/BOM file would only ever
124
+ // hash *differently* — a harmless false positive (an extra reconstruction),
125
+ // never a false negative: a SHA-256 collision would be required to report an
126
+ // edited file as clean, so a needed merge can never be silently skipped.
127
+ if ((await (0, generator_1.calculateChecksum)(content)) !== entry) {
128
+ return true;
129
+ }
130
+ }
131
+ return false;
132
+ }
133
+ /**
134
+ * Best-effort read of the installed `@postxl/generators` version, used to detect
135
+ * generator drift between the snapshot and the current run. Falls back to
136
+ * `'unknown'` if it cannot be resolved (drift detection is advisory only).
137
+ */
138
+ function resolveGeneratorVersion() {
139
+ try {
140
+ const require = (0, node_module_1.createRequire)(__filename);
141
+ const pkg = require('@postxl/generators/package.json');
142
+ return pkg.version ?? 'unknown';
143
+ }
144
+ catch {
145
+ return 'unknown';
146
+ }
147
+ }
@@ -24,3 +24,18 @@ export declare function loadProjectSchema(params: {
24
24
  projectPath: string;
25
25
  program: Command;
26
26
  }): Promise<ProjectSchema>;
27
+ /**
28
+ * Like {@link loadProjectSchema}, but also returns the fully-merged raw schema
29
+ * object (all inline + split `schema/*.model.json` / `*.enum.json` inputs
30
+ * collapsed into one JSON object). The raw object is what gets persisted as the
31
+ * base snapshot for the three-way merge: it is reproducible regardless of how a
32
+ * project splits its schema, and it can be re-parsed to reconstruct the previous
33
+ * generation.
34
+ */
35
+ export declare function loadProjectSchemaWithRaw(params: {
36
+ projectPath: string;
37
+ program: Command;
38
+ }): Promise<{
39
+ schema: ProjectSchema;
40
+ raw: Record<string, unknown>;
41
+ }>;
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.loadAndMergeRawSchema = loadAndMergeRawSchema;
37
37
  exports.loadProjectSchema = loadProjectSchema;
38
+ exports.loadProjectSchemaWithRaw = loadProjectSchemaWithRaw;
38
39
  const fs = __importStar(require("node:fs/promises"));
39
40
  const path = __importStar(require("node:path"));
40
41
  const schema_1 = require("@postxl/schema");
@@ -98,6 +99,17 @@ async function loadAndMergeRawSchema(params) {
98
99
  * preserves the behavior of the previous in-command schema loader.
99
100
  */
100
101
  async function loadProjectSchema(params) {
102
+ return (await loadProjectSchemaWithRaw(params)).schema;
103
+ }
104
+ /**
105
+ * Like {@link loadProjectSchema}, but also returns the fully-merged raw schema
106
+ * object (all inline + split `schema/*.model.json` / `*.enum.json` inputs
107
+ * collapsed into one JSON object). The raw object is what gets persisted as the
108
+ * base snapshot for the three-way merge: it is reproducible regardless of how a
109
+ * project splits its schema, and it can be re-parsed to reconstruct the previous
110
+ * generation.
111
+ */
112
+ async function loadProjectSchemaWithRaw(params) {
101
113
  const mergedInput = await loadAndMergeRawSchema(params);
102
114
  const result = schema_1.zProjectSchema.safeParse(mergedInput);
103
115
  if (!result.success) {
@@ -105,7 +117,7 @@ async function loadProjectSchema(params) {
105
117
  (0, log_schema_error_1.logSchemaValidationError)(result.error);
106
118
  process.exit(1);
107
119
  }
108
- return result.data;
120
+ return { schema: result.data, raw: mergedInput };
109
121
  }
110
122
  function toDefinitionMap(entries) {
111
123
  const out = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postxl/cli",
3
- "version": "1.9.2",
3
+ "version": "1.10.1",
4
4
  "description": "Command-line interface for PostXL code generation framework",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -45,10 +45,10 @@
45
45
  "dotenv": "17.4.2",
46
46
  "ts-morph": "26.0.0",
47
47
  "zod-validation-error": "5.0.0",
48
- "@postxl/generator": "^1.6.3",
49
- "@postxl/generators": "^2.2.0",
50
- "@postxl/schema": "^2.1.0",
51
- "@postxl/utils": "^1.4.1"
48
+ "@postxl/generator": "^1.7.1",
49
+ "@postxl/generators": "^3.1.0",
50
+ "@postxl/schema": "^2.2.0",
51
+ "@postxl/utils": "^1.4.2"
52
52
  },
53
53
  "devDependencies": {},
54
54
  "wallaby": {