CodeSampleX

Exemple

levn 0.4.1: parse

Échantillon vérifié pour npm levn 0.4.1: parse. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.

sha256:3954ffcecd6b6397831b9c6295777229ef1bb7fef99b6ab91063edeb08903f4e

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-01

Cas

HOW
Objectif
verify levn.parse in pkg:npm/levn@0.4.1
Paquets
Symboles
  • levn.parse
Environnement
node 22.23.2
Créé
2026-09-01T15:51:17Z

Contrat

  1. levn.parse parses primitive types including Number, String, Boolean, Undefined, Null, and NaN from string notation
  2. levn.parse parses composite types including arrays, tuples, and objects with nested type specifications
  3. levn.parse parses special types including Date literals and RegExp patterns with optional delimiters and flags
  4. levn.parse parses union types by attempting candidate type conversions in left-to-right precedence order
  5. levn.parse supports explicit mode using wildcard type or explicit option to require unambiguous literal syntax
  6. levn.parse supports custom type definitions with custom typeOf, validate, and cast functions
  7. levn.parse throws an error when the input string does not conform to the expected type

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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 levn.parse in pkg:npm/levn@0.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/levn@0.4.1
Demonstrate these symbols/APIs:
  - levn.parse

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:25e15e631172911c86d8d9c1cfbbad4f754284f6f1ae8f3de6fd7061b7139a55","contract":["levn.parse parses primitive types including Number, String, Boolean, Undefined, Null, and NaN from string notation","levn.parse parses composite types including arrays, tuples, and objects with nested type specifications","levn.parse parses special types including Date literals and RegExp patterns with optional delimiters and flags","levn.parse parses union types by attempting candidate type conversions in left-to-right precedence order","levn.parse supports explicit mode using wildcard type or explicit option to require unambiguous literal syntax","levn.parse supports custom type definitions with custom typeOf, validate, and cast functions","levn.parse throws an error when the input string does not conform to the expected type"],"goal":"verify levn.parse in pkg:npm/levn@0.4.1","kind":"HOW","packages":["pkg:npm/levn@0.4.1"],"schemaVersion":1,"symbols":["levn.parse"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/levn@0.4.1"],"schemaVersion":1,"subject":"pkg:npm/levn@0.4.1","symbols":["levn.parse"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-levn",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-levn",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "levn": "0.4.1"
      }
    },
    "node_modules/levn": {
      "version": "0.4.1",
      "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
      "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
      "license": "MIT",
      "dependencies": {
        "prelude-ls": "^1.2.1",
        "type-check": "~0.4.0"
      },
      "engines": {
        "node": ">= 0.8.0"
      }
    },
    "node_modules/prelude-ls": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
      "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8.0"
      }
    },
    "node_modules/type-check": {
      "version": "0.4.0",
      "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
      "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
      "license": "MIT",
      "dependencies": {
        "prelude-ls": "^1.2.1"
      },
      "engines": {
        "node": ">= 0.8.0"
      }
    }
  }
}
package.json
{
  "name": "sample-levn",
  "version": "1.0.0",
  "description": "Clean-room verification for levn.parse",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "levn": "0.4.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify levn.parse in pkg:npm/levn@0.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/levn@0.4.1"
  ],
  "symbols": [
    "levn.parse"
  ]
}
src/index.js
const levn = require('levn');

/**
 * Parses a string input into a JavaScript value based on the specified type.
 * @param {string} type - Type specification string.
 * @param {string} input - Levn formatted string input.
 * @param {object} [options] - Optional parsing options.
 * @returns {*} Parsed JavaScript value.
 */
function parseValue(type, input, options) {
  return levn.parse(type, input, options);
}

module.exports = {
  parseValue,
  levn,
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { parseValue, levn } = require('../src/index.js');

async function runContract() {
  // 1. levn.parse parses primitive types including Number, String, Boolean, Undefined, Null, and NaN from string notation
  assert.strictEqual(parseValue('Number', '42'), 42);
  assert.strictEqual(parseValue('Number', '3.14'), 3.14);
  assert.strictEqual(parseValue('String', 'hello world'), 'hello world');
  assert.strictEqual(parseValue('Boolean', 'true'), true);
  assert.strictEqual(parseValue('Boolean', 'false'), false);
  assert.strictEqual(parseValue('Undefined', 'undefined'), undefined);
  assert.strictEqual(parseValue('Null', 'null'), null);
  assert.strictEqual(Number.isNaN(parseValue('NaN', 'NaN')), true);

  // 2. levn.parse parses composite types including arrays, tuples, and objects with nested type specifications
  assert.deepStrictEqual(parseValue('[Number]', '1, 2, 3'), [1, 2, 3]);
  assert.deepStrictEqual(parseValue('[String]', 'foo, bar, baz'), ['foo', 'bar', 'baz']);
  assert.deepStrictEqual(parseValue('(String, Number, Boolean)', 'alice, 30, true'), ['alice', 30, true]);
  assert.deepStrictEqual(
    parseValue('{name: String, count: Number}', 'name: item, count: 5'),
    { name: 'item', count: 5 }
  );

  // 3. levn.parse parses special types including Date literals and RegExp patterns with optional delimiters and flags
  const parsedDate = parseValue('Date', '2025-01-15');
  assert.ok(parsedDate instanceof Date);
  assert.strictEqual(parsedDate.getUTCFullYear(), 2025);

  const parsedRegExp = parseValue('RegExp', '/[a-z]+/i');
  assert.ok(parsedRegExp instanceof RegExp);
  assert.strictEqual(parsedRegExp.test('ABC'), true);

  const unquotedRegExp = parseValue('RegExp', 'hello');
  assert.ok(unquotedRegExp instanceof RegExp);
  assert.strictEqual(unquotedRegExp.test('hello'), true);

  // 4. levn.parse parses union types by attempting candidate type conversions in left-to-right precedence order
  assert.strictEqual(parseValue('Number | String', '123'), 123);
  assert.strictEqual(parseValue('Number | String', 'sample-text'), 'sample-text');
  assert.strictEqual(parseValue('Boolean | Number', 'true'), true);
  assert.strictEqual(parseValue('Boolean | Number', '99'), 99);

  // 5. levn.parse supports explicit mode using wildcard type or explicit option to require unambiguous literal syntax
  assert.deepStrictEqual(parseValue('*', '[1, "two", true]'), [1, 'two', true]);
  assert.strictEqual(parseValue('String', 'value', { explicit: true }), 'value');
  assert.throws(() => {
    parseValue('RegExp', 'not-a-regex-literal', { explicit: true });
  }, /does not type check/);

  // 6. levn.parse supports custom type definitions with custom typeOf, validate, and cast functions
  const customOptions = {
    customTypes: {
      EvenNumber: {
        typeOf: 'Number',
        validate: function(x) {
          return typeof x === 'number' && x % 2 === 0;
        },
        cast: function(val) {
          const num = parseInt(val, 10);
          return isNaN(num) ? { type: 'Nothing' } : { type: 'Just', value: num };
        }
      }
    }
  };
  assert.strictEqual(parseValue('EvenNumber', '8', customOptions), 8);
  assert.throws(() => {
    parseValue('EvenNumber', '9', customOptions);
  }, /does not type check/);

  // 7. levn.parse throws an error when the input string does not conform to the expected type
  assert.throws(() => {
    parseValue('Number', 'not-a-number');
  }, /does not type check/);

  console.log('Contract tests passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Seeder d'origine

anonyme