CodeSampleX

Ejemplo

loose-envify 1.4.0: loose-envify

Muestra verificada para npm loose-envify 1.4.0: loose-envify. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:252adfac65d0e0a3f513fc7b4e426baf75b82a4eef727850ffae093b1671308c

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify loose-envify in pkg:npm/loose-envify@1.4.0
Paquetes
Símbolos
  • loose-envify
Entorno
node 22.23.2
Creado
2026-09-01T22:49:41Z

Contrato

  1. looseEnvify exports transform stream replacing process.env references with literal values
  2. createCustomEnvTransformer uses looseEnvify/custom to replace custom variables including numbers and booleans
  3. purge option replaces undefined environment variables with literal undefined
  4. looseEnvify passes through .json files unmodified
  5. looseEnvify preserves assignments and property chains on process.env

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 loose-envify in pkg:npm/loose-envify@1.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/loose-envify@1.4.0
Demonstrate these symbols/APIs:
  - loose-envify

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:5f4daa86b33e5a1befa1d84920f638b8f5f2ae4f9493a53902b708467b39c147","contract":["looseEnvify exports transform stream replacing process.env references with literal values","createCustomEnvTransformer uses looseEnvify/custom to replace custom variables including numbers and booleans","purge option replaces undefined environment variables with literal undefined","looseEnvify passes through .json files unmodified","looseEnvify preserves assignments and property chains on process.env"],"goal":"verify loose-envify in pkg:npm/loose-envify@1.4.0","kind":"HOW","packages":["pkg:npm/loose-envify@1.4.0"],"schemaVersion":1,"symbols":["loose-envify"]},"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","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/loose-envify@1.4.0"],"schemaVersion":1,"subject":"pkg:npm/loose-envify@1.4.0","symbols":["loose-envify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-loose-envify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-loose-envify",
      "version": "1.0.0",
      "dependencies": {
        "loose-envify": "1.4.0"
      }
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/loose-envify": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
      "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
      "license": "MIT",
      "dependencies": {
        "js-tokens": "^3.0.0 || ^4.0.0"
      },
      "bin": {
        "loose-envify": "cli.js"
      }
    }
  }
}
package.json
{
  "name": "sample-loose-envify",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of loose-envify",
  "main": "src/index.js",
  "dependencies": {
    "loose-envify": "1.4.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify loose-envify in pkg:npm/loose-envify@1.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/loose-envify@1.4.0"
  ],
  "symbols": [
    "loose-envify"
  ]
}
src/index.js
const looseEnvify = require('loose-envify');
const looseEnvifyCustom = require('loose-envify/custom');
const { Readable } = require('node:stream');

/**
 * Transforms JavaScript code by replacing process.env references using loose-envify stream.
 * @param {string} code - Source code string.
 * @param {string} [filename='index.js'] - File name for transform stream.
 * @param {object} [env=process.env] - Environment variable overrides.
 * @returns {Promise<string>} Transformed code.
 */
function replaceEnvCode(code, filename = 'index.js', env = process.env) {
  return new Promise((resolve, reject) => {
    const transformStream = looseEnvify(filename, env);
    let result = '';

    transformStream.on('data', (chunk) => {
      result += chunk.toString();
    });
    transformStream.on('end', () => {
      resolve(result);
    });
    transformStream.on('error', (err) => {
      reject(err);
    });

    const readable = new Readable();
    readable.push(code);
    readable.push(null);
    readable.pipe(transformStream);
  });
}

/**
 * Creates a custom environment replacer function using loose-envify/custom.
 * @param {object} customEnv - Custom environment dictionary.
 * @returns {(code: string, filename?: string, trOpts?: object) => Promise<string>}
 */
function createCustomEnvTransformer(customEnv) {
  const transformFactory = looseEnvifyCustom(customEnv);
  return function transform(code, filename = 'index.js', trOpts) {
    return new Promise((resolve, reject) => {
      const transformStream = transformFactory(filename, trOpts);
      let result = '';

      transformStream.on('data', (chunk) => {
        result += chunk.toString();
      });
      transformStream.on('end', () => {
        resolve(result);
      });
      transformStream.on('error', (err) => {
        reject(err);
      });

      const readable = new Readable();
      readable.push(code);
      readable.push(null);
      readable.pipe(transformStream);
    });
  };
}

module.exports = {
  looseEnvify,
  looseEnvifyCustom,
  replaceEnvCode,
  createCustomEnvTransformer
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  looseEnvify,
  looseEnvifyCustom,
  replaceEnvCode,
  createCustomEnvTransformer
} = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof looseEnvify, 'function', 'looseEnvify should be a function');
assert.strictEqual(typeof looseEnvifyCustom, 'function', 'looseEnvifyCustom should be a function');
assert.strictEqual(typeof replaceEnvCode, 'function', 'replaceEnvCode should be a function');
assert.strictEqual(typeof createCustomEnvTransformer, 'function', 'createCustomEnvTransformer should be a function');

// 2. Default looseEnvify transform replacing process.env references with literal values
const sampleCode = `
if (process.env.NODE_ENV === "production") {
  console.log("Running in production mode");
}
const api = process.env.API_ENDPOINT;
`;
const transformed = await replaceEnvCode(sampleCode, 'app.js', {
  NODE_ENV: 'production',
  API_ENDPOINT: 'https://example.com/api'
});
assert.ok(transformed.includes('if ("production" === "production")'), 'NODE_ENV should be replaced with "production"');
assert.ok(transformed.includes('const api = "https://example.com/api";'), 'API_ENDPOINT should be replaced');
assert.ok(!transformed.includes('process.env.NODE_ENV'), 'process.env.NODE_ENV should not remain');
assert.ok(!transformed.includes('process.env.API_ENDPOINT'), 'process.env.API_ENDPOINT should not remain');

// 3. Custom envify factory replaces custom variables including numbers and booleans
const customTransformer = createCustomEnvTransformer({
  APP_PORT: 8080,
  FEATURE_FLAG: true,
  DEBUG: false,
  NAME: 'SampleApp'
});
const customCode = `
const port = process.env.APP_PORT;
const enabled = process.env.FEATURE_FLAG;
const debug = process.env.DEBUG;
const name = process.env.NAME;
`;
const customResult = await customTransformer(customCode, 'server.js');
assert.ok(customResult.includes('const port = 8080;'), 'Number environment variable should be replaced with numeric literal');
assert.ok(customResult.includes('const enabled = true;'), 'Boolean environment variable should be replaced with true');
assert.ok(customResult.includes('const debug = false;'), 'Boolean environment variable should be replaced with false');
assert.ok(customResult.includes('const name = "SampleApp";'), 'String environment variable should be replaced with string literal');

// 4. Purge option replaces undefined environment variables with literal 'undefined'
const purgeTransformer = createCustomEnvTransformer({
  KNOWN_VAR: 'known',
  _: ['purge']
});
const purgeCode = `
const a = process.env.KNOWN_VAR;
const b = process.env.UNDEFINED_VAR;
`;
const purgeResult = await purgeTransformer(purgeCode, 'config.js');
assert.ok(purgeResult.includes('const a = "known";'), 'Known variable should be replaced');
assert.ok(purgeResult.includes('const b = undefined;'), 'Unknown variable with purge should be replaced with undefined');

// 5. JSON files passthrough unmodified
const jsonInput = '{"env": "process.env.NODE_ENV"}';
const jsonResult = await replaceEnvCode(jsonInput, 'config.json', { NODE_ENV: 'production' });
assert.strictEqual(jsonResult, jsonInput, 'JSON files should pass through unmodified');

// 6. Preserves assignments and property chains on process.env
const assignmentCode = `
process.env.NODE_ENV = "override";
const sub = process.env.NODE_ENV.toUpperCase();
`;
const preservedResult = await replaceEnvCode(assignmentCode, 'init.js', { NODE_ENV: 'production' });
assert.ok(preservedResult.includes('process.env.NODE_ENV = "override";'), 'Assignment should not be replaced');
assert.ok(preservedResult.includes('process.env.NODE_ENV.toUpperCase();'), 'Property access on process.env variable should not be replaced');

console.log('All loose-envify contract tests passed successfully.');

Seeder de origen

anónimo