-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathregistry.ts
More file actions
283 lines (244 loc) · 8.28 KB
/
registry.ts
File metadata and controls
283 lines (244 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
* Copyright (c) 2025, Salesforce, Inc.
* SPDX-License-Identifier: Apache-2
* For full license text, see the license.txt file in the repo root or http://www.apache.org/licenses/LICENSE-2.0
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import {glob} from 'glob';
import type {
Scaffold,
ScaffoldManifest,
ScaffoldSource,
ScaffoldDiscoveryOptions,
ScaffoldProvider,
ScaffoldTransformer,
} from './types.js';
import {SCAFFOLDS_DATA_DIR} from './types.js';
import {validateScaffoldManifest} from './validators.js';
import {getLogger} from '../logging/logger.js';
/**
* Load a scaffold manifest from a directory
* @param scaffoldDir - Path to the scaffold directory
* @param source - Source type for this scaffold
* @returns Scaffold object or null if invalid
*/
async function loadScaffold(scaffoldDir: string, source: ScaffoldSource): Promise<Scaffold | null> {
const manifestPath = path.join(scaffoldDir, 'scaffold.json');
try {
const manifestContent = await fs.readFile(manifestPath, 'utf-8');
const manifest = JSON.parse(manifestContent) as ScaffoldManifest;
// Validate manifest
const errors = validateScaffoldManifest(manifest);
if (errors.length > 0) {
const logger = getLogger();
logger.warn({manifestPath, errors}, 'Invalid scaffold manifest');
return null;
}
const filesPath = path.join(scaffoldDir, 'files');
// Check if files directory exists
try {
await fs.access(filesPath);
} catch {
const logger = getLogger();
logger.warn({scaffoldDir}, 'Scaffold has no files/ directory');
return null;
}
return {
id: manifest.name,
manifest,
path: scaffoldDir,
filesPath,
source,
};
} catch {
// Manifest doesn't exist or is invalid JSON
return null;
}
}
/**
* Discover scaffolds from a directory
* @param baseDir - Base directory to search
* @param source - Source type for scaffolds found here
* @returns Array of discovered scaffolds
*/
async function discoverScaffoldsFromDir(baseDir: string, source: ScaffoldSource): Promise<Scaffold[]> {
const scaffolds: Scaffold[] = [];
try {
await fs.access(baseDir);
} catch {
// Directory doesn't exist
return scaffolds;
}
// Find all scaffold.json files
const manifestPaths = await glob('*/scaffold.json', {
cwd: baseDir,
absolute: false,
});
for (const manifestPath of manifestPaths) {
const scaffoldDir = path.join(baseDir, path.dirname(manifestPath));
const scaffold = await loadScaffold(scaffoldDir, source);
if (scaffold) {
scaffolds.push(scaffold);
}
}
return scaffolds;
}
/**
* Filter scaffolds based on discovery options
*/
function filterScaffolds(scaffolds: Scaffold[], options: ScaffoldDiscoveryOptions): Scaffold[] {
let filtered = scaffolds;
// Filter by category
if (options.category) {
filtered = filtered.filter((s) => s.manifest.category === options.category);
}
// Filter by source
if (options.sources && options.sources.length > 0) {
filtered = filtered.filter((s) => options.sources!.includes(s.source));
}
// Filter by search query
if (options.query) {
const query = options.query.toLowerCase();
filtered = filtered.filter((s) => {
const searchText = [s.manifest.name, s.manifest.displayName, s.manifest.description].join(' ').toLowerCase();
return searchText.includes(query);
});
}
return filtered;
}
/**
* Options for creating a scaffold registry
*/
export interface ScaffoldRegistryOptions {
/**
* Override the built-in scaffolds directory. Useful for bundled environments
* (e.g. VS Code extensions) where the SDK's data files are copied to a
* different location. Defaults to the SDK's own `data/scaffolds/` directory.
*/
builtInScaffoldsDir?: string;
}
/**
* Scaffold registry for discovering and managing scaffolds
*/
export class ScaffoldRegistry {
private providers: ScaffoldProvider[] = [];
private transformers: ScaffoldTransformer[] = [];
private scaffoldCache: Map<string, Scaffold[]> = new Map();
private readonly builtInScaffoldsDir: string;
constructor(options?: ScaffoldRegistryOptions) {
this.builtInScaffoldsDir = options?.builtInScaffoldsDir ?? SCAFFOLDS_DATA_DIR;
}
/**
* Add scaffold providers
*/
addProviders(providers: ScaffoldProvider[]): void {
this.providers.push(...providers);
this.clearCache();
}
/**
* Add scaffold transformers
*/
addTransformers(transformers: ScaffoldTransformer[]): void {
this.transformers.push(...transformers);
this.clearCache();
}
/**
* Clear the scaffold cache
*/
clearCache(): void {
this.scaffoldCache.clear();
}
/**
* Get all scaffolds from all sources
* @param options - Discovery options
* @returns Array of scaffolds (deduplicated by name, later sources override earlier)
*/
async getScaffolds(options: ScaffoldDiscoveryOptions = {}): Promise<Scaffold[]> {
const cacheKey = JSON.stringify(options);
if (this.scaffoldCache.has(cacheKey)) {
return this.scaffoldCache.get(cacheKey)!;
}
// Collect scaffolds from all sources in priority order
const allScaffolds: Scaffold[] = [];
// 1. Run 'before' providers
const beforeProviders = this.providers.filter((p) => p.priority === 'before');
for (const provider of beforeProviders) {
const providerScaffolds = await provider.getScaffolds(options);
allScaffolds.push(...providerScaffolds);
}
// 2. Built-in scaffolds (lowest priority for built-ins)
const builtInScaffolds = await discoverScaffoldsFromDir(this.builtInScaffoldsDir, 'built-in');
allScaffolds.push(...builtInScaffolds);
// 3. User scaffolds (~/.b2c/scaffolds/)
const userScaffoldsDir = path.join(os.homedir(), '.b2c', 'scaffolds');
const userScaffolds = await discoverScaffoldsFromDir(userScaffoldsDir, 'user');
allScaffolds.push(...userScaffolds);
// 4. Project scaffolds (.b2c/scaffolds/) - highest priority
if (options.projectRoot) {
const projectScaffoldsDir = path.join(options.projectRoot, '.b2c', 'scaffolds');
const projectScaffolds = await discoverScaffoldsFromDir(projectScaffoldsDir, 'project');
allScaffolds.push(...projectScaffolds);
}
// 5. Run 'after' providers
const afterProviders = this.providers.filter((p) => p.priority === 'after');
for (const provider of afterProviders) {
const providerScaffolds = await provider.getScaffolds(options);
allScaffolds.push(...providerScaffolds);
}
// Deduplicate by ID (later sources override earlier)
const scaffoldMap = new Map<string, Scaffold>();
for (const scaffold of allScaffolds) {
scaffoldMap.set(scaffold.id, scaffold);
}
let scaffolds = Array.from(scaffoldMap.values());
// Apply transformers
for (const transformer of this.transformers) {
scaffolds = await Promise.all(
scaffolds.map((s) =>
transformer.transform(s, {
outputDir: process.cwd(),
variables: {},
dryRun: false,
force: false,
interactive: false,
}),
),
);
}
// Apply filters
scaffolds = filterScaffolds(scaffolds, options);
// Sort by name
scaffolds.sort((a, b) => a.id.localeCompare(b.id));
this.scaffoldCache.set(cacheKey, scaffolds);
return scaffolds;
}
/**
* Get a specific scaffold by ID
* @param id - Scaffold ID
* @param options - Discovery options
* @returns Scaffold or null if not found
*/
async getScaffold(id: string, options: ScaffoldDiscoveryOptions = {}): Promise<Scaffold | null> {
const scaffolds = await this.getScaffolds(options);
return scaffolds.find((s) => s.id === id) || null;
}
/**
* Search scaffolds by query
* @param query - Search query
* @param options - Additional discovery options
* @returns Matching scaffolds
*/
async searchScaffolds(query: string, options: ScaffoldDiscoveryOptions = {}): Promise<Scaffold[]> {
return this.getScaffolds({...options, query});
}
}
/**
* Create a new scaffold registry instance
*
* @param options - Registry options (e.g. override built-in scaffolds directory)
*/
export function createScaffoldRegistry(options?: ScaffoldRegistryOptions): ScaffoldRegistry {
return new ScaffoldRegistry(options);
}