prpm 0.2.0 → 1.0.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.
Files changed (48) hide show
  1. package/dist/index.js +14257 -109
  2. package/package.json +11 -9
  3. package/dist/__tests__/e2e/test-helpers.js +0 -153
  4. package/dist/commands/buy-credits.js +0 -224
  5. package/dist/commands/catalog.js +0 -365
  6. package/dist/commands/collections.js +0 -655
  7. package/dist/commands/config.js +0 -161
  8. package/dist/commands/credits.js +0 -186
  9. package/dist/commands/index.js +0 -184
  10. package/dist/commands/info.js +0 -78
  11. package/dist/commands/init.js +0 -684
  12. package/dist/commands/install.js +0 -829
  13. package/dist/commands/list.js +0 -198
  14. package/dist/commands/login.js +0 -316
  15. package/dist/commands/outdated.js +0 -130
  16. package/dist/commands/playground.js +0 -637
  17. package/dist/commands/popular.js +0 -33
  18. package/dist/commands/publish.js +0 -803
  19. package/dist/commands/schema.js +0 -41
  20. package/dist/commands/search.js +0 -446
  21. package/dist/commands/starred.js +0 -147
  22. package/dist/commands/subscribe.js +0 -211
  23. package/dist/commands/telemetry.js +0 -104
  24. package/dist/commands/trending.js +0 -86
  25. package/dist/commands/uninstall.js +0 -120
  26. package/dist/commands/update.js +0 -121
  27. package/dist/commands/upgrade.js +0 -121
  28. package/dist/commands/whoami.js +0 -83
  29. package/dist/core/claude-config.js +0 -91
  30. package/dist/core/cursor-config.js +0 -130
  31. package/dist/core/downloader.js +0 -64
  32. package/dist/core/errors.js +0 -29
  33. package/dist/core/filesystem.js +0 -246
  34. package/dist/core/lockfile.js +0 -292
  35. package/dist/core/marketplace-converter.js +0 -224
  36. package/dist/core/prompts.js +0 -62
  37. package/dist/core/registry-client.js +0 -305
  38. package/dist/core/schema-validator.js +0 -74
  39. package/dist/core/telemetry.js +0 -253
  40. package/dist/core/user-config.js +0 -147
  41. package/dist/types/registry.js +0 -12
  42. package/dist/types.js +0 -9
  43. package/dist/utils/license-extractor.js +0 -122
  44. package/dist/utils/multi-package.js +0 -117
  45. package/dist/utils/parallel-publisher.js +0 -144
  46. package/dist/utils/script-executor.js +0 -72
  47. package/dist/utils/snippet-extractor.js +0 -77
  48. package/dist/utils/webapp-url.js +0 -44
@@ -1,829 +0,0 @@
1
- "use strict";
2
- /**
3
- * Install command - Install packages from registry
4
- */
5
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- var desc = Object.getOwnPropertyDescriptor(m, k);
8
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
- desc = { enumerable: true, get: function() { return m[k]; } };
10
- }
11
- Object.defineProperty(o, k2, desc);
12
- }) : (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- o[k2] = m[k];
15
- }));
16
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
- Object.defineProperty(o, "default", { enumerable: true, value: v });
18
- }) : function(o, v) {
19
- o["default"] = v;
20
- });
21
- var __importStar = (this && this.__importStar) || (function () {
22
- var ownKeys = function(o) {
23
- ownKeys = Object.getOwnPropertyNames || function (o) {
24
- var ar = [];
25
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
- return ar;
27
- };
28
- return ownKeys(o);
29
- };
30
- return function (mod) {
31
- if (mod && mod.__esModule) return mod;
32
- var result = {};
33
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
- __setModuleDefault(result, mod);
35
- return result;
36
- };
37
- })();
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.handleInstall = handleInstall;
43
- exports.installFromLockfile = installFromLockfile;
44
- exports.createInstallCommand = createInstallCommand;
45
- const commander_1 = require("commander");
46
- const registry_client_1 = require("@pr-pm/registry-client");
47
- const user_config_1 = require("../core/user-config");
48
- const filesystem_1 = require("../core/filesystem");
49
- const telemetry_1 = require("../core/telemetry");
50
- const tar = __importStar(require("tar"));
51
- const errors_1 = require("../core/errors");
52
- const prompts_1 = require("../core/prompts");
53
- const path_1 = __importDefault(require("path"));
54
- const lockfile_1 = require("../core/lockfile");
55
- const cursor_config_1 = require("../core/cursor-config");
56
- const claude_config_1 = require("../core/claude-config");
57
- /**
58
- * Get icon for package format and subtype
59
- */
60
- function getPackageIcon(format, subtype) {
61
- // Subtype icons take precedence
62
- const subtypeIcons = {
63
- 'skill': 'šŸŽ“',
64
- 'agent': 'šŸ¤–',
65
- 'slash-command': '⚔',
66
- 'rule': 'šŸ“‹',
67
- 'prompt': 'šŸ’¬',
68
- 'collection': 'šŸ“¦',
69
- 'chatmode': 'šŸ’¬',
70
- 'tool': 'šŸ”§',
71
- 'hook': 'šŸŖ',
72
- };
73
- // Format-specific icons for rules/defaults
74
- const formatIcons = {
75
- 'claude': 'šŸ¤–',
76
- 'cursor': 'šŸ“‹',
77
- 'windsurf': '🌊',
78
- 'continue': 'āž”ļø',
79
- 'copilot': 'āœˆļø',
80
- 'kiro': 'šŸŽÆ',
81
- 'mcp': 'šŸ”—',
82
- 'agents.md': 'šŸ“',
83
- 'generic': 'šŸ“¦',
84
- };
85
- return subtypeIcons[subtype] || formatIcons[format] || 'šŸ“¦';
86
- }
87
- /**
88
- * Get human-readable label for package format and subtype
89
- */
90
- function getPackageLabel(format, subtype) {
91
- const formatLabels = {
92
- 'claude': 'Claude',
93
- 'cursor': 'Cursor',
94
- 'windsurf': 'Windsurf',
95
- 'continue': 'Continue',
96
- 'copilot': 'GitHub Copilot',
97
- 'kiro': 'Kiro',
98
- 'mcp': 'MCP',
99
- 'agents.md': 'Agents.md',
100
- 'generic': '',
101
- };
102
- const subtypeLabels = {
103
- 'skill': 'Skill',
104
- 'agent': 'Agent',
105
- 'slash-command': 'Slash Command',
106
- 'rule': 'Rule',
107
- 'prompt': 'Prompt',
108
- 'collection': 'Collection',
109
- 'chatmode': 'Chat Mode',
110
- 'tool': 'Tool',
111
- 'hook': 'Hook',
112
- };
113
- const formatLabel = formatLabels[format];
114
- const subtypeLabel = subtypeLabels[subtype];
115
- if (format === 'generic') {
116
- return subtypeLabel;
117
- }
118
- return `${formatLabel} ${subtypeLabel}`;
119
- }
120
- async function handleInstall(packageSpec, options) {
121
- const startTime = Date.now();
122
- let success = false;
123
- let error;
124
- try {
125
- // Check if this is explicitly a collection install (collections/name)
126
- if (packageSpec.startsWith('collections/')) {
127
- const collectionId = packageSpec.replace('collections/', '');
128
- console.log(`šŸ“„ Installing ${collectionId}@latest...`);
129
- const { handleCollectionInstall } = await Promise.resolve().then(() => __importStar(require('./collections.js')));
130
- return await handleCollectionInstall(collectionId, {
131
- format: options.as,
132
- skipOptional: false,
133
- dryRun: false,
134
- });
135
- }
136
- // Parse package spec (e.g., "react-rules" or "react-rules@1.2.0" or "@pr-pm/pkg@1.0.0")
137
- // For scoped packages (@scope/name), the first @ is part of the package name
138
- let packageId;
139
- let specVersion;
140
- if (packageSpec.startsWith('@')) {
141
- // Scoped package: @scope/name or @scope/name@version
142
- const match = packageSpec.match(/^(@[^/]+\/[^@]+)(?:@(.+))?$/);
143
- if (!match) {
144
- throw new Error('Invalid package spec format. Use: @scope/package or @scope/package@version');
145
- }
146
- packageId = match[1];
147
- specVersion = match[2];
148
- }
149
- else {
150
- // Unscoped package: name or name@version
151
- const parts = packageSpec.split('@');
152
- packageId = parts[0];
153
- specVersion = parts[1];
154
- }
155
- // Read existing lock file
156
- const lockfile = await (0, lockfile_1.readLockfile)();
157
- const lockedVersion = (0, lockfile_1.getLockedVersion)(lockfile, packageId);
158
- // Determine version to install
159
- let version;
160
- if (options.frozenLockfile) {
161
- // Frozen lockfile mode - must use exact locked version
162
- if (!lockedVersion) {
163
- throw new Error(`Package ${packageId} not found in lock file. Run without --frozen-lockfile to update.`);
164
- }
165
- version = lockedVersion;
166
- }
167
- else {
168
- // Normal mode - use specified version or locked version or latest
169
- version = options.version || specVersion || lockedVersion || 'latest';
170
- }
171
- // Check if package is already installed (skip if --force option is set)
172
- if (!options.force && lockfile && lockfile.packages[packageId]) {
173
- const installedPkg = lockfile.packages[packageId];
174
- const requestedVersion = options.version || specVersion;
175
- // If no specific version requested, or same version requested
176
- if (!requestedVersion || requestedVersion === 'latest' || requestedVersion === installedPkg.version) {
177
- console.log(`\n✨ Package already installed!`);
178
- console.log(` šŸ“¦ ${packageId}@${installedPkg.version}`);
179
- console.log(` šŸ”„ Format: ${installedPkg.format || 'unknown'} | Subtype: ${installedPkg.subtype || 'unknown'}`);
180
- console.log(`\nšŸ’” To reinstall or upgrade:`);
181
- console.log(` prpm upgrade ${packageId} # Upgrade to latest version`);
182
- console.log(` prpm uninstall ${packageId} # Uninstall first, then install`);
183
- success = true;
184
- return;
185
- }
186
- else if (requestedVersion !== installedPkg.version) {
187
- // Different version requested - allow upgrade/downgrade
188
- console.log(`šŸ“¦ Upgrading ${packageId}: ${installedPkg.version} → ${requestedVersion}`);
189
- }
190
- }
191
- console.log(`šŸ“„ Installing ${packageId}@${version}...`);
192
- const config = await (0, user_config_1.getConfig)();
193
- const client = (0, registry_client_1.getRegistryClient)(config);
194
- // Check if this is a collection first (by trying to fetch it)
195
- // Collections can be: name, scope/name, or @scope/name
196
- let isCollection = false;
197
- try {
198
- // Try to parse as collection
199
- let scope;
200
- let name_slug;
201
- const matchWithScope = packageId.match(/^@?([^/]+)\/([^/@]+)$/);
202
- if (matchWithScope) {
203
- [, scope, name_slug] = matchWithScope;
204
- }
205
- else {
206
- // No scope, assume 'collection' scope
207
- scope = 'collection';
208
- name_slug = packageId;
209
- }
210
- // Try to fetch as collection
211
- await client.getCollection(scope, name_slug, version === 'latest' ? undefined : version);
212
- isCollection = true;
213
- // If successful, delegate to collection install handler
214
- const { handleCollectionInstall } = await Promise.resolve().then(() => __importStar(require('./collections.js')));
215
- return await handleCollectionInstall(packageId, {
216
- format: options.as,
217
- skipOptional: false,
218
- dryRun: false,
219
- });
220
- }
221
- catch (err) {
222
- // Not a collection, continue with package install
223
- isCollection = false;
224
- }
225
- // Get package info
226
- const pkg = await client.getPackage(packageId);
227
- const typeIcon = getPackageIcon(pkg.format, pkg.subtype);
228
- const typeLabel = getPackageLabel(pkg.format, pkg.subtype);
229
- console.log(` ${pkg.name} ${pkg.official ? 'šŸ…' : ''}`);
230
- console.log(` ${pkg.description || 'No description'}`);
231
- console.log(` ${typeIcon} Type: ${typeLabel}`);
232
- // Check if this is a Claude hook and show informational message
233
- if (pkg.format === 'claude' && pkg.subtype === 'hook') {
234
- // Only show detailed warning if not part of a collection (to avoid spam)
235
- if (!options.fromCollection) {
236
- console.log(`\nšŸ“Œ Installing Claude Hook`);
237
- console.log(` āš ļø Note: Hooks execute shell commands automatically.`);
238
- console.log(` šŸ“– Review the hook configuration in .claude/settings.json after installation.`);
239
- console.log();
240
- }
241
- else {
242
- // Brief message for collection installs
243
- console.log(` šŸŖ Hook (merges into .claude/settings.json)`);
244
- }
245
- }
246
- // Determine format preference with priority order:
247
- // 1. CLI --as flag (highest priority)
248
- // 2. defaultFormat from .prpmrc config
249
- // 3. Auto-detection based on existing directories
250
- // 4. Package native format (fallback)
251
- let format = options.as;
252
- if (!format) {
253
- // Check for config default format
254
- if (config.defaultFormat) {
255
- format = config.defaultFormat;
256
- console.log(` āš™ļø Using default format from config: ${format}`);
257
- }
258
- else {
259
- // Auto-detect format based on existing directories
260
- const detectedFormat = await (0, filesystem_1.autoDetectFormat)();
261
- if (detectedFormat) {
262
- format = detectedFormat;
263
- console.log(` šŸ” Auto-detected ${format} format (found .${format}/ directory)`);
264
- }
265
- else {
266
- // No config or detection, use package's native format
267
- format = pkg.format;
268
- }
269
- }
270
- }
271
- // Special handling for Claude packages: default to CLAUDE.md if it doesn't exist
272
- // BUT only for packages that are generic rules (not skills, agents, or commands)
273
- if (!options.as && pkg.format === 'claude' && pkg.subtype === 'rule') {
274
- const claudeMdExists = await (0, filesystem_1.fileExists)('CLAUDE.md');
275
- if (!claudeMdExists) {
276
- // CLAUDE.md doesn't exist, install as CLAUDE.md (recommended format for Claude Code)
277
- format = 'claude-md';
278
- console.log(` šŸ’” Installing as CLAUDE.md (recommended for Claude Code)`);
279
- console.log(` To install as skill instead, use: prpm install ${packageId} --as claude`);
280
- }
281
- else {
282
- // CLAUDE.md already exists, install as skill to avoid overwriting
283
- console.log(` ā„¹ļø CLAUDE.md already exists, installing as skill in .claude/skills/`);
284
- }
285
- }
286
- if (options.as && format !== 'canonical') {
287
- console.log(` šŸ”„ Converting to ${format} format...`);
288
- }
289
- // Determine version to install
290
- let tarballUrl;
291
- let actualVersion;
292
- if (version === 'latest') {
293
- if (!pkg.latest_version) {
294
- throw new Error('No versions available for this package');
295
- }
296
- tarballUrl = pkg.latest_version.tarball_url;
297
- actualVersion = pkg.latest_version.version;
298
- console.log(` šŸ“¦ Installing version ${pkg.latest_version.version}`);
299
- }
300
- else {
301
- const versionInfo = await client.getPackageVersion(packageId, version);
302
- tarballUrl = versionInfo.tarball_url;
303
- actualVersion = version;
304
- console.log(` šŸ“¦ Installing version ${version}`);
305
- }
306
- // Download package in requested format
307
- console.log(` ā¬‡ļø Downloading...`);
308
- const tarball = await client.downloadPackage(tarballUrl, { format });
309
- // Extract tarball and save files
310
- console.log(` šŸ“‚ Extracting...`);
311
- // Determine effective format and subtype (from conversion or package native format)
312
- const effectiveFormat = format || pkg.format;
313
- const effectiveSubtype = options.subtype || pkg.subtype;
314
- // Extract all files from tarball
315
- const extractedFiles = await extractTarball(tarball, packageId);
316
- const locationOverride = options.location?.trim();
317
- if (locationOverride && effectiveFormat !== 'agents.md') {
318
- console.log(` āš ļø --location option currently only applies to Agents.md installs. Ignoring for ${effectiveFormat}.`);
319
- }
320
- // Track where files were saved for user feedback
321
- let destPath;
322
- let fileCount = 0;
323
- let hookMetadata = undefined;
324
- // Special handling for CLAUDE.md format (goes in project root)
325
- if (format === 'claude-md') {
326
- if (extractedFiles.length !== 1) {
327
- throw new Error('CLAUDE.md format only supports single-file packages');
328
- }
329
- let mainFile = extractedFiles[0].content;
330
- destPath = 'CLAUDE.md';
331
- await (0, filesystem_1.saveFile)(destPath, mainFile);
332
- fileCount = 1;
333
- }
334
- // Check if this is a multi-file package
335
- else if (extractedFiles.length === 1) {
336
- const destDir = (0, filesystem_1.getDestinationDir)(effectiveFormat, effectiveSubtype, pkg.name);
337
- // Single file package
338
- let mainFile = extractedFiles[0].content;
339
- // Determine file extension based on effective format
340
- // Cursor rules use .mdc, but slash commands and other files use .md
341
- const fileExtension = (effectiveFormat === 'cursor' && format === 'cursor') ? 'mdc' : 'md';
342
- const packageName = (0, filesystem_1.stripAuthorNamespace)(packageId);
343
- // For Claude skills, use SKILL.md filename in the package directory
344
- // For agents.md, always install as AGENTS.md in the project root
345
- // For Copilot, use official naming conventions
346
- // For other formats, use package name as filename
347
- if (effectiveFormat === 'claude' && effectiveSubtype === 'skill') {
348
- destPath = `${destDir}/SKILL.md`;
349
- }
350
- else if (effectiveFormat === 'claude' && effectiveSubtype === 'hook') {
351
- // Claude hooks are merged into settings.json
352
- destPath = `${destDir}/settings.json`;
353
- }
354
- else if (effectiveFormat === 'agents.md') {
355
- let targetPath = 'AGENTS.md';
356
- if (locationOverride) {
357
- targetPath = path_1.default.join(locationOverride, 'AGENTS.override.md');
358
- console.log(` šŸ“ Installing Agents.md package to custom location: ${targetPath}`);
359
- }
360
- destPath = targetPath;
361
- if (await (0, filesystem_1.fileExists)(destPath)) {
362
- if (options.force) {
363
- console.log(` āš ļø ${destPath} already exists - overwriting (forced).`);
364
- }
365
- else {
366
- console.log(` āš ļø ${destPath} already exists.`);
367
- const overwrite = await (0, prompts_1.promptYesNo)(` Overwrite existing ${destPath}? (y/N): `, ` āš ļø Non-interactive terminal detected. Remove or rename ${destPath} to continue.`);
368
- if (!overwrite) {
369
- console.log(` 🚫 Skipping install to avoid overwriting ${destPath}`);
370
- success = true;
371
- return;
372
- }
373
- }
374
- }
375
- }
376
- else if (effectiveFormat === 'copilot') {
377
- // Official GitHub Copilot naming conventions
378
- if (effectiveSubtype === 'chatmode') {
379
- // Chat modes: .github/chatmodes/NAME.chatmode.md
380
- destPath = `${destDir}/${packageName}.chatmode.md`;
381
- }
382
- else {
383
- // Path-specific instructions: .github/instructions/NAME.instructions.md
384
- destPath = `${destDir}/${packageName}.instructions.md`;
385
- }
386
- }
387
- else if (effectiveFormat === 'kiro' && effectiveSubtype === 'hook') {
388
- // Kiro hooks use .kiro.hook extension (JSON files)
389
- destPath = `${destDir}/${packageName}.kiro.hook`;
390
- }
391
- else {
392
- destPath = `${destDir}/${packageName}.${fileExtension}`;
393
- }
394
- // Handle cursor format - add header if missing for .mdc files
395
- if (format === 'cursor' && effectiveFormat === 'cursor') {
396
- if (!(0, cursor_config_1.hasMDCHeader)(mainFile)) {
397
- console.log(` āš ļø Adding missing MDC header...`);
398
- mainFile = (0, cursor_config_1.addMDCHeader)(mainFile, pkg.description);
399
- }
400
- // Apply cursor config if available
401
- if (config.cursor) {
402
- console.log(` āš™ļø Applying cursor config...`);
403
- mainFile = (0, cursor_config_1.applyCursorConfig)(mainFile, config.cursor);
404
- }
405
- }
406
- // Apply Claude config if downloading in Claude format
407
- if (format === 'claude' && (0, claude_config_1.hasClaudeHeader)(mainFile)) {
408
- if (config.claude) {
409
- console.log(` āš™ļø Applying Claude agent config...`);
410
- mainFile = (0, claude_config_1.applyClaudeConfig)(mainFile, config.claude);
411
- }
412
- }
413
- // Special handling for Claude hooks - merge into settings.json
414
- if (effectiveFormat === 'claude' && effectiveSubtype === 'hook') {
415
- const { readFile } = await Promise.resolve().then(() => __importStar(require('fs/promises')));
416
- // Parse the hook configuration from the downloaded file
417
- let hookConfig;
418
- try {
419
- hookConfig = JSON.parse(mainFile);
420
- }
421
- catch (err) {
422
- throw new Error(`Invalid hook configuration: ${err}. Hook file must be valid JSON.`);
423
- }
424
- // Generate unique hook ID for this installation
425
- const hookId = `${packageId}@${actualVersion || version}`;
426
- // Read existing settings.json if it exists
427
- let existingSettings = { hooks: {} };
428
- if (await (0, filesystem_1.fileExists)(destPath)) {
429
- try {
430
- const existingContent = await readFile(destPath, 'utf-8');
431
- existingSettings = JSON.parse(existingContent);
432
- if (!existingSettings.hooks) {
433
- existingSettings.hooks = {};
434
- }
435
- }
436
- catch (err) {
437
- console.log(` āš ļø Warning: Could not parse existing settings.json, creating new one.`);
438
- existingSettings = { hooks: {} };
439
- }
440
- }
441
- // Track which events this hook adds to
442
- const events = [];
443
- // Merge the new hook configuration
444
- // Assume the downloaded file contains a hooks object
445
- if (hookConfig.hooks) {
446
- for (const [event, eventHooks] of Object.entries(hookConfig.hooks)) {
447
- if (!existingSettings.hooks[event]) {
448
- existingSettings.hooks[event] = [];
449
- }
450
- // Add hook ID to each hook config for tracking
451
- const hooksWithId = eventHooks.map(hook => ({
452
- ...hook,
453
- __prpm_hook_id: hookId, // Internal tracking ID
454
- }));
455
- // Add new hooks to the event
456
- existingSettings.hooks[event] = [
457
- ...existingSettings.hooks[event],
458
- ...hooksWithId
459
- ];
460
- events.push(event);
461
- }
462
- console.log(` āœ“ Merged hook configuration into settings.json`);
463
- // Store metadata for lockfile
464
- hookMetadata = { events, hookId };
465
- }
466
- mainFile = JSON.stringify(existingSettings, null, 2);
467
- }
468
- await (0, filesystem_1.saveFile)(destPath, mainFile);
469
- fileCount = 1;
470
- }
471
- else {
472
- const destDir = (0, filesystem_1.getDestinationDir)(effectiveFormat, effectiveSubtype, pkg.name);
473
- // Multi-file package - create directory for package
474
- // For Claude skills, destDir already includes package name, so use it directly
475
- // For Cursor rules converted from Claude skills, use flat structure
476
- const packageName = (0, filesystem_1.stripAuthorNamespace)(packageId);
477
- const isCursorConversion = (effectiveFormat === 'cursor' && pkg.format === 'claude' && pkg.subtype === 'skill');
478
- const packageDir = (effectiveFormat === 'claude' && effectiveSubtype === 'skill')
479
- ? destDir
480
- : isCursorConversion
481
- ? destDir // Cursor uses flat structure
482
- : `${destDir}/${packageName}`;
483
- destPath = packageDir;
484
- console.log(` šŸ“ Multi-file package - creating directory: ${packageDir}`);
485
- // For Claude skills, verify SKILL.md exists
486
- if (effectiveFormat === 'claude' && effectiveSubtype === 'skill') {
487
- const skillMdIndex = extractedFiles.findIndex(f => f.name === 'SKILL.md' || f.name.endsWith('/SKILL.md'));
488
- if (skillMdIndex === -1) {
489
- // SKILL.md not found, look for common variations and auto-rename
490
- const skillFileIndex = extractedFiles.findIndex(f => f.name.toLowerCase().endsWith('skill.md') ||
491
- (f.name.endsWith('.md') && extractedFiles.length === 1) // Single .md file
492
- );
493
- if (skillFileIndex !== -1) {
494
- const oldName = extractedFiles[skillFileIndex].name;
495
- const basePath = oldName.substring(0, oldName.lastIndexOf('/') + 1);
496
- const newName = basePath + 'SKILL.md';
497
- console.log(` āš ļø Auto-fixing skill filename: ${oldName} → ${newName}`);
498
- console.log(` (Claude skills must be named SKILL.md per official documentation)`);
499
- extractedFiles[skillFileIndex].name = newName;
500
- }
501
- else {
502
- throw new Error('Claude skills must contain a SKILL.md file. ' +
503
- 'According to Claude documentation, skills must have a file named SKILL.md in their directory. ' +
504
- 'No suitable file found to rename. Please update the package to follow this requirement.');
505
- }
506
- }
507
- }
508
- // Track JSON files for @reference insertion in Cursor conversion
509
- const jsonFiles = [];
510
- for (const file of extractedFiles) {
511
- // Strip the tarball's root directory prefix to preserve subdirectories
512
- // Example: ".claude/skills/agent-builder/docs/examples.md" → "docs/examples.md"
513
- // ".claude/skills/agent-builder/SKILL.md" → "SKILL.md"
514
- // Find the common prefix (the package's root directory in the tarball)
515
- const pathParts = file.name.split('/');
516
- // For Claude skills, the tarball structure is typically: .claude/skills/package-name/...
517
- // We want to strip everything up to and including the package-name directory
518
- let relativeFileName = file.name;
519
- // Find the skills directory index
520
- const skillsDirIndex = pathParts.indexOf('skills');
521
- if (skillsDirIndex !== -1 && pathParts.length > skillsDirIndex + 2) {
522
- // Skip: .claude/skills/package-name/ and keep the rest
523
- relativeFileName = pathParts.slice(skillsDirIndex + 2).join('/');
524
- }
525
- else if (pathParts.length > 1) {
526
- // Fallback: just take the filename (last part)
527
- relativeFileName = pathParts[pathParts.length - 1];
528
- }
529
- let fileContent = file.content;
530
- let fileName = relativeFileName;
531
- // Handle Cursor conversion from Claude skill
532
- if (isCursorConversion) {
533
- // Convert SKILL.md to .mdc
534
- if (fileName === 'SKILL.md' || fileName.endsWith('/SKILL.md')) {
535
- fileName = `${packageName}.mdc`;
536
- // Add MDC header if missing
537
- if (!(0, cursor_config_1.hasMDCHeader)(fileContent)) {
538
- console.log(` āš ļø Adding MDC header to converted skill...`);
539
- fileContent = (0, cursor_config_1.addMDCHeader)(fileContent, pkg.description);
540
- }
541
- // Apply cursor config if available
542
- if (config.cursor) {
543
- console.log(` āš™ļø Applying cursor config...`);
544
- fileContent = (0, cursor_config_1.applyCursorConfig)(fileContent, config.cursor);
545
- }
546
- }
547
- // Track JSON files for @reference
548
- else if (fileName.endsWith('.json')) {
549
- // Flatten structure - remove subdirectories
550
- const jsonFileName = fileName.split('/').pop() || fileName;
551
- fileName = jsonFileName;
552
- jsonFiles.push(jsonFileName);
553
- }
554
- // For other files (docs, etc), flatten the structure
555
- else {
556
- fileName = fileName.split('/').pop() || fileName;
557
- }
558
- }
559
- const filePath = `${packageDir}/${fileName}`;
560
- await (0, filesystem_1.saveFile)(filePath, fileContent);
561
- fileCount++;
562
- }
563
- // Add @references to .mdc file for JSON files
564
- if (isCursorConversion && jsonFiles.length > 0) {
565
- const mdcFile = `${packageDir}/${packageName}.mdc`;
566
- const { readFile } = await Promise.resolve().then(() => __importStar(require('fs/promises')));
567
- let mdcContent = await readFile(mdcFile, 'utf-8');
568
- // Find the end of frontmatter (if exists)
569
- const frontmatterMatch = mdcContent.match(/^---\n[\s\S]*?\n---\n/);
570
- if (frontmatterMatch) {
571
- const frontmatterEnd = frontmatterMatch[0].length;
572
- const beforeFrontmatter = mdcContent.slice(0, frontmatterEnd);
573
- const afterFrontmatter = mdcContent.slice(frontmatterEnd);
574
- // Add @references right after frontmatter
575
- const references = jsonFiles.map(f => `@${f}`).join('\n');
576
- mdcContent = `${beforeFrontmatter}\n${references}\n${afterFrontmatter}`;
577
- await (0, filesystem_1.saveFile)(mdcFile, mdcContent);
578
- console.log(` āœ“ Added ${jsonFiles.length} @reference(s) to ${packageName}.mdc`);
579
- }
580
- }
581
- }
582
- // Update or create lock file
583
- const updatedLockfile = lockfile || (0, lockfile_1.createLockfile)();
584
- (0, lockfile_1.addToLockfile)(updatedLockfile, packageId, {
585
- version: actualVersion || version,
586
- tarballUrl,
587
- format: pkg.format, // Preserve original package format
588
- subtype: pkg.subtype, // Preserve original package subtype
589
- installedPath: destPath,
590
- fromCollection: options.fromCollection,
591
- hookMetadata, // Track hook installation metadata for uninstall
592
- });
593
- (0, lockfile_1.setPackageIntegrity)(updatedLockfile, packageId, tarball);
594
- await (0, lockfile_1.writeLockfile)(updatedLockfile);
595
- // Update lockfile (already done above via addToLockfile + writeLockfile)
596
- // No need to call addPackage again as it would be redundant
597
- // Track download analytics
598
- await client.trackDownload(packageId, {
599
- version: actualVersion || version,
600
- client: 'cli',
601
- format,
602
- });
603
- // Display the incremented download count
604
- const newDownloadCount = pkg.total_downloads + 1;
605
- console.log(`\nāœ… Successfully installed ${packageId}`);
606
- console.log(` šŸ“ Saved to: ${destPath}`);
607
- console.log(` šŸ”’ Lock file updated`);
608
- console.log(`\nšŸ’” This package has been downloaded ${newDownloadCount.toLocaleString()} times`);
609
- success = true;
610
- }
611
- catch (err) {
612
- error = err instanceof Error ? err.message : String(err);
613
- throw new errors_1.CLIError(`\nāŒ Installation failed: ${error}\n\nšŸ’” Tips:\n - Check package name: prpm search <query>\n - Get package info: prpm info <package>`, 1);
614
- }
615
- finally {
616
- await telemetry_1.telemetry.track({
617
- command: 'install',
618
- success,
619
- error,
620
- duration: Date.now() - startTime,
621
- data: {
622
- packageId: packageSpec ? packageSpec.split('@')[0] : 'lockfile',
623
- version: options.version || 'latest',
624
- convertTo: options.as,
625
- },
626
- });
627
- await telemetry_1.telemetry.shutdown();
628
- }
629
- }
630
- async function extractTarball(tarball, packageId) {
631
- const files = [];
632
- const zlib = await Promise.resolve().then(() => __importStar(require('zlib')));
633
- const fs = await Promise.resolve().then(() => __importStar(require('fs')));
634
- const os = await Promise.resolve().then(() => __importStar(require('os')));
635
- return new Promise((resolve, reject) => {
636
- // Decompress gzip first
637
- zlib.gunzip(tarball, async (err, result) => {
638
- if (err) {
639
- reject(err);
640
- return;
641
- }
642
- // Check if this is a tar archive by looking for tar header
643
- const isTar = result.length > 257 && result.toString('utf-8', 257, 262) === 'ustar';
644
- if (!isTar) {
645
- // Not a tar archive, treat as single gzipped file
646
- files.push({
647
- name: `${packageId}.md`,
648
- content: result.toString('utf-8')
649
- });
650
- resolve(files);
651
- return;
652
- }
653
- // Create temp directory for extraction
654
- const tmpDir = await fs.promises.mkdtemp(path_1.default.join(os.tmpdir(), 'prpm-'));
655
- try {
656
- // Write tar data to temp file
657
- const tarPath = path_1.default.join(tmpDir, 'package.tar');
658
- await fs.promises.writeFile(tarPath, result);
659
- // Extract using tar library
660
- await tar.extract({
661
- file: tarPath,
662
- cwd: tmpDir,
663
- });
664
- // Read all extracted files
665
- const extractedFiles = await fs.promises.readdir(tmpDir, { withFileTypes: true, recursive: true });
666
- // Files to exclude from package content (metadata files)
667
- const excludeFiles = ['package.tar', 'prpm.json', 'README.md', 'LICENSE', 'LICENSE.txt', 'LICENSE.md'];
668
- for (const entry of extractedFiles) {
669
- if (entry.isFile() && !excludeFiles.includes(entry.name)) {
670
- const filePath = path_1.default.join(entry.path || tmpDir, entry.name);
671
- const content = await fs.promises.readFile(filePath, 'utf-8');
672
- const relativePath = path_1.default.relative(tmpDir, filePath);
673
- files.push({
674
- name: relativePath,
675
- content
676
- });
677
- }
678
- }
679
- if (files.length === 0) {
680
- // No files found, fall back to single file
681
- files.push({
682
- name: `${packageId}.md`,
683
- content: result.toString('utf-8')
684
- });
685
- }
686
- // Cleanup
687
- await fs.promises.rm(tmpDir, { recursive: true, force: true });
688
- resolve(files);
689
- }
690
- catch (tarErr) {
691
- // Cleanup and fall back to single file
692
- await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => { });
693
- files.push({
694
- name: `${packageId}.md`,
695
- content: result.toString('utf-8')
696
- });
697
- resolve(files);
698
- }
699
- });
700
- });
701
- }
702
- /**
703
- * Detect project format from existing directories
704
- */
705
- function detectProjectFormat() {
706
- const fs = require('fs');
707
- if (fs.existsSync('.cursor/rules') || fs.existsSync('.cursor'))
708
- return 'cursor';
709
- if (fs.existsSync('.claude/agents') || fs.existsSync('.claude'))
710
- return 'claude';
711
- if (fs.existsSync('.continue'))
712
- return 'continue';
713
- if (fs.existsSync('.windsurf'))
714
- return 'windsurf';
715
- return null;
716
- }
717
- /**
718
- * Install all packages from prpm.lock
719
- */
720
- async function installFromLockfile(options) {
721
- try {
722
- // Read lockfile
723
- const lockfile = await (0, lockfile_1.readLockfile)();
724
- if (!lockfile) {
725
- throw new errors_1.CLIError('āŒ No prpm.lock file found\n\nšŸ’” Run "prpm install <package>" first to create a lockfile, or initialize a new project with "prpm init"', 1);
726
- }
727
- const packageIds = Object.keys(lockfile.packages);
728
- if (packageIds.length === 0) {
729
- console.log('āœ… No packages to install (prpm.lock is empty)');
730
- return;
731
- }
732
- console.log(`šŸ“¦ Installing ${packageIds.length} package${packageIds.length === 1 ? '' : 's'} from prpm.lock...\n`);
733
- let successCount = 0;
734
- let failCount = 0;
735
- // Install each package from lockfile
736
- for (const packageId of packageIds) {
737
- const lockEntry = lockfile.packages[packageId];
738
- try {
739
- // Extract package spec (strip version if present in packageId)
740
- const packageSpec = packageId.includes('@') && !packageId.startsWith('@')
741
- ? packageId.substring(0, packageId.lastIndexOf('@'))
742
- : packageId;
743
- console.log(` Installing ${packageId}...`);
744
- let locationOverride = options.location;
745
- if (!locationOverride && lockEntry.format === 'agents.md' && lockEntry.installedPath) {
746
- const baseName = path_1.default.basename(lockEntry.installedPath);
747
- if (baseName === 'AGENTS.override.md') {
748
- locationOverride = path_1.default.dirname(lockEntry.installedPath);
749
- }
750
- else if (baseName !== 'AGENTS.md') {
751
- // If the lockfile contains a non-standard filename, honor its directory
752
- locationOverride = path_1.default.dirname(lockEntry.installedPath);
753
- }
754
- }
755
- await handleInstall(packageSpec, {
756
- version: lockEntry.version,
757
- as: options.as || lockEntry.format,
758
- subtype: options.subtype || lockEntry.subtype,
759
- frozenLockfile: options.frozenLockfile,
760
- force: true, // Force reinstall when installing from lockfile
761
- location: locationOverride,
762
- });
763
- successCount++;
764
- }
765
- catch (error) {
766
- // Check if this is a success exit (CLIError with exitCode 0)
767
- if (error instanceof errors_1.CLIError && error.exitCode === 0) {
768
- successCount++;
769
- }
770
- else {
771
- failCount++;
772
- console.error(` āŒ Failed to install ${packageId}:`);
773
- console.error(` Type: ${error?.constructor?.name}`);
774
- console.error(` Message: ${error instanceof Error ? error.message : String(error)}`);
775
- if (error instanceof errors_1.CLIError) {
776
- console.error(` ExitCode: ${error.exitCode}`);
777
- }
778
- }
779
- }
780
- }
781
- console.log(`\nāœ… Installed ${successCount}/${packageIds.length} packages`);
782
- if (failCount > 0) {
783
- throw new errors_1.CLIError(`āŒ ${failCount} package${failCount === 1 ? '' : 's'} failed to install`, 1);
784
- }
785
- }
786
- catch (error) {
787
- if (error instanceof errors_1.CLIError) {
788
- throw error;
789
- }
790
- throw new errors_1.CLIError(`āŒ Failed to install from lockfile: ${error}`, 1);
791
- }
792
- }
793
- function createInstallCommand() {
794
- const command = new commander_1.Command('install');
795
- command
796
- .description('Install a package from the registry, or install all packages from prpm.lock if no package specified')
797
- .argument('[package]', 'Package to install (e.g., react-rules or react-rules@1.2.0). If omitted, installs all packages from prpm.lock')
798
- .option('--version <version>', 'Specific version to install')
799
- .option('--as <format>', 'Convert and install in specific format (cursor, claude, continue, windsurf, copilot, kiro, agents.md, canonical)')
800
- .option('--format <format>', 'Alias for --as')
801
- .option('--location <path>', 'Custom location for installed files (currently supports Agents.md)')
802
- .option('--subtype <subtype>', 'Specify subtype when converting (skill, agent, rule, etc.)')
803
- .option('--frozen-lockfile', 'Fail if lock file needs to be updated (for CI)')
804
- .action(async (packageSpec, options) => {
805
- // Support both --as and --format (format is alias for as)
806
- const convertTo = options.format || options.as;
807
- if (convertTo && !['cursor', 'claude', 'continue', 'windsurf', 'copilot', 'kiro', 'agents.md', 'canonical'].includes(convertTo)) {
808
- throw new errors_1.CLIError('āŒ Format must be one of: cursor, claude, continue, windsurf, copilot, kiro, agents.md, canonical\n\nšŸ’” Examples:\n prpm install my-package --as cursor # Convert to Cursor format\n prpm install my-package --format claude # Convert to Claude format\n prpm install my-package --format kiro # Convert to Kiro format\n prpm install my-package --format agents.md # Convert to Agents.md format\n prpm install my-package # Install in native format', 1);
809
- }
810
- // If no package specified, install from lockfile
811
- if (!packageSpec) {
812
- await installFromLockfile({
813
- as: convertTo,
814
- subtype: options.subtype,
815
- frozenLockfile: options.frozenLockfile,
816
- location: options.location,
817
- });
818
- return;
819
- }
820
- await handleInstall(packageSpec, {
821
- version: options.version,
822
- as: convertTo,
823
- subtype: options.subtype,
824
- frozenLockfile: options.frozenLockfile,
825
- location: options.location,
826
- });
827
- });
828
- return command;
829
- }