CodeSampleX

샘플

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

검증된 샘플 — npm nanoid 5.1.16: Generate unique identifiers using default and custom alphabet generators in nanoid. node 22 · linux alpine/x64 · docker에서…

sha256:b5fdad3b3ce94574a1ab041974da7c554d5b134a183ef5884731f5fcd16564cf

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node linux 24 · ubuntu · glibc 2.39 x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Generate unique identifiers using default and custom alphabet generators in nanoid
패키지
심벌
  • customAlphabet
  • nanoid
  • urlAlphabet
환경
node
생성일
2026-08-27T16:39:59Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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');

오리진 시더

익명