@pgpmjs/slice 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/slice.js ADDED
@@ -0,0 +1,536 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildDependencyGraph = buildDependencyGraph;
4
+ exports.validateDAG = validateDAG;
5
+ exports.extractPackageFromPath = extractPackageFromPath;
6
+ exports.findMatchingPattern = findMatchingPattern;
7
+ exports.assignChangesToPackages = assignChangesToPackages;
8
+ exports.mergeSmallPackages = mergeSmallPackages;
9
+ exports.buildPackageDependencies = buildPackageDependencies;
10
+ exports.detectPackageCycle = detectPackageCycle;
11
+ exports.computeDeployOrder = computeDeployOrder;
12
+ exports.topologicalSortWithinPackage = topologicalSortWithinPackage;
13
+ exports.generatePlanContent = generatePlanContent;
14
+ exports.generateControlContent = generateControlContent;
15
+ exports.generateSinglePackage = generateSinglePackage;
16
+ exports.slicePlan = slicePlan;
17
+ const parser_1 = require("@pgpmjs/ast/files/plan/parser");
18
+ const writer_1 = require("@pgpmjs/ast/files/plan/writer");
19
+ const closure_1 = require("./closure");
20
+ const minimatch_1 = require("minimatch");
21
+ /**
22
+ * Build a dependency graph from a parsed plan file
23
+ */
24
+ function buildDependencyGraph(plan) {
25
+ const graph = {
26
+ nodes: new Map(),
27
+ edges: new Map(),
28
+ reverseEdges: new Map(),
29
+ tags: new Map(),
30
+ plan
31
+ };
32
+ // Add all changes as nodes
33
+ for (const change of plan.changes) {
34
+ graph.nodes.set(change.name, change);
35
+ graph.edges.set(change.name, new Set(change.dependencies || []));
36
+ // Build reverse edges for dependency analysis
37
+ for (const dep of change.dependencies || []) {
38
+ if (!graph.reverseEdges.has(dep)) {
39
+ graph.reverseEdges.set(dep, new Set());
40
+ }
41
+ graph.reverseEdges.get(dep).add(change.name);
42
+ }
43
+ }
44
+ // Index tags by change
45
+ for (const tag of plan.tags || []) {
46
+ if (!graph.tags.has(tag.change)) {
47
+ graph.tags.set(tag.change, []);
48
+ }
49
+ graph.tags.get(tag.change).push(tag);
50
+ }
51
+ return graph;
52
+ }
53
+ /**
54
+ * Validate that the dependency graph is a DAG (no cycles)
55
+ */
56
+ function validateDAG(graph) {
57
+ const visited = new Set();
58
+ const visiting = new Set();
59
+ function dfs(node, path) {
60
+ if (visiting.has(node)) {
61
+ throw new Error(`Cycle detected: ${[...path, node].join(' -> ')}`);
62
+ }
63
+ if (visited.has(node))
64
+ return;
65
+ visiting.add(node);
66
+ const deps = graph.edges.get(node) || new Set();
67
+ for (const dep of deps) {
68
+ // Only follow internal dependencies
69
+ if (graph.nodes.has(dep)) {
70
+ dfs(dep, [...path, node]);
71
+ }
72
+ }
73
+ visiting.delete(node);
74
+ visited.add(node);
75
+ }
76
+ for (const node of graph.nodes.keys()) {
77
+ dfs(node, []);
78
+ }
79
+ }
80
+ /**
81
+ * Extract package name from a change path using folder-based strategy
82
+ */
83
+ function extractPackageFromPath(changeName, depth = 1, prefixToStrip = 'schemas') {
84
+ const parts = changeName.split('/');
85
+ // Handle special folders that should go to core
86
+ if (parts[0] === 'extensions' || parts[0] === 'migrate') {
87
+ return 'core';
88
+ }
89
+ // Strip prefix if present
90
+ let startIdx = 0;
91
+ if (parts[0] === prefixToStrip) {
92
+ startIdx = 1;
93
+ }
94
+ // Get package name at specified depth
95
+ if (parts.length > startIdx) {
96
+ // For depth > 1, join multiple segments
97
+ const endIdx = Math.min(startIdx + depth, parts.length - 1);
98
+ if (endIdx > startIdx) {
99
+ return parts.slice(startIdx, endIdx).join('/');
100
+ }
101
+ return parts[startIdx];
102
+ }
103
+ return 'core';
104
+ }
105
+ /**
106
+ * Find the matching package for a change using pattern-based strategy.
107
+ * Returns the first matching slice's package name, or undefined if no match.
108
+ */
109
+ function findMatchingPattern(changeName, strategy) {
110
+ for (const slice of strategy.slices) {
111
+ for (const pattern of slice.patterns) {
112
+ if ((0, minimatch_1.minimatch)(changeName, pattern, { dot: true })) {
113
+ return slice.packageName;
114
+ }
115
+ }
116
+ }
117
+ return undefined;
118
+ }
119
+ /**
120
+ * Assign changes to packages based on grouping strategy
121
+ */
122
+ function assignChangesToPackages(graph, strategy, defaultPackage = 'core') {
123
+ const assignments = new Map();
124
+ for (const [changeName] of graph.nodes) {
125
+ let packageName;
126
+ switch (strategy.type) {
127
+ case 'folder': {
128
+ const depth = strategy.depth ?? 1;
129
+ const prefix = strategy.prefixToStrip ?? 'schemas';
130
+ packageName = extractPackageFromPath(changeName, depth, prefix);
131
+ break;
132
+ }
133
+ case 'pattern': {
134
+ const matched = findMatchingPattern(changeName, strategy);
135
+ packageName = matched || defaultPackage;
136
+ break;
137
+ }
138
+ case 'explicit': {
139
+ packageName = strategy.mapping[changeName] || defaultPackage;
140
+ break;
141
+ }
142
+ default:
143
+ packageName = defaultPackage;
144
+ }
145
+ // Fallback to default package
146
+ if (!packageName) {
147
+ packageName = defaultPackage;
148
+ }
149
+ if (!assignments.has(packageName)) {
150
+ assignments.set(packageName, new Set());
151
+ }
152
+ assignments.get(packageName).add(changeName);
153
+ }
154
+ return assignments;
155
+ }
156
+ /**
157
+ * Merge small packages into larger ones
158
+ */
159
+ function mergeSmallPackages(assignments, minChanges, defaultPackage = 'core') {
160
+ const result = new Map();
161
+ // Ensure default package exists
162
+ if (!result.has(defaultPackage)) {
163
+ result.set(defaultPackage, new Set());
164
+ }
165
+ for (const [pkg, changes] of assignments) {
166
+ if (changes.size < minChanges && pkg !== defaultPackage) {
167
+ // Merge into default package
168
+ const defaultChanges = result.get(defaultPackage);
169
+ for (const change of changes) {
170
+ defaultChanges.add(change);
171
+ }
172
+ }
173
+ else {
174
+ result.set(pkg, new Set(changes));
175
+ }
176
+ }
177
+ // Remove empty default package if it exists
178
+ if (result.get(defaultPackage)?.size === 0) {
179
+ result.delete(defaultPackage);
180
+ }
181
+ return result;
182
+ }
183
+ /**
184
+ * Build package-level dependency graph
185
+ */
186
+ function buildPackageDependencies(graph, assignments, extraEdges) {
187
+ const packageDeps = new Map();
188
+ // Build reverse lookup: change -> package
189
+ const changeToPackage = new Map();
190
+ for (const [pkg, changes] of assignments) {
191
+ packageDeps.set(pkg, new Set());
192
+ for (const change of changes) {
193
+ changeToPackage.set(change, pkg);
194
+ }
195
+ }
196
+ // Check each change's dependencies
197
+ for (const [changeName, deps] of graph.edges) {
198
+ const myPackage = changeToPackage.get(changeName);
199
+ if (!myPackage)
200
+ continue;
201
+ const allDeps = new Set(deps);
202
+ for (const dep of extraEdges?.get(changeName)?.keys() ?? []) {
203
+ allDeps.add(dep);
204
+ }
205
+ for (const dep of allDeps) {
206
+ const depPackage = changeToPackage.get(dep);
207
+ if (depPackage && depPackage !== myPackage) {
208
+ // Cross-package dependency
209
+ packageDeps.get(myPackage).add(depPackage);
210
+ }
211
+ }
212
+ }
213
+ return packageDeps;
214
+ }
215
+ /**
216
+ * Detect cycles in package dependency graph
217
+ */
218
+ function detectPackageCycle(deps) {
219
+ const visited = new Set();
220
+ const visiting = new Set();
221
+ function dfs(pkg, path) {
222
+ if (visiting.has(pkg)) {
223
+ return [...path, pkg];
224
+ }
225
+ if (visited.has(pkg))
226
+ return null;
227
+ visiting.add(pkg);
228
+ const pkgDeps = deps.get(pkg) || new Set();
229
+ for (const dep of pkgDeps) {
230
+ const cycle = dfs(dep, [...path, pkg]);
231
+ if (cycle)
232
+ return cycle;
233
+ }
234
+ visiting.delete(pkg);
235
+ visited.add(pkg);
236
+ return null;
237
+ }
238
+ for (const pkg of deps.keys()) {
239
+ const cycle = dfs(pkg, []);
240
+ if (cycle)
241
+ return cycle;
242
+ }
243
+ return null;
244
+ }
245
+ /**
246
+ * Compute deployment order for packages (topological sort)
247
+ */
248
+ function computeDeployOrder(packageDeps) {
249
+ const order = [];
250
+ const visited = new Set();
251
+ const allPackages = new Set();
252
+ // Collect all packages
253
+ for (const pkg of packageDeps.keys()) {
254
+ allPackages.add(pkg);
255
+ }
256
+ for (const deps of packageDeps.values()) {
257
+ for (const dep of deps) {
258
+ allPackages.add(dep);
259
+ }
260
+ }
261
+ function visit(pkg) {
262
+ if (visited.has(pkg))
263
+ return;
264
+ visited.add(pkg);
265
+ const deps = packageDeps.get(pkg) || new Set();
266
+ for (const dep of deps) {
267
+ visit(dep);
268
+ }
269
+ order.push(pkg);
270
+ }
271
+ // Visit all packages (sorted for determinism)
272
+ for (const pkg of [...allPackages].sort()) {
273
+ visit(pkg);
274
+ }
275
+ return order;
276
+ }
277
+ /**
278
+ * Topological sort of changes within a package
279
+ */
280
+ function topologicalSortWithinPackage(changes, graph) {
281
+ const result = [];
282
+ const visited = new Set();
283
+ function visit(change) {
284
+ if (visited.has(change))
285
+ return;
286
+ if (!changes.has(change))
287
+ return;
288
+ visited.add(change);
289
+ const deps = graph.edges.get(change) || new Set();
290
+ for (const dep of deps) {
291
+ if (changes.has(dep)) {
292
+ visit(dep);
293
+ }
294
+ }
295
+ result.push(change);
296
+ }
297
+ // Visit in alphabetical order for determinism
298
+ for (const change of [...changes].sort()) {
299
+ visit(change);
300
+ }
301
+ return result;
302
+ }
303
+ /**
304
+ * Generate plan file content for a package
305
+ */
306
+ function generatePlanContent(pkgName, entries, tags = []) {
307
+ let content = `%syntax-version=1.0.0\n`;
308
+ content += `%project=${pkgName}\n`;
309
+ content += `%uri=${pkgName}\n\n`;
310
+ // Dependency brackets keep their original order (empty order map), matching
311
+ // the source plans this content is sliced from.
312
+ const originalOrder = new Map();
313
+ for (const entry of entries) {
314
+ content += (0, writer_1.generateChangeLineContent)(entry, originalOrder) + '\n';
315
+ // Add tags associated with this change
316
+ const changeTags = tags.filter(t => t.change === entry.name);
317
+ for (const tag of changeTags) {
318
+ content += (0, writer_1.generateTagLineContent)(tag) + '\n';
319
+ }
320
+ }
321
+ return content;
322
+ }
323
+ /**
324
+ * Generate control file content for a package
325
+ */
326
+ function generateControlContent(pkgName, deps) {
327
+ let content = `# ${pkgName} extension\n`;
328
+ content += `comment = '${pkgName} module'\n`;
329
+ content += `default_version = '0.0.1'\n`;
330
+ content += `relocatable = false\n`;
331
+ if (deps.size > 0) {
332
+ content += `requires = '${[...deps].sort().join(', ')}'\n`;
333
+ }
334
+ return content;
335
+ }
336
+ /**
337
+ * Generate a single package output
338
+ */
339
+ function generateSinglePackage(pkgName, changes, graph, changeToPackage, pkgDeps, crossPackageDeps = 'change') {
340
+ // Back-compat: earlier signature took useTagsForCrossPackageDeps: boolean
341
+ const crossPackageDepMode = crossPackageDeps === true ? 'tag' : crossPackageDeps === false ? 'change' : crossPackageDeps;
342
+ // Sort changes in topological order within package
343
+ const sortedChanges = topologicalSortWithinPackage(changes, graph);
344
+ // Build plan entries with updated dependencies
345
+ const planEntries = [];
346
+ for (const changeName of sortedChanges) {
347
+ const originalChange = graph.nodes.get(changeName);
348
+ const deps = graph.edges.get(changeName) || new Set();
349
+ const newDeps = [];
350
+ for (const dep of deps) {
351
+ const depPkg = changeToPackage.get(dep);
352
+ if (!depPkg) {
353
+ // External dependency (from installed module) - keep as-is
354
+ newDeps.push(dep);
355
+ }
356
+ else if (depPkg === pkgName) {
357
+ // Internal dependency - keep as-is
358
+ newDeps.push(dep);
359
+ }
360
+ else {
361
+ // Cross-package dependency
362
+ if (crossPackageDepMode === 'control-only') {
363
+ // Dropped from the plan line; carried by the control file's
364
+ // `requires` (extension install ordering deploys the whole
365
+ // dependency package first)
366
+ continue;
367
+ }
368
+ if (crossPackageDepMode === 'tag') {
369
+ // Find latest tag in the dependency package
370
+ const depPkgChanges = [...graph.nodes.keys()]
371
+ .filter(c => changeToPackage.get(c) === depPkg);
372
+ const lastChange = depPkgChanges[depPkgChanges.length - 1];
373
+ const tags = graph.tags.get(lastChange);
374
+ if (tags && tags.length > 0) {
375
+ const latestTag = tags[tags.length - 1];
376
+ newDeps.push(`${depPkg}:@${latestTag.name}`);
377
+ }
378
+ else {
379
+ newDeps.push(`${depPkg}:${dep}`);
380
+ }
381
+ }
382
+ else {
383
+ newDeps.push(`${depPkg}:${dep}`);
384
+ }
385
+ }
386
+ }
387
+ planEntries.push({
388
+ name: changeName,
389
+ dependencies: newDeps,
390
+ timestamp: originalChange.timestamp,
391
+ planner: originalChange.planner,
392
+ email: originalChange.email,
393
+ comment: originalChange.comment
394
+ });
395
+ }
396
+ // Collect tags for this package
397
+ const packageTags = [];
398
+ for (const changeName of sortedChanges) {
399
+ const changeTags = graph.tags.get(changeName) || [];
400
+ packageTags.push(...changeTags);
401
+ }
402
+ // Generate plan content
403
+ const planContent = generatePlanContent(pkgName, planEntries, packageTags);
404
+ // Generate control file content
405
+ const controlContent = generateControlContent(pkgName, pkgDeps);
406
+ return {
407
+ name: pkgName,
408
+ planContent,
409
+ controlContent,
410
+ changes: planEntries,
411
+ packageDependencies: [...pkgDeps]
412
+ };
413
+ }
414
+ /**
415
+ * Main slicing function
416
+ */
417
+ function slicePlan(config) {
418
+ // Parse the source plan file
419
+ const planResult = (0, parser_1.parsePlanFile)(config.sourcePlan);
420
+ if (!planResult.data) {
421
+ const errorMessages = planResult.errors?.map(e => `Line ${e.line}: ${e.message}`).join('\n') || 'Unknown error';
422
+ throw new Error(`Failed to parse plan file: ${errorMessages}`);
423
+ }
424
+ const plan = planResult.data;
425
+ const warnings = [];
426
+ // Build dependency graph
427
+ const graph = buildDependencyGraph(plan);
428
+ // Validate DAG
429
+ try {
430
+ validateDAG(graph);
431
+ }
432
+ catch (error) {
433
+ throw new Error(`Invalid plan file: ${error.message}`);
434
+ }
435
+ // Assign changes to packages
436
+ let assignments = assignChangesToPackages(graph, config.strategy, config.defaultPackage || 'core');
437
+ // Expand closure-enabled pattern slices to cover their dependency closure
438
+ let closureReport;
439
+ let astDepEdges;
440
+ if (config.closure && config.strategy.type === 'pattern' &&
441
+ config.strategy.slices.some(s => s.closure)) {
442
+ const astEdges = (0, closure_1.buildAstEdges)(graph, config.closure.moduleDir);
443
+ closureReport = (0, closure_1.expandClosures)(assignments, graph, astEdges, config.strategy, config.defaultPackage || 'core');
444
+ astDepEdges = astEdges.edges;
445
+ }
446
+ // Merge small packages if configured
447
+ if (config.minChangesPerPackage && config.minChangesPerPackage > 1) {
448
+ assignments = mergeSmallPackages(assignments, config.minChangesPerPackage, config.defaultPackage || 'core');
449
+ }
450
+ // Build package dependencies (AST-discovered edges only affect package-level
451
+ // requires/deploy order, never plan lines — PL/pgSQL body references are
452
+ // late-binding and may legitimately form cycles between functions)
453
+ const packageDeps = buildPackageDependencies(graph, assignments, astDepEdges);
454
+ // Check for package cycles
455
+ const cycle = detectPackageCycle(packageDeps);
456
+ if (cycle) {
457
+ warnings.push({
458
+ type: 'cycle_detected',
459
+ message: `Package cycle detected: ${cycle.join(' -> ')}`,
460
+ suggestedAction: 'Consider merging these packages or reorganizing dependencies'
461
+ });
462
+ // For now, we'll proceed but warn - in production we might want to auto-merge
463
+ }
464
+ // Build reverse lookup
465
+ const changeToPackage = new Map();
466
+ for (const [pkg, changes] of assignments) {
467
+ for (const change of changes) {
468
+ changeToPackage.set(change, pkg);
469
+ }
470
+ }
471
+ // Compute deploy order
472
+ const deployOrder = computeDeployOrder(packageDeps);
473
+ // Generate packages
474
+ const packages = [];
475
+ for (const pkgName of deployOrder) {
476
+ const changes = assignments.get(pkgName);
477
+ if (!changes || changes.size === 0)
478
+ continue;
479
+ const pkgOutput = generateSinglePackage(pkgName, changes, graph, changeToPackage, packageDeps.get(pkgName) || new Set(), config.crossPackageDepMode ?? (config.useTagsForCrossPackageDeps ? 'tag' : 'change'));
480
+ packages.push(pkgOutput);
481
+ // Check for heavy cross-package dependencies
482
+ let crossDeps = 0;
483
+ let totalDeps = 0;
484
+ for (const change of changes) {
485
+ const deps = graph.edges.get(change) || new Set();
486
+ for (const dep of deps) {
487
+ totalDeps++;
488
+ const depPkg = changeToPackage.get(dep);
489
+ if (depPkg && depPkg !== pkgName) {
490
+ crossDeps++;
491
+ }
492
+ }
493
+ }
494
+ const ratio = totalDeps > 0 ? crossDeps / totalDeps : 0;
495
+ if (ratio > 0.5) {
496
+ warnings.push({
497
+ type: 'heavy_cross_deps',
498
+ message: `Package "${pkgName}" has ${Math.round(ratio * 100)}% cross-package dependencies`,
499
+ suggestedAction: 'Consider merging with dependent packages or reorganizing'
500
+ });
501
+ }
502
+ }
503
+ // Calculate stats
504
+ let internalEdges = 0;
505
+ let crossPackageEdges = 0;
506
+ for (const [change, deps] of graph.edges) {
507
+ const myPkg = changeToPackage.get(change);
508
+ for (const dep of deps) {
509
+ const depPkg = changeToPackage.get(dep);
510
+ if (depPkg === myPkg) {
511
+ internalEdges++;
512
+ }
513
+ else if (depPkg) {
514
+ crossPackageEdges++;
515
+ }
516
+ }
517
+ }
518
+ const totalEdges = internalEdges + crossPackageEdges;
519
+ return {
520
+ packages,
521
+ workspace: {
522
+ packages: deployOrder,
523
+ deployOrder,
524
+ dependencies: Object.fromEntries([...packageDeps.entries()].map(([k, v]) => [k, [...v].sort()]))
525
+ },
526
+ warnings,
527
+ stats: {
528
+ totalChanges: graph.nodes.size,
529
+ packagesCreated: packages.length,
530
+ internalEdges,
531
+ crossPackageEdges,
532
+ crossPackageRatio: totalEdges > 0 ? crossPackageEdges / totalEdges : 0
533
+ },
534
+ ...(closureReport ? { closureReport } : {})
535
+ };
536
+ }