@wengine-ai/claude-code-router-shared 2.0.21

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,416 @@
1
+ /**
2
+ * Core preset installation functionality
3
+ * Note: This module does not contain CLI interaction logic, interaction logic is provided by the caller
4
+ */
5
+
6
+ import * as fs from 'fs/promises';
7
+ import * as path from 'path';
8
+ import JSON5 from 'json5';
9
+ import AdmZip from 'adm-zip';
10
+ import { PresetFile, ManifestFile, PresetInfo, PresetMetadata } from './types';
11
+ import { HOME_DIR, PRESETS_DIR } from '../constants';
12
+ import { loadConfigFromManifest } from './schema';
13
+
14
+ /**
15
+ * Validate if preset name is safe (prevent path traversal attacks)
16
+ * @param presetName Preset name
17
+ */
18
+ function validatePresetName(presetName: string): void {
19
+ if (!presetName || presetName.trim() === '') {
20
+ throw new Error('Preset name cannot be empty');
21
+ }
22
+
23
+ // Reject names containing path traversal sequences
24
+ if (presetName.includes('..') || presetName.includes('/') || presetName.includes('\\')) {
25
+ throw new Error('Invalid preset name: path traversal detected');
26
+ }
27
+
28
+ // Reject absolute paths
29
+ if (path.isAbsolute(presetName)) {
30
+ throw new Error('Invalid preset name: absolute path not allowed');
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Get the full path of the preset directory
36
+ * @param presetName Preset name
37
+ */
38
+ export function getPresetDir(presetName: string): string {
39
+ validatePresetName(presetName);
40
+ return path.join(HOME_DIR, 'presets', presetName);
41
+ }
42
+
43
+ /**
44
+ * Get temporary directory path
45
+ */
46
+ export function getTempDir(): string {
47
+ return path.join(HOME_DIR, 'temp');
48
+ }
49
+
50
+ /**
51
+ * Validate and normalize file path, ensuring it's within the target directory
52
+ * @param targetDir Target directory
53
+ * @param entryPath ZIP entry path
54
+ * @returns Safe absolute path
55
+ */
56
+ function validateAndResolvePath(targetDir: string, entryPath: string): string {
57
+ const resolvedTargetDir = path.resolve(targetDir);
58
+ const resolvedPath = path.resolve(targetDir, entryPath);
59
+
60
+ // Verify that the resolved path is within the target directory
61
+ if (!resolvedPath.startsWith(resolvedTargetDir)) {
62
+ throw new Error(`Path traversal detected: ${entryPath}`);
63
+ }
64
+
65
+ return resolvedPath;
66
+ }
67
+
68
+ /**
69
+ * Extract preset file to target directory
70
+ * @param sourceZip Source ZIP file path
71
+ * @param targetDir Target directory
72
+ */
73
+ export async function extractPreset(sourceZip: string, targetDir: string): Promise<void> {
74
+ // Check if target directory already exists
75
+ try {
76
+ await fs.access(targetDir);
77
+ throw new Error(`Preset directory already exists: ${path.basename(targetDir)}`);
78
+ } catch (error: any) {
79
+ if (error.code !== 'ENOENT') {
80
+ throw error;
81
+ }
82
+ // ENOENT means directory does not exist, can continue
83
+ }
84
+
85
+ // Create target directory
86
+ await fs.mkdir(targetDir, { recursive: true });
87
+
88
+ // Extract files
89
+ const zip = new AdmZip(sourceZip);
90
+ const entries = zip.getEntries();
91
+
92
+ // Detect if there's a single root directory (GitHub ZIP files usually have this characteristic)
93
+ if (entries.length > 0) {
94
+ // Get all top-level directories
95
+ const rootDirs = new Set<string>();
96
+ for (const entry of entries) {
97
+ const parts = entry.entryName.split('/');
98
+ if (parts.length > 1) {
99
+ rootDirs.add(parts[0]);
100
+ }
101
+ }
102
+
103
+ // If there's only one root directory, remove it
104
+ if (rootDirs.size === 1) {
105
+ const singleRoot = Array.from(rootDirs)[0];
106
+
107
+ // Check if manifest.json is in root directory
108
+ const hasManifestInRoot = entries.some(e =>
109
+ e.entryName === 'manifest.json' || e.entryName.startsWith(`${singleRoot}/manifest.json`)
110
+ );
111
+
112
+ if (hasManifestInRoot) {
113
+ // Extract all files from the root directory
114
+ for (const entry of entries) {
115
+ if (entry.isDirectory) {
116
+ continue;
117
+ }
118
+
119
+ // Remove root directory prefix
120
+ let newPath = entry.entryName;
121
+ if (newPath.startsWith(`${singleRoot}/`)) {
122
+ newPath = newPath.substring(singleRoot.length + 1);
123
+ }
124
+
125
+ // Skip root directory itself
126
+ if (newPath === '' || newPath === singleRoot) {
127
+ continue;
128
+ }
129
+
130
+ // Validate path safety and extract file
131
+ const targetPath = validateAndResolvePath(targetDir, newPath);
132
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
133
+ await fs.writeFile(targetPath, entry.getData());
134
+ }
135
+
136
+ return;
137
+ }
138
+ }
139
+ }
140
+
141
+ // If there's no single root directory, validate and extract files one by one
142
+ for (const entry of entries) {
143
+ if (entry.isDirectory) {
144
+ continue;
145
+ }
146
+
147
+ // Validate path safety
148
+ const targetPath = validateAndResolvePath(targetDir, entry.entryName);
149
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
150
+ await fs.writeFile(targetPath, entry.getData());
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Read manifest from extracted directory
156
+ * @param presetDir Preset directory path
157
+ */
158
+ export async function readManifestFromDir(presetDir: string): Promise<ManifestFile> {
159
+ const manifestPath = path.join(presetDir, 'manifest.json');
160
+ const content = await fs.readFile(manifestPath, 'utf-8');
161
+ return JSON5.parse(content) as ManifestFile;
162
+ }
163
+
164
+ /**
165
+ * List of known metadata fields
166
+ */
167
+ const METADATA_FIELDS = [
168
+ 'name',
169
+ 'version',
170
+ 'description',
171
+ 'author',
172
+ 'homepage',
173
+ 'repository',
174
+ 'license',
175
+ 'keywords',
176
+ 'ccrVersion',
177
+ 'source',
178
+ 'sourceType',
179
+ 'checksum',
180
+ ];
181
+
182
+ /**
183
+ * Dynamic configuration system field list
184
+ */
185
+ const DYNAMIC_CONFIG_FIELDS = [
186
+ 'schema',
187
+ 'template',
188
+ 'configMappings',
189
+ ];
190
+
191
+ /**
192
+ * Convert manifest to PresetFile format
193
+ * Correctly separate metadata, config, and dynamic configuration system fields
194
+ */
195
+ export function manifestToPresetFile(manifest: ManifestFile): PresetFile {
196
+ const metadata: any = {};
197
+ const config: any = {};
198
+ const dynamicConfig: any = {};
199
+
200
+ // Categorize all fields
201
+ for (const [key, value] of Object.entries(manifest)) {
202
+ if (METADATA_FIELDS.includes(key)) {
203
+ // metadata fields
204
+ metadata[key] = value;
205
+ } else if (DYNAMIC_CONFIG_FIELDS.includes(key)) {
206
+ // dynamic configuration system fields
207
+ dynamicConfig[key] = value;
208
+ } else {
209
+ // configuration fields
210
+ config[key] = value;
211
+ }
212
+ }
213
+
214
+ return {
215
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
216
+ config,
217
+ schema: dynamicConfig.schema,
218
+ template: dynamicConfig.template,
219
+ configMappings: dynamicConfig.configMappings,
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Download preset file to temporary location
225
+ * @param url Download URL
226
+ * @returns Temporary file path
227
+ */
228
+ export async function downloadPresetToTemp(url: string): Promise<string> {
229
+ const response = await fetch(url);
230
+ if (!response.ok) {
231
+ throw new Error(`Failed to download preset: ${response.statusText}`);
232
+ }
233
+ const buffer = await response.arrayBuffer();
234
+
235
+ // Create temporary file
236
+ const tempDir = getTempDir();
237
+ await fs.mkdir(tempDir, { recursive: true });
238
+
239
+ const tempFile = path.join(tempDir, `preset-${Date.now()}.zip`);
240
+ await fs.writeFile(tempFile, Buffer.from(buffer));
241
+
242
+ return tempFile;
243
+ }
244
+
245
+ /**
246
+ * Load preset file
247
+ * @param source Preset source (preset name or directory path)
248
+ */
249
+ export async function loadPreset(source: string): Promise<PresetFile> {
250
+ // Check if it's absolute or relative path (contains / or \)
251
+ if (source.includes('/') || source.includes('\\')) {
252
+ // Directory path - read manifest from directory
253
+ const manifestPath = path.join(source, 'manifest.json');
254
+ const content = await fs.readFile(manifestPath, 'utf-8');
255
+ const manifest = JSON5.parse(content) as ManifestFile;
256
+ return manifestToPresetFile(manifest);
257
+ }
258
+
259
+ // Otherwise treat as preset name (read from presets directory)
260
+ const presetDir = getPresetDir(source);
261
+ const manifest = await readManifestFromDir(presetDir);
262
+ return manifestToPresetFile(manifest);
263
+ }
264
+
265
+ /**
266
+ * Validate preset file
267
+ */
268
+ export async function validatePreset(preset: PresetFile): Promise<{
269
+ valid: boolean;
270
+ errors: string[];
271
+ warnings: string[];
272
+ }> {
273
+ const errors: string[] = [];
274
+ const warnings: string[] = [];
275
+
276
+ // Validate metadata
277
+ if (!preset.metadata) {
278
+ warnings.push('Missing metadata section');
279
+ } else {
280
+ if (!preset.metadata.name) {
281
+ errors.push('Missing preset name in metadata');
282
+ }
283
+ if (!preset.metadata.version) {
284
+ warnings.push('Missing version in metadata');
285
+ }
286
+ }
287
+
288
+ // Validate configuration section
289
+ if (!preset.config) {
290
+ errors.push('Missing config section');
291
+ }
292
+
293
+ // Validate Providers
294
+ if (preset.config.Providers) {
295
+ for (const provider of preset.config.Providers) {
296
+ if (!provider.name) {
297
+ errors.push('Provider missing name field');
298
+ }
299
+ if (!provider.api_base_url) {
300
+ errors.push(`Provider "${provider.name}" missing api_base_url`);
301
+ }
302
+ if (!provider.models || provider.models.length === 0) {
303
+ warnings.push(`Provider "${provider.name}" has no models`);
304
+ }
305
+ }
306
+ }
307
+
308
+ return {
309
+ valid: errors.length === 0,
310
+ errors,
311
+ warnings,
312
+ };
313
+ }
314
+
315
+ /**
316
+ * Extract metadata fields from manifest
317
+ * @param manifest Manifest object
318
+ * @returns Metadata object
319
+ */
320
+ export function extractMetadata(manifest: ManifestFile): PresetMetadata {
321
+ const metadata: PresetMetadata = {
322
+ name: manifest.name,
323
+ version: manifest.version,
324
+ };
325
+
326
+ // Optional fields
327
+ if (manifest.description !== undefined) metadata.description = manifest.description;
328
+ if (manifest.author !== undefined) metadata.author = manifest.author;
329
+ if (manifest.homepage !== undefined) metadata.homepage = manifest.homepage;
330
+ if (manifest.repository !== undefined) metadata.repository = manifest.repository;
331
+ if (manifest.license !== undefined) metadata.license = manifest.license;
332
+ if (manifest.keywords !== undefined) metadata.keywords = manifest.keywords;
333
+ if (manifest.ccrVersion !== undefined) metadata.ccrVersion = manifest.ccrVersion;
334
+ if (manifest.source !== undefined) metadata.source = manifest.source;
335
+ if (manifest.sourceType !== undefined) metadata.sourceType = manifest.sourceType;
336
+ if (manifest.checksum !== undefined) metadata.checksum = manifest.checksum;
337
+
338
+ return metadata;
339
+ }
340
+
341
+ /**
342
+ * Save manifest to preset directory
343
+ * @param presetName Preset name
344
+ * @param manifest Manifest object
345
+ */
346
+ export async function saveManifest(presetName: string, manifest: ManifestFile): Promise<void> {
347
+ const presetDir = getPresetDir(presetName);
348
+ const manifestPath = path.join(presetDir, 'manifest.json');
349
+ await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
350
+ }
351
+
352
+ /**
353
+ * Check if preset is already installed
354
+ * @param presetName Preset name
355
+ */
356
+ export async function isPresetInstalled(presetName: string): Promise<boolean> {
357
+ const presetDir = getPresetDir(presetName);
358
+ try {
359
+ await fs.access(presetDir);
360
+ return true;
361
+ } catch {
362
+ return false;
363
+ }
364
+ }
365
+
366
+ /**
367
+ * List all installed presets
368
+ * @returns Array of PresetInfo
369
+ */
370
+ export async function listPresets(): Promise<PresetInfo[]> {
371
+ const presetsDir = PRESETS_DIR;
372
+ const presets: PresetInfo[] = [];
373
+
374
+ try {
375
+ await fs.access(presetsDir);
376
+ } catch {
377
+ return presets;
378
+ }
379
+
380
+ // Read all subdirectories in the directory
381
+ const entries = await fs.readdir(presetsDir, { withFileTypes: true });
382
+
383
+ for (const entry of entries) {
384
+ if (entry.isDirectory()) {
385
+ const presetName = entry.name;
386
+ const presetDir = path.join(presetsDir, presetName);
387
+ const manifestPath = path.join(presetDir, 'manifest.json');
388
+
389
+ try {
390
+ // Check if manifest.json exists
391
+ await fs.access(manifestPath);
392
+
393
+ // Read manifest.json
394
+ const content = await fs.readFile(manifestPath, 'utf-8');
395
+ const manifest = JSON5.parse(content) as ManifestFile;
396
+
397
+ // Get directory creation time
398
+ const stats = await fs.stat(presetDir);
399
+
400
+ presets.push({
401
+ name: manifest.name || presetName,
402
+ version: manifest.version,
403
+ description: manifest.description,
404
+ author: manifest.author,
405
+ config: loadConfigFromManifest(manifest, presetDir),
406
+ });
407
+ } catch {
408
+ // Ignore invalid preset directories (no manifest.json or read failed)
409
+ // Can choose to skip or add to list marked as error
410
+ continue;
411
+ }
412
+ }
413
+ }
414
+
415
+ return presets;
416
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Preset marketplace management
3
+ * Fetches preset market data directly from remote without caching
4
+ */
5
+
6
+ import { PresetIndexEntry } from './types';
7
+
8
+ // Preset market URL
9
+ const MARKET_URL = 'https://pub-0dc3e1677e894f07bbea11b17a29e032.r2.dev/presets.json';
10
+
11
+ /**
12
+ * Fetch preset market data from remote URL
13
+ */
14
+ async function fetchMarketData(): Promise<PresetIndexEntry[]> {
15
+ const response = await fetch(MARKET_URL);
16
+
17
+ if (!response.ok) {
18
+ throw new Error(`Failed to fetch preset market: ${response.status} ${response.statusText}`);
19
+ }
20
+
21
+ const data = await response.json() as PresetIndexEntry[];
22
+ return data;
23
+ }
24
+
25
+ /**
26
+ * Get preset market data (always fetches from remote)
27
+ * @returns Array of preset market entries
28
+ */
29
+ export async function getMarketPresets(): Promise<PresetIndexEntry[]> {
30
+ return await fetchMarketData();
31
+ }
32
+
33
+ /**
34
+ * Find a preset in the market by preset name (id or name field)
35
+ * @param presetName Preset name to search for
36
+ * @returns Preset entry if found, null otherwise
37
+ */
38
+ export async function findMarketPresetByName(presetName: string): Promise<PresetIndexEntry | null> {
39
+ const marketPresets = await getMarketPresets();
40
+
41
+ // First try exact match by id
42
+ let preset = marketPresets.find(p => p.id === presetName);
43
+
44
+ // If not found, try exact match by name
45
+ if (!preset) {
46
+ preset = marketPresets.find(p => p.name === presetName);
47
+ }
48
+
49
+ // If still not found, try case-insensitive match by name
50
+ if (!preset) {
51
+ const lowerName = presetName.toLowerCase();
52
+ preset = marketPresets.find(p => p.name.toLowerCase() === lowerName);
53
+ }
54
+
55
+ return preset || null;
56
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Configuration merge strategies
3
+ */
4
+
5
+ import { MergeStrategy, ProviderConfig, RouterConfig, TransformerConfig } from './types';
6
+
7
+ /**
8
+ * Merge Provider configuration
9
+ * Overwrite if provider exists, otherwise add
10
+ */
11
+ function mergeProviders(
12
+ existing: ProviderConfig[],
13
+ incoming: ProviderConfig[]
14
+ ): ProviderConfig[] {
15
+ const result = [...existing];
16
+ const existingNames = new Map(existing.map(p => [p.name, result.findIndex(x => x.name === p.name)]));
17
+
18
+ for (const provider of incoming) {
19
+ const existingIndex = existingNames.get(provider.name);
20
+ if (existingIndex !== undefined) {
21
+ // Provider exists, overwrite directly
22
+ result[existingIndex] = provider;
23
+ } else {
24
+ // New provider, add directly
25
+ result.push(provider);
26
+ }
27
+ }
28
+
29
+ return result;
30
+ }
31
+
32
+ /**
33
+ * Merge Router configuration
34
+ */
35
+ async function mergeRouter(
36
+ existing: RouterConfig,
37
+ incoming: RouterConfig,
38
+ strategy: MergeStrategy,
39
+ onRouterConflict?: (key: string, existingValue: any, newValue: any) => Promise<boolean>
40
+ ): Promise<RouterConfig> {
41
+ const result = { ...existing };
42
+
43
+ for (const [key, value] of Object.entries(incoming)) {
44
+ if (value === undefined || value === null) {
45
+ continue;
46
+ }
47
+
48
+ const existingValue = result[key];
49
+
50
+ if (existingValue === undefined || existingValue === null) {
51
+ // No such routing rule in existing config, add directly
52
+ result[key] = value;
53
+ } else {
54
+ // Conflict exists
55
+ if (strategy === MergeStrategy.ASK && onRouterConflict) {
56
+ const shouldOverwrite = await onRouterConflict(key, existingValue, value);
57
+ if (shouldOverwrite) {
58
+ result[key] = value;
59
+ }
60
+ } else if (strategy === MergeStrategy.OVERWRITE) {
61
+ result[key] = value;
62
+ } else if (strategy === MergeStrategy.MERGE) {
63
+ // For Router, merge strategy equals skip, keep existing value
64
+ // Or can ask user
65
+ }
66
+ // skip strategy: keep existing value, do nothing
67
+ }
68
+ }
69
+
70
+ return result;
71
+ }
72
+
73
+ /**
74
+ * Merge Transformer configuration
75
+ */
76
+ async function mergeTransformers(
77
+ existing: TransformerConfig[],
78
+ incoming: TransformerConfig[],
79
+ strategy: MergeStrategy,
80
+ onTransformerConflict?: (transformerPath: string) => Promise<'keep' | 'overwrite' | 'skip'>
81
+ ): Promise<TransformerConfig[]> {
82
+ if (!existing || existing.length === 0) {
83
+ return incoming;
84
+ }
85
+
86
+ if (!incoming || incoming.length === 0) {
87
+ return existing;
88
+ }
89
+
90
+ // Transformer merge logic: match by path
91
+ const result = [...existing];
92
+ const existingPaths = new Set(existing.map(t => t.path));
93
+
94
+ for (const transformer of incoming) {
95
+ if (!transformer.path) {
96
+ // Transformer without path, add directly
97
+ result.push(transformer);
98
+ continue;
99
+ }
100
+
101
+ if (existingPaths.has(transformer.path)) {
102
+ // Transformer with same path already exists
103
+ if (strategy === MergeStrategy.ASK && onTransformerConflict) {
104
+ const action = await onTransformerConflict(transformer.path);
105
+ if (action === 'overwrite') {
106
+ const index = result.findIndex(t => t.path === transformer.path);
107
+ result[index] = transformer;
108
+ }
109
+ // keep and skip do nothing
110
+ } else if (strategy === MergeStrategy.OVERWRITE) {
111
+ const index = result.findIndex(t => t.path === transformer.path);
112
+ result[index] = transformer;
113
+ }
114
+ // merge and skip strategies: keep existing
115
+ } else {
116
+ // New transformer, add directly
117
+ result.push(transformer);
118
+ }
119
+ }
120
+
121
+ return result;
122
+ }
123
+
124
+ /**
125
+ * Merge other top-level configurations
126
+ */
127
+ async function mergeOtherConfig(
128
+ existing: any,
129
+ incoming: any,
130
+ strategy: MergeStrategy,
131
+ onConfigConflict?: (key: string) => Promise<boolean>,
132
+ excludeKeys: string[] = ['Providers', 'Router', 'transformers']
133
+ ): Promise<any> {
134
+ const result = { ...existing };
135
+
136
+ for (const [key, value] of Object.entries(incoming)) {
137
+ if (excludeKeys.includes(key)) {
138
+ continue;
139
+ }
140
+
141
+ if (value === undefined || value === null) {
142
+ continue;
143
+ }
144
+
145
+ const existingValue = result[key];
146
+
147
+ if (existingValue === undefined || existingValue === null) {
148
+ // No such field in existing config, add directly
149
+ result[key] = value;
150
+ } else {
151
+ // Conflict exists
152
+ if (strategy === MergeStrategy.ASK && onConfigConflict) {
153
+ const shouldOverwrite = await onConfigConflict(key);
154
+ if (shouldOverwrite) {
155
+ result[key] = value;
156
+ }
157
+ } else if (strategy === MergeStrategy.OVERWRITE) {
158
+ result[key] = value;
159
+ }
160
+ // merge and skip strategies: keep existing值
161
+ }
162
+ }
163
+
164
+ return result;
165
+ }
166
+
167
+ /**
168
+ * Merge interaction callback interface
169
+ */
170
+ export interface MergeCallbacks {
171
+ onRouterConflict?: (key: string, existingValue: any, newValue: any) => Promise<boolean>;
172
+ onTransformerConflict?: (transformerPath: string) => Promise<'keep' | 'overwrite' | 'skip'>;
173
+ onConfigConflict?: (key: string) => Promise<boolean>;
174
+ }
175
+
176
+ /**
177
+ * Main configuration merge function
178
+ * @param baseConfig Base configuration (existing configuration)
179
+ * @param presetConfig Preset configuration
180
+ * @param strategy Merge strategy
181
+ * @param callbacks Interactive callback functions
182
+ * @returns Merged configuration
183
+ */
184
+ export async function mergeConfig(
185
+ baseConfig: any,
186
+ presetConfig: any,
187
+ strategy: MergeStrategy = MergeStrategy.ASK,
188
+ callbacks?: MergeCallbacks
189
+ ): Promise<any> {
190
+ const result = { ...baseConfig };
191
+
192
+ // Merge Providers
193
+ if (presetConfig.Providers) {
194
+ result.Providers = mergeProviders(
195
+ result.Providers || [],
196
+ presetConfig.Providers
197
+ );
198
+ }
199
+
200
+ // Merge Router
201
+ if (presetConfig.Router) {
202
+ result.Router = await mergeRouter(
203
+ result.Router || {},
204
+ presetConfig.Router,
205
+ strategy,
206
+ callbacks?.onRouterConflict
207
+ );
208
+ }
209
+
210
+ // Merge transformers
211
+ if (presetConfig.transformers) {
212
+ result.transformers = await mergeTransformers(
213
+ result.transformers || [],
214
+ presetConfig.transformers,
215
+ strategy,
216
+ callbacks?.onTransformerConflict
217
+ );
218
+ }
219
+
220
+ // Merge other configurations
221
+ const otherConfig = await mergeOtherConfig(
222
+ result,
223
+ presetConfig,
224
+ strategy,
225
+ callbacks?.onConfigConflict
226
+ );
227
+
228
+ return otherConfig;
229
+ }