fix(readme): Expand README with detailed usage examples, API reference and features; add local assistant settings

This commit is contained in:
2025-08-18 02:17:15 +00:00
parent c2a92197a2
commit 925f5c7097
3 changed files with 308 additions and 58 deletions

View File

@@ -1,5 +1,11 @@
# Changelog
## 2025-08-18 - 2.0.6 - fix(readme)
Expand README with detailed usage examples, API reference and features; add local assistant settings
- Expanded README.md: added badges, features list, installation instructions (including pnpm), quick start, detailed usage examples (package info, search, download, extraction, version management, virtual directory), caching info, API reference, and common use cases.
- Added .claude/settings.local.json to define local assistant permissions
## 2025-08-18 - 2.0.5 - fix(smartnpm)
Fix file extraction & streaming, types and caching; update deps and CI; skip flaky tests

344
readme.md
View File

@@ -1,93 +1,337 @@
# @push.rocks/smartnpm
interface with npm to retrieve package information
**Smart npm interface for Node.js 🚀**
## Install
To install `@push.rocks/smartnpm`, open your terminal and run the following command:
```sh
[![npm](https://img.shields.io/npm/v/@push.rocks/smartnpm.svg)](https://www.npmjs.com/package/@push.rocks/smartnpm)
[![TypeScript](https://img.shields.io/badge/TypeScript-4.x-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
> A powerful TypeScript library to programmatically interact with npm registries, retrieve package information, search packages, and handle package downloads with full caching support.
## 🎯 Features
- 📦 **Package Information Retrieval** - Get comprehensive metadata about any npm package
- 🔍 **Advanced Package Search** - Search npm registry with multiple filter options
- 💾 **Package Downloads** - Download and extract packages to disk programmatically
- 📁 **File Extraction** - Extract specific files or directories from packages without full download
- 🏷️ **Version & Tag Management** - Work with specific versions, dist-tags, and version ranges
-**Smart Caching** - Built-in caching system for improved performance
- 🌐 **Custom Registry Support** - Use with npm, Verdaccio, or any npm-compatible registry
- 🗂️ **Virtual Directory Creation** - Load packages as virtual file systems in memory
## 📥 Installation
```bash
npm install @push.rocks/smartnpm --save
```
This will add `@push.rocks/smartnpm` as a dependency to your project and you're ready to start using it.
## Usage
To use `@push.rocks/smartnpm` in your project, you first need to import it in your TypeScript files. `@push.rocks/smartnpm` provides a powerful interface to interact with npm to retrieve package information, handle package downloads, and more. Below are examples showcasing how to leverage some of its features in real-world scenarios.
Or using pnpm (recommended):
### Initialize the NpmRegistry
Before you can retrieve any package information or perform actions such as downloading packages, you need to create an instance of `NpmRegistry`. This acts as your starting point.
```bash
pnpm add @push.rocks/smartnpm
```
## 🚀 Quick Start
```typescript
import { NpmRegistry } from '@push.rocks/smartnpm';
// Initialize with default npm registry
const npmRegistry = new NpmRegistry();
// Or use a custom registry
const customRegistry = new NpmRegistry({
npmRegistryUrl: 'https://your-registry.example.com'
});
```
## 📘 Usage Examples
### Package Information Retrieval
Get detailed information about any npm package:
```typescript
import { NpmRegistry } from '@push.rocks/smartnpm';
const npmRegistry = new NpmRegistry();
```
Optionally, you can provide a custom npm registry URL if you're not using the default npm registry:
async function getPackageDetails() {
const packageInfo = await npmRegistry.getPackageInfo('@angular/core');
```typescript
const customRegistry = new NpmRegistry({
npmRegistryUrl: 'https://custom.registry.url'
console.log(`Package: ${packageInfo.name}`);
console.log(`Latest Version: ${packageInfo.version}`);
console.log(`Description: ${packageInfo.description}`);
console.log(`License: ${packageInfo.license}`);
// Access all versions
packageInfo.allVersions.forEach(version => {
console.log(`- ${version.version}: ${version.date}`);
});
```
### Retrieve Package Information
`@push.rocks/smartnpm` allows you to easily get detailed information about a package, including its versions, dist tags, and metadata. Here's how you can get information about a specific package:
```typescript
async function getPackageInfo() {
const packageName = 'your-package-name';
const packageInfo = await npmRegistry.getPackageInfo(packageName);
console.log(packageInfo);
// Access dist tags
packageInfo.allDistTags.forEach(tag => {
console.log(`Tag ${tag.name}: ${tag.targetVersion}`);
});
}
getPackageInfo();
```
### Search for Packages
You can search for packages using a variety of filters such as keywords, author, maintainer, etc. Here's an example of searching for packages with specific criteria:
### 🔍 Advanced Package Search
Search the npm registry with powerful filters:
```typescript
async function searchPackages() {
// Search with multiple criteria
const searchResults = await npmRegistry.searchOnNpm({
keywords: ['webpack-plugin'],
author: 'webpack'
name: 'webpack-plugin',
keywords: ['webpack', 'plugin', 'build'],
author: 'webpack-contrib',
maintainer: 'sokra',
scope: '@webpack',
deprecated: false,
unstable: false,
insecure: false,
boostExact: true,
scoreEffect: 15.3,
qualityWeight: 1.95,
popularityWeight: 3.3,
maintenanceWeight: 2.05
});
console.log(searchResults);
}
searchPackages();
console.log(`Found ${searchResults.length} packages`);
searchResults.forEach(pkg => {
console.log(`📦 ${pkg.name}@${pkg.version}`);
console.log(` Score: ${pkg.searchScore}`);
console.log(` Quality: ${pkg.score.detail.quality}`);
console.log(` Popularity: ${pkg.score.detail.popularity}`);
console.log(` Maintenance: ${pkg.score.detail.maintenance}`);
});
}
```
### Downloading Packages
`@push.rocks/smartnpm` provides an easy way to download npm packages and extract them to a specific directory. This could be useful for creating tools that need to programmatically handle packages.
### 💾 Download Packages
Download and extract npm packages to your filesystem:
```typescript
async function downloadPackage() {
const packageName = 'some-package';
const targetDirectory = './path/to/targetDir';
// Download latest version
await npmRegistry.savePackageToDisk('express', './downloads/express');
await npmRegistry.savePackageToDisk(packageName, targetDirectory);
console.log(`${packageName} has been downloaded to ${targetDirectory}`);
// Download specific version
const packageInfo = await npmRegistry.getPackageInfo('express');
const specificVersion = packageInfo.allVersions.find(v => v.version === '4.18.0');
if (specificVersion) {
await specificVersion.saveToDisk('./downloads/express-4.18.0');
}
}
downloadPackage();
```
### Working with Package Versions and Dist Tags
You can easily retrieve detailed information about specific package versions or distribution tags. This is particularly useful for automation scripts that need to work with specific versions of a package.
### 📁 Extract Specific Files
Extract individual files or directories from packages without downloading the entire package:
```typescript
async function getPackageVersionDetails() {
const packageName = 'some-package';
const version = '1.0.0'; // You can also use dist tags like 'latest'
async function extractSpecificFiles() {
// Get a single file
const readmeFile = await npmRegistry.getFileFromPackage(
'typescript',
'README.md'
);
const packageInfo = await npmRegistry.getPackageInfo(packageName);
const versionInfo = packageInfo.allVersions.find(v => v.version === version);
console.log(versionInfo);
if (readmeFile) {
console.log('README Contents:', readmeFile.contentBuffer.toString());
}
getPackageVersionDetails();
// Get a file from specific version
const packageJson = await npmRegistry.getFileFromPackage(
'react',
'package.json',
{ version: '18.0.0' }
);
// Get all files from a directory
const sourceFiles = await npmRegistry.getFilesFromPackage(
'@angular/core',
'src/',
{ distTag: 'latest' }
);
sourceFiles.forEach(file => {
console.log(`📄 ${file.path} (${file.contentBuffer.length} bytes)`);
});
}
```
These examples only scratch the surface of what you can achieve with `@push.rocks/smartnpm`. By integrating this library, you have a powerful tool at your disposal for interacting with npm in a programmatic way, enabling a wide range of possibilities for automation, CI/CD, and tooling around npm packages.
### 🏷️ Version Management
Work with specific versions and dist tags:
```typescript
async function versionManagement() {
const pkg = await npmRegistry.getPackageInfo('vue');
// Get best matching version for a range
const bestVersion = pkg.getBestMatchingVersion('^3.0.0');
console.log(`Best matching version: ${bestVersion}`);
// Work with dist tags
const latestTag = pkg.allDistTags.find(t => t.name === 'latest');
const nextTag = pkg.allDistTags.find(t => t.name === 'next');
console.log(`Latest: ${latestTag?.targetVersion}`);
console.log(`Next: ${nextTag?.targetVersion}`);
// Get files from specific dist tag
const files = await npmRegistry.getFilesFromPackage(
'vue',
'dist/',
{ distTag: 'next' }
);
}
```
### 🗂️ Virtual Directory
Load packages as virtual file systems in memory:
```typescript
async function virtualDirectory() {
// Create virtual directory from package
const virtualDir = await npmRegistry.getPackageAsSmartfileVirtualDir('@angular/cli');
// Work with files in memory
const allFiles = virtualDir.getFileArray();
allFiles.forEach(file => {
console.log(`Virtual file: ${file.path}`);
});
// Export virtual directory to disk if needed
await virtualDir.saveToDisk('./output/angular-cli');
}
```
### ⚡ Caching
The library includes built-in intelligent caching:
```typescript
// Files are automatically cached
const file1 = await npmRegistry.getFileFromPackage('lodash', 'package.json');
// This will be served from cache
const file2 = await npmRegistry.getFileFromPackage('lodash', 'package.json');
// Cache is registry-specific and version-aware
const specificVersion = await npmRegistry.getFileFromPackage(
'lodash',
'README.md',
{ version: '4.17.21' }
);
```
## 🏗️ API Reference
### NpmRegistry Class
#### Constructor
```typescript
new NpmRegistry(options?: INpmRegistryConstructorOptions)
```
Options:
- `npmRegistryUrl`: Custom registry URL (default: `https://registry.npmjs.org`)
#### Methods
##### `getPackageInfo(packageName: string): Promise<NpmPackage>`
Retrieves comprehensive information about a package.
##### `searchOnNpm(searchObject: ISearchObject): Promise<NpmPackage[]>`
Searches the npm registry with advanced filters.
##### `savePackageToDisk(packageName: string, targetDir: string): Promise<void>`
Downloads and extracts a package to the filesystem.
##### `getFileFromPackage(packageName: string, filePath: string, options?): Promise<SmartFile>`
Extracts a single file from a package.
##### `getFilesFromPackage(packageName: string, filePath: string, options?): Promise<SmartFile[]>`
Extracts multiple files from a package directory.
##### `getPackageAsSmartfileVirtualDir(packageName: string): Promise<VirtualDirectory>`
Creates an in-memory virtual directory from a package.
### NpmPackage Class
#### Properties
- `name`: Package name
- `version`: Current version
- `description`: Package description
- `license`: License type
- `allVersions`: Array of all available versions
- `allDistTags`: Array of all dist tags
- `dependencies`: Package dependencies
- `keywords`: Package keywords
- `maintainers`: Package maintainers
- `dist`: Distribution information
#### Methods
##### `getBestMatchingVersion(versionRange: string): string`
Finds the best matching version for a semver range.
##### `saveToDisk(targetDir: string): Promise<void>`
Saves the package to disk.
##### `getFileFromPackage(filePath: string, options?): Promise<SmartFile>`
Gets a file from the package.
##### `getFilesFromPackage(filePath: string, options?): Promise<SmartFile[]>`
Gets multiple files from the package.
## 🔧 Advanced Configuration
### Custom Registry with Authentication
```typescript
const privateRegistry = new NpmRegistry({
npmRegistryUrl: 'https://private-registry.company.com'
});
// Note: Authentication should be configured via .npmrc or npm config
```
### Error Handling
```typescript
try {
const pkg = await npmRegistry.getPackageInfo('non-existent-package');
} catch (error) {
console.error('Package not found:', error.message);
}
// Safe file extraction
const file = await npmRegistry.getFileFromPackage('express', 'README.md');
if (file) {
// File exists
console.log('File size:', file.contentBuffer.length);
} else {
// File doesn't exist
console.log('File not found');
}
```
## 🎯 Common Use Cases
- **CI/CD Pipelines**: Automatically download and verify package contents
- **Security Scanning**: Extract and analyze package files without installation
- **Documentation Generation**: Pull README files and docs from packages
- **Dependency Analysis**: Analyze package structures and dependencies
- **Registry Mirroring**: Sync packages between registries
- **Package Validation**: Verify package contents before deployment
- **Automated Updates**: Check for new versions and update notifications
## License and Legal Information

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartnpm',
version: '2.0.5',
version: '2.0.6',
description: 'A library to interface with npm for retrieving package information and manipulation.'
}