CodeSampleX

Пример

nanoid 5.1.16: urlAlphabet

Проверенный пример — npm nanoid 5.1.16: urlAlphabet. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: urlAlphabet is an exported…

sha256:ae5b17892d50a6ef5c6ae48844fb968e72c2bafa0a62a6fe367d4eb24b87715f

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

Кейс

HOW
Цель
verify nanoid.urlAlphabet in pkg:npm/nanoid@5.1.16
Пакеты
Символы
  • nanoid.urlAlphabet
Окружение
node 22.23.2
Создан
2026-09-06T19:12:42Z

Контракт

  1. urlAlphabet is an exported 64-character string containing URL-safe characters
  2. urlAlphabet contains 64 unique characters with numbers, lowercase letters, uppercase letters, hyphen, and underscore
  3. urlAlphabet characters all conform to URL-safe ASCII character set
  4. urlAlphabet is exported from the root nanoid package as an ESM named export
  5. urlAlphabet can be used with customAlphabet to generate URL-safe identifiers

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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: verify nanoid.urlAlphabet in pkg:npm/nanoid@5.1.16
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/nanoid@5.1.16
Demonstrate these symbols/APIs:
  - 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:e35ecb1826688c99ed16e6e31b785050d0b0752eb1c5d2ba5fb672779580de77","contract":["urlAlphabet is an exported 64-character string containing URL-safe characters","urlAlphabet contains 64 unique characters with numbers, lowercase letters, uppercase letters, hyphen, and underscore","urlAlphabet characters all conform to URL-safe ASCII character set","urlAlphabet is exported from the root nanoid package as an ESM named export","urlAlphabet can be used with customAlphabet to generate URL-safe identifiers"],"goal":"verify nanoid.urlAlphabet in pkg:npm/nanoid@5.1.16","kind":"HOW","packages":["pkg:npm/nanoid@5.1.16"],"schemaVersion":1,"symbols":["nanoid.urlAlphabet"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/nanoid@5.1.16"],"schemaVersion":1,"subject":"pkg:npm/nanoid@5.1.16","symbols":["nanoid.urlAlphabet"],"verifierAdapter":"node-typescript@1"}
index.js
import { urlAlphabet } from 'nanoid';

/**
 * Returns the default URL-safe alphabet string used by Nano ID.
 * @returns {string} The 64-character URL-safe alphabet.
 */
export function getUrlAlphabet() {
  return urlAlphabet;
}

/**
 * Validates whether all characters in a given string belong to nanoid.urlAlphabet.
 * @param {string} str - String to validate.
 * @returns {boolean} True if all characters are in urlAlphabet, false otherwise.
 */
export function isUrlSafeString(str) {
  if (typeof str !== 'string') {
    return false;
  }
  for (let i = 0; i < str.length; i++) {
    if (!urlAlphabet.includes(str[i])) {
      return false;
    }
  }
  return true;
}

export { urlAlphabet };
package-lock.json
{
  "name": "sample-nanoid-urlalphabet",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-nanoid-urlalphabet",
      "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": "sample-nanoid-urlalphabet",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "description": "verify nanoid.urlAlphabet in pkg:npm/nanoid@5.1.16",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "nanoid": "5.1.16"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify nanoid.urlAlphabet in pkg:npm/nanoid@5.1.16",
  "kind": "HOW",
  "packages": [
    "pkg:npm/nanoid@5.1.16"
  ],
  "symbols": [
    "nanoid.urlAlphabet"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import { urlAlphabet as rootAlphabet, customAlphabet } from 'nanoid';
import { urlAlphabet, getUrlAlphabet, isUrlSafeString } from '../index.js';

function testAlphabetStructure() {
  // 1. urlAlphabet is an exported 64-character string containing URL-safe characters
  assert.strictEqual(typeof urlAlphabet, 'string', 'urlAlphabet must be a string');
  assert.strictEqual(urlAlphabet.length, 64, 'urlAlphabet must have length 64');
  assert.strictEqual(getUrlAlphabet(), urlAlphabet, 'getUrlAlphabet helper must return urlAlphabet');

  // 2. urlAlphabet contains 64 unique characters with numbers, lowercase letters, uppercase letters, hyphen, and underscore
  const charSet = new Set(urlAlphabet);
  assert.strictEqual(charSet.size, 64, 'urlAlphabet must contain 64 unique characters');

  for (let c = 65; c <= 90; c++) {
    assert.ok(charSet.has(String.fromCharCode(c)), `Must contain uppercase letter ${String.fromCharCode(c)}`);
  }
  for (let c = 97; c <= 122; c++) {
    assert.ok(charSet.has(String.fromCharCode(c)), `Must contain lowercase letter ${String.fromCharCode(c)}`);
  }
  for (let c = 48; c <= 57; c++) {
    assert.ok(charSet.has(String.fromCharCode(c)), `Must contain digit ${String.fromCharCode(c)}`);
  }
  assert.ok(charSet.has('-'), 'Must contain hyphen (-) character');
  assert.ok(charSet.has('_'), 'Must contain underscore (_) character');

  // 3. urlAlphabet characters all conform to URL-safe ASCII character set
  assert.match(urlAlphabet, /^[A-Za-z0-9_-]{64}$/, 'urlAlphabet characters must all be URL-safe ASCII');
  assert.strictEqual(isUrlSafeString(urlAlphabet), true, 'urlAlphabet must pass isUrlSafeString check');
  assert.strictEqual(isUrlSafeString('hello-world_123'), true);
  assert.strictEqual(isUrlSafeString('hello world!'), false);
  assert.strictEqual(isUrlSafeString(null), false);

  // 4. urlAlphabet is exported from the root nanoid package as an ESM named export
  assert.strictEqual(rootAlphabet, urlAlphabet, 'root export must match urlAlphabet');

  // 5. urlAlphabet can be used with customAlphabet to generate URL-safe identifiers
  const generate = customAlphabet(urlAlphabet, 21);
  assert.strictEqual(typeof generate, 'function', 'customAlphabet should return a generator');
  const id = generate();
  assert.strictEqual(typeof id, 'string', 'Generated ID must be a string');
  assert.strictEqual(id.length, 21, 'Generated ID length must match configured size');
  assert.strictEqual(isUrlSafeString(id), true, 'Generated ID characters must all belong to urlAlphabet');
}

function runAll() {
  testAlphabetStructure();
  console.log('Contract verification finished successfully.');
}

try {
  runAll();
  process.exit(0);
} catch (err) {
  console.error('Contract verification failed:', err);
  process.exit(1);
}

Исходный сидер

аноним