npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@arcpkg/id-generator

v0.0.1-beta.0.1

Published

ID-GENERATOR est une bibliothèque TypeScript robuste pour générer des identifiants uniques avec des formats personnalisables. Elle offre une syntaxe expressive pour créer des identifiants complexes combinant texte, chaînes aléatoires, UUID et fonctions pe

Readme

@arcpkg/id-generator

License TypeScript Browser Node.js

@arcpkg/id-generator est une bibliothèque TypeScript robuste pour générer des identifiants uniques avec des formats personnalisables. Elle offre une syntaxe expressive pour créer des identifiants complexes combinant texte, chaînes aléatoires, UUID et fonctions personnalisées.

✨ Fonctionnalités Principales

🔤 Formats de Génération Flexibles

  • Syntaxe intuitive : Utilisez des templates avec tokens spéciaux
  • Combinaisons multiples : Mélangez texte, random, UUID et handlers personnalisés
  • Cache intelligent : Génération optimisée avec cache pour les patterns non-variants

🎲 Types de Génération Supportés

  • Chaînes aléatoires : Numeric, alphabetic, alphanumeric (avec/sans casse)
  • UUID : Versions v1 à v5 avec implémentations standards
  • Handlers personnalisés : Intégrez vos propres fonctions de génération
  • Handlers intégrés : Timestamp, date, time, compteur, variables d'environnement

⚡ Performance & Sécurité

  • Générateur cryptographique : Utilise crypto.getRandomValues pour la sécurité
  • Singleton pattern : Instance unique optimisée
  • Gestion de cache : Réduction des calculs redondants
  • Validation stricte : Erreurs détaillées pour formats invalides

📦 Installation

Via npm/yarn/pnpm

npm install @arcpkg/id-generator
# ou
yarn add @arcpkg/id-generator
# ou
pnpm add @arcpkg/id-generator

Importation directe (CDN)

<script src="@arcpkg/id-generator/id-generator.all.js"></script>

🚀 Démarrage Rapide

TypeScript/ES Modules

import { IdentifierGenerator, IdentifierGeneratorHandlers } from '@arcpkg/id-generator';
// ou
import IdGenerator from '@arcpkg/id-generator';

CommonJS

const { IdentifierGenerator, IdentifierGeneratorHandlers } = require('@arcpkg/id-generator');

Navigateur (global)

<script src="@arcpkg/id-generator/id-generator.all.js"></script>
<script>
  // Disponible globalement
  const generator = IdentifierGenerator.getInstance();
  const id = generator.generate('prefix-#rand{size:8,type:alphanumeric}');
</script>

📚 Syntaxe des Formats

Structure de Base

texte_littéral#token{options}texte_suivant
  • texte_littéral : Texte statique inclus tel quel
  • # : Délimiteur de token spécial
  • token : Type de token (rand, uuid, custom)
  • {options} : Options spécifiques au token (optionnel)

Tokens Disponibles

| Token | Description | Options | |-------|-------------|---------| | #rand{...} | Chaîne aléatoire | size, type, variant | | #uuid{...} | UUID | version | | #custom{...} | Handler personnalisé | Nom du handler | | Texte seul | Texte statique | Aucune |

Options des Tokens

Options pour #rand

{
  size: number,          // Longueur de la chaîne (défaut: 8)
  type: RandomType,      // 'numeric' | 'alphabetic' | 'alphabetic-case' | 'alphanumeric' | 'alphanumeric-case'
  variant: boolean       // Si true, génère à chaque fois (défaut: false)
}

Options pour #uuid

{
  version: UUIDVersion   // 'v1' | 'v2' | 'v3' | 'v4' | 'v5' (défaut: 'v4')
}

Options pour #custom

{
  handlerName: string    // Nom du handler personnalisé
}

🔧 Utilisation Détaillée

Instance Singleton

// Méthode recommandée : singleton
const generator = IdentifierGenerator.getInstance();

// Méthode statique (plus concise)
const id = IdentifierGenerator.generateId('format');

Exemples Complets

Exemple 1 : ID avec Random et UUID

const generator = IdentifierGenerator.getInstance();

const id1 = generator.generate(
  'mda-#rand{size:10,type:alphanumeric}-#uuid{version:v1}',
  {
    customTimestamp: () => Date.now().toString()
  }
);
// Résultat: "mda-a3b8c9d2e1-6ba7b810-9dad-11d1-80b4-00c04fd430c8"

Exemple 2 : Random avec variant

const id2 = generator.generate(
  'lorem-#rand{type:alphanumeric,variant:true}-ipsum',
  {
    user: () => 'john_doe'
  }
);
// Résultat: "lorem-a1b2c3d4-ipsum" (change à chaque appel)

Exemple 3 : Handler personnalisé

const id3 = generator.generate(
  'user-#custom{userId}-#rand{size:6,type:numeric}',
  {
    userId: () => 'USR_' + Math.random().toString(36).substr(2, 9)
  }
);
// Résultat: "user-USR_abc123def-123456"

Exemple 4 : Utilisation des handlers intégrés

const id4 = IdentifierGenerator.generateId(
  'order-#custom{timestamp}-#rand{size:8,type:alphanumeric-case}',
  {
    timestamp: IdentifierGeneratorHandlers.timestamp
  }
);
// Résultat: "order-1641234567890-A1b2C3d4"

Handlers Intégrés

// Disponibles dans IdentifierGeneratorHandlers
{
  timestamp: () => Date.now().toString(),
  date: () => new Date().toISOString().slice(0, 10).replace(/-/g, ''),
  time: () => new Date().toISOString().slice(11, 19).replace(/:/g, ''),
  counter: () => { /* compteur auto-incrémenté */ },
  env: (envVar: string) => process.env[envVar] || ''
}

🎯 Cas d'Utilisation Avancés

Génération d'ID Transactionnels

function generateTransactionId(prefix: string): string {
  return IdentifierGenerator.generateId(
    `\${prefix}-#custom{date}-#custom{time}-#rand{size:12,type:numeric}`,
    {
      date: IdentifierGeneratorHandlers.date,
      time: IdentifierGeneratorHandlers.time
    }
  );
}
// Résultat: "TXN-20231225-143025-123456789012"

Génération d'ID Utilisateur

class UserService {
  private counter = 0;
  
  generateUserId(username: string): string {
    return IdentifierGenerator.getInstance().generate(
      'USR-#custom{prefix}-#custom{seq}-#rand{size:4,type:alphanumeric}',
      {
        prefix: () => username.substring(0, 3).toUpperCase(),
        seq: () => (++this.counter).toString().padStart(6, '0')
      }
    );
  }
}
// Résultat: "USR-JOH-000001-A1B2"

Génération d'ID de Session

function generateSessionId(): string {
  return IdentifierGenerator.generateId(
    'SESS-#uuid{version:v4}-#custom{timestamp}',
    {
      timestamp: () => Date.now().toString(36)
    }
  );
}
// Résultat: "SESS-550e8400-e29b-41d4-a716-446655440000-kyz9w8"

⚙️ Configuration Avancée

Gestion du Cache

const generator = IdentifierGenerator.getInstance();

// Générer avec cache (par défaut pour les non-variants)
const cachedId = generator.generate('id-#rand{size:8,type:alphanumeric,variant:false}');
// Même valeur à chaque appel pour la même session

// Vider le cache
generator.clearCache();

// Forcer une nouvelle génération
const freshId = generator.generate('id-#rand{size:8,type:alphanumeric,variant:true}');

Handlers Personnalisés Complexes

// Handler avec paramètres
const configurableHandler = (prefix: string, length: number) => 
  () => prefix + Math.random().toString(36).substr(2, length);

// Handler asynchrone (à wrapper)
const asyncHandler = async () => {
  const response = await fetch('/api/id-source');
  return response.text();
};

const generator = IdentifierGenerator.getInstance();
const id = generator.generate(
  'item-#custom{dynamicId}',
  {
    dynamicId: () => configurableHandler('ITM_', 8)()
  }
);

Extension des Types

// Ajouter de nouveaux types de random
interface ExtendedRandomOptions extends RandomOptions {
  exclude?: string; // Caractères à exclure
}

// Créer un générateur étendu
class ExtendedIdentifierGenerator extends IdentifierGenerator {
  protected generateRandomString(options: ExtendedRandomOptions): string {
    if (options.exclude) {
      // Implémentation personnalisée
    }
    return super.generateRandomString(options);
  }
}

📊 Table des Types de Random

| Type | Caractères Inclus | Exemple | |------|------------------|---------| | numeric | 0-9 | "12345678" | | alphabetic | a-z (minuscules) | "abcdefgh" | | alphabetic-case | a-z, A-Z | "AbCdEfGh" | | alphanumeric | a-z, 0-9 | "a1b2c3d4" | | alphanumeric-case | a-z, A-Z, 0-9 | "A1b2C3d4" |

🛡️ Gestion des Erreurs

Erreurs de Format

try {
  generator.generate('invalid-#unknown{type:invalid}');
} catch (error) {
  console.error('Erreur de format:', error.message);
  // "Type de token non supporté: unknown"
}

Erreurs de Handler

try {
  generator.generate('#custom{missingHandler}', {});
} catch (error) {
  console.error('Handler manquant:', error.message);
  // "Handler personnalisé non trouvé: missingHandler"
}

Validation des Options

// Taille négative
generator.generate('#rand{size:-5}'); // Lance une erreur

// Type invalide
generator.generate('#rand{type:invalid}'); // Utilise la valeur par défaut

🔧 Intégration

Avec React

import React, { useMemo } from 'react';
import { IdentifierGenerator } from '@arcpkg/id-generator';

const ProductCard: React.FC<{ product: Product }> = ({ product }) => {
  const uniqueId = useMemo(() => 
    IdentifierGenerator.generateId(
      'product-#custom{id}-#rand{size:4,type:alphanumeric}',
      { id: () => product.id }
    ), [product.id]);
    
  return (
    <div id={uniqueId}>
      {/* Contenu */}
    </div>
  );
};

Avec Node.js

import { IdentifierGenerator, IdentifierGeneratorHandlers } from '@arcpkg/id-generator';

// Configuration pour Node.js
if (typeof window === 'undefined') {
  // Polyfill pour crypto si nécessaire
  global.crypto = require('crypto');
}

export function generateRequestId(): string {
  return IdentifierGenerator.generateId(
    'req-#custom{timestamp}-#rand{size:16,type:alphanumeric-case}',
    {
      timestamp: IdentifierGeneratorHandlers.timestamp
    }
  );
}

Avec Vue.js

<template>
  <div :id="uniqueId">
    <!-- Contenu -->
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { IdentifierGenerator } from '@arcpkg/id-generator';

const props = defineProps(['item']);

const uniqueId = computed(() => 
  IdentifierGenerator.generateId(
    'item-#custom{itemId}',
    { itemId: () => props.item.id }
  )
);
</script>

📋 Table des Performances

| Opération | Temps moyen | Mémoire | |-----------|-------------|---------| | Génération simple (#rand) | < 1ms | ~100KB | | Génération UUID (#uuid v4) | < 2ms | ~100KB | | Format complexe (5 tokens) | < 5ms | ~150KB | | Cache hit | < 0.1ms | N/A |

🚨 Meilleures Pratiques

1. Réutiliser les Instances

// MAUVAIS : nouvelle instance à chaque fois
const id1 = new IdentifierGenerator().generate(...);

// BON : singleton
const generator = IdentifierGenerator.getInstance();
const id2 = generator.generate(...);
const id3 = generator.generate(...);

2. Utiliser le Cache Appropriément

// Pour les IDs uniques par session
generator.generate('session-#rand{variant:true}');

// Pour les IDs constants
generator.generate('constant-#rand{variant:false}');

3. Valider les Formats

function isValidFormat(format: string): boolean {
  try {
    IdentifierGenerator.generateId(format, {});
    return true;
  } catch {
    return false;
  }
}

4. Sécuriser la Génération

// Utiliser crypto pour les IDs sensibles
const secureId = generator.generate(
  '#rand{size:32,type:alphanumeric-case,variant:true}'
);

🔗 API Complète

Classe IdentifierGenerator

Méthodes Statiques

  • getInstance(): IdentifierGenerator - Retourne l'instance singleton
  • generateId(format: string, customHandlers?: Record<string, CustomHandler>): string - Génère un ID directement
  • exposeToGlobal(): void - Expose à l'objet global (navigateur)

Méthodes d'Instance

  • generate(format: string, customHandlers?: Record<string, CustomHandler>): string - Génère un ID
  • clearCache(): void - Vide le cache interne

Objet IdentifierGeneratorHandlers

Handlers prédéfinis pour les cas courants :

  • timestamp(): string
  • date(): string
  • time(): string
  • counter(): string
  • env(envVar: string): string

Types Exportés

export type RandomType = 'numeric' | 'alphabetic' | 'alphabetic-case' | 'alphanumeric' | 'alphanumeric-case';
export type UUIDVersion = 'v1' | 'v2' | 'v3' | 'v4' | 'v5';
export type CustomHandler = () => string;

export interface RandomOptions {
  size: number;
  type: RandomType;
  variant: boolean;
}

export interface UUIDOptions {
  version: UUIDVersion;
}

export interface TokenDefinition {
  type: 'string' | 'random' | 'uuid' | 'custom';
  value: string | RandomOptions | UUIDOptions | CustomHandler;
}

🔧 Build et Développement

Structure du Projet

@arcpkg/id-generator/
├── id-generator.all.js
├── id-generator.all.min.js
├── index.d.ts
├── index.js
├── index.min.d.ts
├── index.min.js
├── package.json
├── tsconfig.json
└── README.md

📄 Licence

MIT License - Voir le fichier LICENSE pour plus de détails.

🐛 Signaler un Bug

Envoyez nous un mail à l'adresse [email protected] pour :

  • Signaler un bug
  • Proposer une amélioration
  • Poser une question

@arcpkg/id-generator - Générez des identifiants uniques avec élégance et puissance.

Développé par l'équipe INICODE