CodeSampleX

Exemple

dotenv 16.6.1

Échantillon vérifié pour npm dotenv 16.6.1. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi : dotenv.parse parses basic…

sha256:8a33b2b2c39e29aa246afb7822c10f89de4808af93e17b065b35f3cd8d6fd342

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
2
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 10

Environnements des exécutions de vérification

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

Cas

HOW
Objectif
verify pkg:npm/dotenv@16.6.1
Paquets
Environnement
node 22.23.2
Créé
2026-08-23T06:00:25Z

Contrat

  1. dotenv.parse parses basic key-value pairs with unquoted, single-quoted, and double-quoted values
  2. dotenv.parse strips leading export keywords and inline comments on unquoted values
  3. dotenv.parse expands newline and carriage return escape sequences in double-quoted strings
  4. dotenv.populate sets environment variables on target object without overwriting existing keys by default
  5. dotenv.populate with override set to true overwrites existing target keys
  6. dotenv.populate throws an error when parsed argument is not an object
  7. dotenv.configDotenv loads variables from specified file paths into target processEnv
  8. dotenv.configDotenv returns an error object when target path does not exist

Fichiers

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 pkg:npm/dotenv@16.6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/dotenv@16.6.1

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:03dd128a17047f836ab37087b7449633b59057548bac2eec8abc6587a4edfac8","contract":["dotenv.parse parses basic key-value pairs with unquoted, single-quoted, and double-quoted values","dotenv.parse strips leading export keywords and inline comments on unquoted values","dotenv.parse expands newline and carriage return escape sequences in double-quoted strings","dotenv.populate sets environment variables on target object without overwriting existing keys by default","dotenv.populate with override set to true overwrites existing target keys","dotenv.populate throws an error when parsed argument is not an object","dotenv.configDotenv loads variables from specified file paths into target processEnv","dotenv.configDotenv returns an error object when target path does not exist"],"goal":"verify pkg:npm/dotenv@16.6.1","kind":"HOW","packages":["pkg:npm/dotenv@16.6.1"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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/dotenv@16.6.1"],"schemaVersion":1,"subject":"pkg:npm/dotenv@16.6.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-dotenv",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-dotenv",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "dotenv": "16.6.1"
      }
    },
    "node_modules/dotenv": {
      "version": "16.6.1",
      "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
      "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=12"
      },
      "funding": {
        "url": "https://dotenvx.com"
      }
    }
  }
}
package.json
{
  "name": "sample-dotenv",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "dotenv": "16.6.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/dotenv@16.6.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/dotenv@16.6.1"
  ]
}
src/index.mjs
import dotenv from 'dotenv';

/**
 * Parses a string or buffer in .env format into an object.
 * @param {string|Buffer} src - The contents to parse.
 * @returns {Record<string, string>} Key-value object of environment variables.
 */
export function parseEnv(src) {
  return dotenv.parse(src);
}

/**
 * Populates a target object with values from a parsed environment object.
 * @param {Record<string, string>} target - The destination object (e.g., process.env).
 * @param {Record<string, string>} parsed - The source key-value object.
 * @param {object} [options] - Population options (e.g., { override: boolean }).
 */
export function populateEnv(target, parsed, options = {}) {
  return dotenv.populate(target, parsed, options);
}

/**
 * Loads and populates environment variables from a file into process.env or a custom object.
 * @param {object} [options] - Configuration options.
 * @returns {{ parsed?: Record<string, string>, error?: Error }}
 */
export function loadEnv(options = {}) {
  return dotenv.configDotenv(options);
}

export { dotenv };
export default dotenv;
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import dotenv from 'dotenv';
import { parseEnv, populateEnv, loadEnv } from '../src/index.mjs';

// 1. dotenv.parse parses basic key-value pairs with unquoted, single-quoted, and double-quoted values
{
  const envContent = [
    'PLAIN_KEY=plain_value',
    'SINGLE_QUOTED=\'single value\'',
    'DOUBLE_QUOTED="double value"',
    'BACKTICK_QUOTED=`backtick value`',
    'COLON_KEY: colon_value'
  ].join('\n');

  const parsed = dotenv.parse(envContent);
  assert.equal(parsed.PLAIN_KEY, 'plain_value');
  assert.equal(parsed.SINGLE_QUOTED, 'single value');
  assert.equal(parsed.DOUBLE_QUOTED, 'double value');
  assert.equal(parsed.BACKTICK_QUOTED, 'backtick value');
  assert.equal(parsed.COLON_KEY, 'colon_value');

  // Verify helper export
  const helperParsed = parseEnv('PORT=8080');
  assert.equal(helperParsed.PORT, '8080');
}

// 2. dotenv.parse strips leading export keywords and inline comments on unquoted values
{
  const envContent = [
    'export EXPORTED_VAR=active # this is an inline comment',
    'HASH_IN_DOUBLE="value # not a comment"',
    'HASH_IN_SINGLE=\'value # not a comment\''
  ].join('\n');

  const parsed = dotenv.parse(envContent);
  assert.equal(parsed.EXPORTED_VAR, 'active');
  assert.equal(parsed.HASH_IN_DOUBLE, 'value # not a comment');
  assert.equal(parsed.HASH_IN_SINGLE, 'value # not a comment');
}

// 3. dotenv.parse expands newline and carriage return escape sequences in double-quoted strings
{
  const envContent = [
    'DOUBLE_ESCAPED="line1\\nline2\\rline3"',
    'SINGLE_RAW=\'line1\\nline2\\rline3\''
  ].join('\n');

  const parsed = dotenv.parse(envContent);
  assert.equal(parsed.DOUBLE_ESCAPED, 'line1\nline2\rline3');
  assert.equal(parsed.SINGLE_RAW, 'line1\\nline2\\rline3');
}

// 4. dotenv.populate sets environment variables on target object without overwriting existing keys by default
{
  const target = { EXISTING_KEY: 'original_value' };
  const parsed = {
    EXISTING_KEY: 'new_value',
    NEW_KEY: 'created_value'
  };

  dotenv.populate(target, parsed);
  assert.equal(target.EXISTING_KEY, 'original_value');
  assert.equal(target.NEW_KEY, 'created_value');

  // Verify helper export
  const targetHelper = { A: '1' };
  populateEnv(targetHelper, { A: '2', B: '3' });
  assert.equal(targetHelper.A, '1');
  assert.equal(targetHelper.B, '3');
}

// 5. dotenv.populate with override set to true overwrites existing target keys
{
  const target = { KEY_TO_OVERRIDE: 'initial_value' };
  const parsed = { KEY_TO_OVERRIDE: 'updated_value' };

  dotenv.populate(target, parsed, { override: true });
  assert.equal(target.KEY_TO_OVERRIDE, 'updated_value');
}

// 6. dotenv.populate throws an error when parsed argument is not an object
{
  assert.throws(
    () => dotenv.populate({}, 'invalid_string'),
    (err) => err.code === 'OBJECT_REQUIRED'
  );
}

// 7. dotenv.configDotenv loads variables from specified file paths into target processEnv
{
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'csx-dotenv-test-'));
  const tempFilePath = path.join(tempDir, 'custom.env');

  try {
    fs.writeFileSync(tempFilePath, 'APP_MODE=production\nAPP_PORT=3000\n', 'utf8');

    const customProcessEnv = {};
    const result = dotenv.configDotenv({
      path: tempFilePath,
      processEnv: customProcessEnv
    });

    assert.equal(result.error, undefined);
    assert.deepEqual(result.parsed, {
      APP_MODE: 'production',
      APP_PORT: '3000'
    });
    assert.equal(customProcessEnv.APP_MODE, 'production');
    assert.equal(customProcessEnv.APP_PORT, '3000');

    // Test loadEnv helper
    const helperTarget = {};
    const helperResult = loadEnv({
      path: tempFilePath,
      processEnv: helperTarget
    });
    assert.equal(helperResult.error, undefined);
    assert.equal(helperTarget.APP_MODE, 'production');
  } finally {
    fs.rmSync(tempDir, { recursive: true, force: true });
  }
}

// 8. dotenv.configDotenv returns an error object when target path does not exist
{
  const nonExistentPath = path.join(os.tmpdir(), 'non-existent-' + Date.now() + '.env');
  const customProcessEnv = {};
  const result = dotenv.configDotenv({
    path: nonExistentPath,
    processEnv: customProcessEnv
  });

  assert.notEqual(result.error, undefined);
  assert.equal(result.error.code, 'ENOENT');
  assert.deepEqual(result.parsed, {});
}

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

Seeder d'origine

anonyme