| 1 | import JSZip from "jszip"; |
| 2 | |
| 3 | import { env } from "./env.js"; |
| 4 | import { logger } from "./util/logger.js"; |
| 5 | |
| 6 | /** |
| 7 | * Pattern to match valid hub slugs (owner/package format) |
| 8 | */ |
| 9 | const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; |
| 10 | |
| 11 | /** |
| 12 | * Hub package type definitions |
| 13 | */ |
| 14 | export type HubPackageType = "rule" | "mcp" | "model" | "prompt"; |
| 15 | |
| 16 | /** |
| 17 | * Hub package processor interface |
| 18 | */ |
| 19 | export interface HubPackageProcessor<T> { |
| 20 | type: HubPackageType; |
| 21 | expectedFileExtensions: string[]; |
| 22 | parseContent(content: string, filename: string): Promise<T> | T; |
| 23 | validateContent?(content: T): boolean; |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Rule processor - handles text content from .md files |
| 28 | */ |
| 29 | export const ruleProcessor: HubPackageProcessor<string> = { |
| 30 | type: "rule", |
| 31 | expectedFileExtensions: [".md"], |
| 32 | parseContent: (content: string) => content, |
| 33 | }; |
| 34 | |
| 35 | /** |
| 36 | * MCP processor - handles JSON/YAML configuration files |
| 37 | */ |
| 38 | export const mcpProcessor: HubPackageProcessor<any> = { |
| 39 | type: "mcp", |
| 40 | expectedFileExtensions: [".json", ".yaml", ".yml"], |
| 41 | parseContent: async (content: string, filename: string) => { |
| 42 | let parsed; |
| 43 | if (filename.endsWith(".json")) { |
| 44 | parsed = JSON.parse(content); |
| 45 | } else { |
| 46 | const yaml = await import("yaml"); |
| 47 | parsed = yaml.parse(content); |
| 48 | } |
| 49 | |
| 50 | // If the parsed content has an 'mcpServers' array, extract the first MCP server |
| 51 | // This handles hub packages that return a full config block |
| 52 | if ( |
| 53 | parsed.mcpServers && |
| 54 | Array.isArray(parsed.mcpServers) && |
| 55 | parsed.mcpServers.length > 0 |
| 56 | ) { |
| 57 | return parsed.mcpServers[0]; |
| 58 | } |
| 59 | |
| 60 | return parsed; |
| 61 | }, |
| 62 | }; |
| 63 | |
| 64 | /** |
| 65 | * Model processor - handles JSON/YAML configuration files |
| 66 | */ |
| 67 | export const modelProcessor: HubPackageProcessor<any> = { |
| 68 | type: "model", |
| 69 | expectedFileExtensions: [".json", ".yaml", ".yml"], |
| 70 | parseContent: async (content: string, filename: string) => { |
| 71 | let parsed; |
| 72 | if (filename.endsWith(".json")) { |
| 73 | parsed = JSON.parse(content); |
| 74 | } else { |
| 75 | const yaml = await import("yaml"); |
| 76 | parsed = yaml.parse(content); |
| 77 | } |
| 78 | |
| 79 | // If the parsed content has a 'models' array, extract the first model |
| 80 | // This handles hub packages that return a full config block |
| 81 | if ( |
| 82 | parsed.models && |
| 83 | Array.isArray(parsed.models) && |
| 84 | parsed.models.length > 0 |
| 85 | ) { |
| 86 | return parsed.models[0]; |
| 87 | } |
| 88 | |
| 89 | return parsed; |
| 90 | }, |
| 91 | }; |
| 92 | |
| 93 | /** |
| 94 | * Prompt processor - handles text content from .md files |
| 95 | */ |
| 96 | export const promptProcessor: HubPackageProcessor<string> = { |
| 97 | type: "prompt", |
| 98 | expectedFileExtensions: [".md", ".txt"], |
| 99 | parseContent: (content: string) => content, |
| 100 | }; |
| 101 | |
| 102 | /** |
| 103 | * Generic hub package loader |
| 104 | */ |
| 105 | export async function loadPackageFromHub<T>( |
| 106 | slug: string, |
| 107 | processor: HubPackageProcessor<T>, |
| 108 | ): Promise<T> { |
| 109 | const parts = slug.split("/"); |
| 110 | if (parts.length !== 2) { |
| 111 | throw new Error( |
| 112 | `Invalid hub slug format. Expected "owner/package", got: ${slug}`, |
| 113 | ); |
| 114 | } |
| 115 | |
| 116 | const [ownerSlug, packageSlug] = parts; |
| 117 | |
| 118 | // Use different endpoints based on package type |
| 119 | let downloadUrl: URL; |
| 120 | if (processor.type === "mcp" || processor.type === "model") { |
| 121 | // MCP and models use the registry endpoint |
| 122 | downloadUrl = new URL( |
| 123 | `registry/v1/${ownerSlug}/${packageSlug}/latest`, |
| 124 | env.apiBase, |
| 125 | ); |
| 126 | } else { |
| 127 | // Rules and prompts use the v0 endpoint |
| 128 | downloadUrl = new URL( |
| 129 | `v0/${ownerSlug}/${packageSlug}/latest/download`, |
| 130 | env.apiBase, |
| 131 | ); |
| 132 | } |
| 133 | |
| 134 | try { |
| 135 | const response = await fetch(downloadUrl); |
| 136 | |
| 137 | if (!response.ok) { |
| 138 | throw new Error(`HTTP ${response.status}: ${response.statusText}`); |
| 139 | } |
| 140 | |
| 141 | // Check if this is a registry endpoint (returns JSON directly) or a zip file |
| 142 | if (processor.type === "mcp" || processor.type === "model") { |
| 143 | // Registry endpoints return JSON with a 'content' field containing YAML/JSON |
| 144 | const jsonResponse = await response.json(); |
| 145 | |
| 146 | // Extract and parse the content field |
| 147 | if (jsonResponse.content) { |
| 148 | // Parse the YAML/JSON content |
| 149 | const parsedContent = await processor.parseContent( |
| 150 | jsonResponse.content, |
| 151 | `${slug}.yaml`, |
| 152 | ); |
| 153 | return parsedContent; |
| 154 | } else { |
| 155 | // If there's no content field, return the response as-is (backward compatibility) |
| 156 | return jsonResponse; |
| 157 | } |
| 158 | } else { |
| 159 | // v0 endpoints return zip files |
| 160 | const arrayBuffer = await response.arrayBuffer(); |
| 161 | const zip = new JSZip(); |
| 162 | const zipContents = await zip.loadAsync(arrayBuffer); |
| 163 | |
| 164 | // Find files matching expected extensions |
| 165 | const matchingFiles = Object.keys(zipContents.files).filter( |
| 166 | (filename) => { |
| 167 | if (zipContents.files[filename].dir) return false; |
| 168 | return processor.expectedFileExtensions.some((ext) => |
| 169 | filename.endsWith(ext), |
| 170 | ); |
| 171 | }, |
| 172 | ); |
| 173 | |
| 174 | if (matchingFiles.length === 0) { |
| 175 | throw new Error( |
| 176 | `No ${processor.type} content found in downloaded zip file. Expected files with extensions: ${processor.expectedFileExtensions.join(", ")}`, |
| 177 | ); |
| 178 | } |
| 179 | |
| 180 | // Use the first matching file |
| 181 | const contentFile = zipContents.files[matchingFiles[0]]; |
| 182 | const rawContent = await contentFile.async("text"); |
| 183 | |
| 184 | // Parse content using the processor |
| 185 | const parsedContent = await processor.parseContent( |
| 186 | rawContent, |
| 187 | matchingFiles[0], |
| 188 | ); |
| 189 | |
| 190 | // Validate if processor has validation |
| 191 | if ( |
| 192 | processor.validateContent && |
| 193 | !processor.validateContent(parsedContent) |
| 194 | ) { |
| 195 | throw new Error( |
| 196 | `Invalid ${processor.type} content in ${matchingFiles[0]}`, |
| 197 | ); |
| 198 | } |
| 199 | |
| 200 | return parsedContent; |
| 201 | } |
| 202 | } catch (error: any) { |
| 203 | throw new Error( |
| 204 | `Failed to load ${processor.type} from hub "${slug}": ${error.message}`, |
| 205 | ); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Convenience functions for specific package types |
| 211 | */ |
| 212 | export const loadRuleFromHub = (slug: string) => |
| 213 | loadPackageFromHub(slug, ruleProcessor); |
| 214 | |
| 215 | export const loadMcpFromHub = (slug: string) => |
| 216 | loadPackageFromHub(slug, mcpProcessor); |
| 217 | |
| 218 | export const loadModelFromHub = (slug: string) => |
| 219 | loadPackageFromHub(slug, modelProcessor); |
| 220 | |
| 221 | export const loadPromptFromHub = (slug: string) => |
| 222 | loadPackageFromHub(slug, promptProcessor); |
| 223 | |
| 224 | /** |
| 225 | * Process a rule specification - supports file paths, hub slugs, or direct content |
| 226 | */ |
| 227 | export async function processRule(ruleSpec: string): Promise<string> { |
| 228 | const trimmedRuleSpec = ruleSpec.trim(); |
| 229 | const hasNewline = /[\r\n]/.test(ruleSpec); |
| 230 | |
| 231 | // If it looks like a file path (single line, typical path indicators) |
| 232 | const looksLikePath = |
| 233 | !hasNewline && |
| 234 | (trimmedRuleSpec.startsWith(".") || |
| 235 | trimmedRuleSpec.startsWith("/") || |
| 236 | trimmedRuleSpec.includes("\\") || |
| 237 | /\.[a-zA-Z]+$/.test(trimmedRuleSpec)); |
| 238 | |
| 239 | if (looksLikePath) { |
| 240 | const fs = await import("fs"); |
| 241 | const path = await import("path"); |
| 242 | |
| 243 | try { |
| 244 | const absolutePath = path.resolve(trimmedRuleSpec); |
| 245 | if (!fs.existsSync(absolutePath)) { |
| 246 | throw new Error(`Rule file not found: ${ruleSpec}`); |
| 247 | } |
| 248 | return fs.readFileSync(absolutePath, "utf-8"); |
| 249 | } catch (error: any) { |
| 250 | throw new Error( |
| 251 | `Failed to read rule file "${ruleSpec}": ${error.message}`, |
| 252 | ); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // Check if it might be a hub slug (contains "/" and is a single line) |
| 257 | if (!hasNewline && trimmedRuleSpec.includes("/")) { |
| 258 | const parts = trimmedRuleSpec.split("/"); |
| 259 | |
| 260 | // If it's exactly 2 parts and matches hub slug pattern, treat as hub slug |
| 261 | if (parts.length === 2 && HUB_SLUG_PATTERN.test(trimmedRuleSpec)) { |
| 262 | return await loadRuleFromHub(trimmedRuleSpec); |
| 263 | } |
| 264 | |
| 265 | // If it has more than 2 parts, it's an invalid hub slug |
| 266 | if (parts.length > 2) { |
| 267 | throw new Error( |
| 268 | `Invalid hub slug format. Expected "owner/package", got: ${trimmedRuleSpec}`, |
| 269 | ); |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // Otherwise, treat it as direct string content |
| 274 | return ruleSpec; |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Batch load multiple packages with error handling |
| 279 | */ |
| 280 | export async function loadPackagesFromHub<T>( |
| 281 | slugs: string[], |
| 282 | processor: HubPackageProcessor<T>, |
| 283 | ): Promise<T[]> { |
| 284 | const results: T[] = []; |
| 285 | |
| 286 | for (const slug of slugs) { |
| 287 | try { |
| 288 | const content = await loadPackageFromHub(slug, processor); |
| 289 | results.push(content); |
| 290 | } catch (error: any) { |
| 291 | logger.warn( |
| 292 | `Failed to load ${processor.type} "${slug}": ${error.message}`, |
| 293 | ); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | return results; |
| 298 | } |