npm package: @houssem__/mf-shared-lib
Description: Shared utilities and components for microfrontend applications
Author: DevOps Team
Latest version: 1.0.0

# mf-shared-lib

Shared utilities and components for microfrontend applications.

## 📦 Installation

```bash
npm install @your-scope/mf-shared-lib
```

## 🚀 Usage

```typescript
import { formatDate, debounce, generateId, isEmpty } from '@your-scope/mf-shared-lib';
import { API_TIMEOUT, HTTP_STATUS } from '@your-scope/mf-shared-lib';

// Format a date
const formatted = formatDate(new Date(), 'en-US');

// Debounce a function
const debouncedFn = debounce(() => {
  console.log('Called after 300ms');
}, 300);

// Generate unique ID
const id = generateId();

// Check if value is empty
if (isEmpty(value)) {
  console.log('Value is empty');
}

// Use constants
fetch('/api/data', {
  timeout: API_TIMEOUT,
});
```

## 📚 API Reference

### Utilities

#### `formatDate(date: Date, locale?: string): string`
Format a date to a localized string.

#### `debounce<T>(func: T, wait: number): Function`
Debounce a function call.

#### `deepClone<T>(obj: T): T`
Deep clone an object.

#### `generateId(): string`
Generate a unique ID.

#### `isEmpty(value: any): boolean`
Check if a value is empty.

### Constants

#### `API_TIMEOUT`
Default API timeout (30000ms).

#### `MAX_RETRY_ATTEMPTS`
Maximum retry attempts (3).

#### `DEFAULT_PAGE_SIZE`
Default pagination size (20).

#### `HTTP_STATUS`
HTTP status code constants.

#### `STORAGE_KEYS`
Local storage key constants.

## 🔧 Development

### Build
```bash
npm run build
```

### Test
```bash
npm test
```

### Lint
```bash
npm run lint
```

## 📝 Publishing

This library is automatically published via GitLab CI/CD:

- **develop** → Dry-run publish (test only)
- **release/x.x.x** → Publish to NPM
- **main** → Publish to NPM

## 🤝 Contributing

1. Create a feature branch from `develop`
2. Make your changes
3. Create a merge request
4. Wait for CI/CD pipeline to pass
5. Get approval and merge

## 📄 License

MIT

# NPM Library Publishing Guide

This guide explains how to publish NPM libraries using the GitLab CI/CD pipeline.

## 📚 Library Projects

The following projects are configured as libraries:
- `mf-shared-lib` - Shared utilities and components
- `mf-product-lib` - Product-related functionality
- `mf-auth-lib` - Authentication and authorization

## 🔧 Setup Requirements

### 1. NPM Token Configuration

**Option A: Public NPM Registry (npmjs.com)**
1. Go to npmjs.com → Account Settings → Access Tokens
2. Generate a new token (Automation type)
3. Add to GitLab: **Settings → CI/CD → Variables**
   - Key: `NPM_TOKEN`
   - Value: `your-npm-token`
   - Masked: ✅ Yes
   - Protected: ✅ Yes (optional)

**Option B: Private Registry (Artifactory/Nexus)**
1. Get authentication token from your registry admin
2. Add to GitLab Variables:
   - Key: `NPM_TOKEN`
   - Value: `your-registry-token`
3. Update `.npmrc` in your project if needed

**Option C: GitLab Package Registry**
- No token needed! Uses `CI_JOB_TOKEN` automatically
- Set `ENABLE_GITLAB_PACKAGE_REGISTRY: "true"`

### 2. Package.json Configuration

Ensure your library's `package.json` has:

```json
{
  "name": "@your-scope/mf-shared-lib",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": [
    "dist"
  ],
  "publishConfig": {
    "access": "restricted"
  },
  "scripts": {
    "build": "tsc",
    "prepublishOnly": "npm run build"
  }
}
```

### 3. Project .gitlab-ci.yml

```yaml
include:
  - project: 'houssem-amara/gitlab-ci-common'
    ref: main
    file: '/templates/common.yml'

variables:
  PROJECT_NAME: "mf-shared-lib"
  PROJECT_TYPE: "library"  # Critical: Set to "library"
  NPM_ACCESS: "restricted"  # or "public"
  ENABLE_SONAR: "true"
  ENABLE_TEAMS_NOTIFICATIONS: "true"
```

## 🚀 Publishing Workflow

### Automatic Publishing

The pipeline automatically publishes libraries on:

1. **Main Branch** → Publishes to NPM
   ```bash
   git checkout main
   git merge develop
   git push origin main
   # Pipeline runs → npm publish
   ```

2. **Release Branches** → Publishes to NPM
   ```bash
   git checkout -b release/1.2.0
   # Make version changes
   git push origin release/1.2.0
   # Pipeline runs → npm publish
   ```

3. **Develop Branch** → Dry-run only (testing)
   ```bash
   git checkout develop
   git push origin develop
   # Pipeline runs → npm publish --dry-run
   ```

### Pipeline Stages for Libraries

```
┌─────────────┐
│ Versioning  │ - Set version from branch/tag
└──────┬──────┘
       │
┌──────▼──────┐
│   Check     │ - Install, Lint, Test
└──────┬──────┘
       │
┌──────▼──────┐
│   Build     │ - Build library (npm run build)
└──────┬──────┘
       │
┌──────▼──────┐
│  Security   │ - SonarQube (if enabled)
│             │ - Checkmarx (if enabled)
└──────┬──────┘
       │
┌──────▼──────┐
│  Publish    │ - npm publish (main/release)
│             │ - npm publish --dry-run (develop)
│             │ - GitLab Package Registry (if enabled)
└─────────────┘
```

## 📦 Consuming Published Libraries

### From NPM Registry

```bash
# Install the library
npm install @your-scope/mf-shared-lib@1.0.0

# In your code
import { SomeUtility } from '@your-scope/mf-shared-lib';
```

### From GitLab Package Registry

1. Create `.npmrc` in your project:
```
@your-group:registry=https://gitlab.example.com/api/v4/packages/npm/
//gitlab.example.com/api/v4/packages/npm/:_authToken=${CI_JOB_TOKEN}
```

2. Install:
```bash
npm install @your-group/mf-shared-lib@1.0.0
```

## 🔄 Versioning Strategy

### Semantic Versioning (SemVer)

- **MAJOR** (1.0.0 → 2.0.0): Breaking changes
- **MINOR** (1.0.0 → 1.1.0): New features, backward compatible
- **PATCH** (1.0.0 → 1.0.1): Bug fixes

### Branch-based Versioning

The pipeline automatically sets versions based on:

```bash
develop      → 1.0.0-dev.123
release/1.2  → 1.2.0-rc.1
main         → 1.2.0
hotfix/1.2.1 → 1.2.1
```

## 🎯 Per-Project Feature Flags

Each library can enable different features:

### mf-shared-lib
```yaml
variables:
  ENABLE_SONAR: "true"       # Code quality scanning
  ENABLE_CHECKMARX: "false"  # Security scanning
  ENABLE_LIGHTHOUSE: "false" # Performance (N/A for libraries)
```

### mf-auth-lib (Security-critical)
```yaml
variables:
  ENABLE_SONAR: "true"
  ENABLE_CHECKMARX: "true"   # Enable for security libraries!
  ENABLE_LIGHTHOUSE: "false"
```

### rexel-ds (Design System)
```yaml
variables:
  PROJECT_TYPE: "design-system"
  ENABLE_SONAR: "false"
  ENABLE_LIGHTHOUSE: "true"  # Test component performance
```

## 🛠️ Troubleshooting

### Publishing Fails

**Issue:** `npm ERR! 403 Forbidden`
- Check NPM_TOKEN is set correctly in GitLab Variables
- Verify token has publish permissions
- Check package name isn't already taken

**Issue:** `npm ERR! need auth`
- Ensure NPM_TOKEN variable is not expired
- Check `.npmrc` is created correctly in before_script

**Issue:** `dist folder not found`
- Verify build script in package.json
- Check build artifacts are created
- Ensure `files` field in package.json includes dist

### Version Conflicts

**Issue:** `npm ERR! version already exists`
- Version is already published to NPM
- Either bump version or use `--force` (not recommended)
- Check your versioning script

### GitLab Package Registry Issues

**Issue:** Can't install from GitLab
- Verify `ENABLE_GITLAB_PACKAGE_REGISTRY: "true"`
- Check authentication in consuming project's `.npmrc`
- Ensure CI_JOB_TOKEN has package read permissions

## 📊 Monitoring

### Check Published Versions

**NPM Registry:**
```bash
npm view @your-scope/mf-shared-lib versions
```

**GitLab Package Registry:**
1. Go to Project → Packages & Registries → Package Registry
2. View all published versions

### Pipeline Status

Monitor in GitLab:
1. Go to CI/CD → Pipelines
2. Check `npm-publish-library` job
3. View logs for publish confirmation

## 🔐 Security Best Practices

1. **Use Scoped Packages**: `@your-company/package-name`
2. **Restrict Access**: Set `NPM_ACCESS: "restricted"`
3. **Enable Checkmarx**: For security-sensitive libraries
4. **Use Protected Branches**: Only allow publishing from main/release
5. **Rotate Tokens**: Update NPM_TOKEN regularly
6. **Review Dependencies**: Run `npm audit` regularly

## 📝 Example: Publishing New Version

```bash
# 1. Create feature branch
git checkout develop
git checkout -b feature/new-utility

# 2. Make changes and test
npm run build
npm test

# 3. Merge to develop
git checkout develop
git merge feature/new-utility
git push origin develop
# → Pipeline runs dry-run publish

# 4. Create release branch
git checkout -b release/1.1.0
# Update CHANGELOG.md
git push origin release/1.1.0
# → Pipeline publishes to NPM

# 5. Merge to main
git checkout main
git merge release/1.1.0
git push origin main
# → Creates git tag, publishes final version
```

## 🆚 Library vs Application Projects

| Feature | Library | Application |
|---------|---------|-------------|
| PROJECT_TYPE | `library` | `application` |
| Build Output | dist/ | dist/app-name/browser |
| Publishing | NPM Registry | Docker Registry |
| Deployment | N/A | Kubernetes via Helm |
| Versioning | SemVer | SemVer + Git Tags |
| Consumers | Other projects | End users |

## 📞 Support

For issues with library publishing:
1. Check pipeline logs in GitLab
2. Verify NPM_TOKEN configuration
3. Review package.json configuration
4. Check the BAMBOO-VS-GITLAB-COMPARISON.md document