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

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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');

オリジンシーダー

匿名