CodeSampleX

Ejemplo

nanoid 5.1.16: Generate unique identifiers using default and custom alphabet generators in nanoid

Muestra verificada para npm nanoid 5.1.16: Generate unique identifiers using default and custom alphabet generators in nanoid. El contrato se ejecutó en node…

sha256:b5fdad3b3ce94574a1ab041974da7c554d5b134a183ef5884731f5fcd16564cf

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node linux 24 · ubuntu · glibc 2.39 x64 node node npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Caso

HOW
Objetivo
Generate unique identifiers using default and custom alphabet generators in nanoid
Paquetes
Símbolos
  • customAlphabet
  • nanoid
  • urlAlphabet
Entorno
node
Creado
2026-08-27T16:39:59Z

Contrato

  1. nanoid generates 21-character URL-safe identifiers by default
  2. assert nanoid respects custom length parameter and returns empty string for size 0
  3. assert nanoid throws RangeError with 'Wrong ID size' on negative sizes
  4. assert customAlphabet produces identifiers restricted to the specified character set
  5. assert customAlphabet generator respects default size and runtime size overrides
  6. assert urlAlphabet contains 64 URL-safe characters
  7. assert sequentially generated identifiers are unique

Archivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • test/contract.mjs

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# nanoid default and customAlphabet Identifier Generation

## Known Solution Search
`search_known_solution` returned existing samples for nanoid 6.x (`sha256:eff79c2db63da8136f9734d8f9e74d3b23b4c2a786312f76e63d54bb09e7fb52`, `sha256:e8d4dcdd4cc51c25ef07e9fc78c54cdb1bf4b593d8b7d49f0ca8d5ea7c0a130c`, `sha256:33fa894d2e8aaa8166a9bf954a74dc0f162cef7ee04cb938033b25c057f076c8`), but no exact sample for `nanoid@5.1.16`. This clean-room sample verifies core `nanoid`, `customAlphabet`, and `urlAlphabet` behaviors on `nanoid@5.1.16`.

## Pinned Release
- Package: `nanoid`
- Version: `5.1.16`

## Observed Behavior
1. `nanoid(size = 21)` generates cryptographic URL-safe string identifiers defaulting to 21 characters using the internal `urlAlphabet`.
2. Calling `nanoid(size)` with custom lengths generates strings of the exact requested length. Size 0 evaluates to `""`.
3. Calling `nanoid(size)` with a negative size throws `RangeError` with the message `'Wrong ID size'`.
4. `customAlphabet(alphabet, defaultSize = 21)` returns a generator function `(size = defaultSize) => string` restricted to the specified character set.
5. Generator functions from `customAlphabet` respect `defaultSize` when called with no arguments, allow overriding the length dynamically per invocation, and return `""` when size is 0.
6. `urlAlphabet` exports the standard 64-character URL-safe string (`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`).
7. 1000 sequentially generated identifiers show zero collision.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Generate unique identifiers using default and custom alphabet generators in nanoid
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/nanoid@5.1.16
Demonstrate these symbols/APIs:
  - customAlphabet
  - nanoid
  - urlAlphabet

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:e2ed180922cffc0926bf5928dec43bd8873dacc4fc87ff7a749f4a56a223f6be","contract":["nanoid generates 21-character URL-safe identifiers by default","assert nanoid respects custom length parameter and returns empty string for size 0","assert nanoid throws RangeError with 'Wrong ID size' on negative sizes","assert customAlphabet produces identifiers restricted to the specified character set","assert customAlphabet generator respects default size and runtime size overrides","assert urlAlphabet contains 64 URL-safe characters","assert sequentially generated identifiers are unique"],"goal":"Generate unique identifiers using default and custom alphabet generators in nanoid","kind":"HOW","packages":["pkg:npm/nanoid@5.1.16"],"schemaVersion":1,"symbols":["customAlphabet","nanoid","urlAlphabet"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"node","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/nanoid@5.1.16"],"schemaVersion":1,"subject":"pkg:npm/nanoid@5.1.16","symbols":["customAlphabet","nanoid","urlAlphabet"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "nanoid-default-custom-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "nanoid-default-custom-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "nanoid": "5.1.16"
      }
    },
    "node_modules/nanoid": {
      "version": "5.1.16",
      "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",
      "integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "bin": {
        "nanoid": "bin/nanoid.js"
      },
      "engines": {
        "node": "^18 || >=20"
      }
    }
  }
}
package.json
{
  "name": "nanoid-default-custom-sample",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "nanoid": "5.1.16"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Generate unique identifiers using default and custom alphabet generators in nanoid",
  "kind": "HOW",
  "packages": [
    "pkg:npm/nanoid@5.1.16"
  ],
  "symbols": [
    "customAlphabet",
    "nanoid",
    "urlAlphabet"
  ]
}
src/index.mjs
import { nanoid, customAlphabet, urlAlphabet } from 'nanoid';

/**
 * Generates a default URL-safe unique identifier.
 *
 * @param {number} [size=21] - ID length (defaults to 21).
 * @returns {string}
 */
export function generateId(size = 21) {
  return nanoid(size);
}

/**
 * Creates a generator function that produces IDs with a custom alphabet.
 *
 * @param {string} alphabet - Allowed characters in the ID.
 * @param {number} [defaultSize=21] - Default length of generated IDs.
 * @returns {(size?: number) => string}
 */
export function createCustomGenerator(alphabet, defaultSize = 21) {
  return customAlphabet(alphabet, defaultSize);
}

export { nanoid, customAlphabet, urlAlphabet };
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  generateId,
  createCustomGenerator,
  nanoid,
  customAlphabet,
  urlAlphabet
} from '../src/index.mjs';

// 1. Assert nanoid generates 21-character URL-safe identifier by default
const defaultId = generateId();
assert.equal(typeof defaultId, 'string');
assert.equal(defaultId.length, 21);
assert.match(defaultId, /^[A-Za-z0-9_-]{21}$/);

// 2. Assert nanoid respects explicit size parameter and returns empty string for size 0
const customLengthId = generateId(12);
assert.equal(customLengthId.length, 12);
assert.match(customLengthId, /^[A-Za-z0-9_-]{12}$/);
assert.equal(nanoid(0), '');

// 3. Assert negative size throws RangeError with 'Wrong ID size'
assert.throws(
  () => nanoid(-1),
  {
    name: 'RangeError',
    message: 'Wrong ID size'
  }
);

// 4. Assert customAlphabet produces IDs restricted to custom character set
const hexGen = createCustomGenerator('0123456789abcdef', 16);
const hexId = hexGen();
assert.equal(hexId.length, 16);
assert.match(hexId, /^[0-9a-f]{16}$/);

// 5. Assert customAlphabet generator respects default size and runtime size overrides
const shortHexId = hexGen(8);
assert.equal(shortHexId.length, 8);
assert.match(shortHexId, /^[0-9a-f]{8}$/);
assert.equal(hexGen(0), '');

// 6. Assert urlAlphabet is a 64-character URL-safe alphabet string
assert.equal(typeof urlAlphabet, 'string');
assert.equal(urlAlphabet.length, 64);
assert.equal(new Set(urlAlphabet).size, 64);
assert.match(urlAlphabet, /^[A-Za-z0-9_-]{64}$/);

// 7. Assert 1000 sequentially generated IDs are unique
const seen = new Set();
for (let i = 0; i < 1000; i++) {
  seen.add(generateId());
}
assert.equal(seen.size, 1000);

console.log('CONTRACT PASS: nanoid default and custom alphabet generator behaviors verified');

Seeder de origen

anónimo