CodeSampleX

示例

loose-envify 1.4.0: loose-envify

已验证示例 — npm loose-envify 1.4.0: loose-envify. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: looseEnvify exports transform stream replacing…

sha256:252adfac65d0e0a3f513fc7b4e426baf75b82a4eef727850ffae093b1671308c

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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-01

案例

HOW
目标
verify loose-envify in pkg:npm/loose-envify@1.4.0
包
符号
  • loose-envify
环境
node 22.23.2
创建时间
2026-09-01T22:49:41Z

契约

  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

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 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.');

原始种子者

匿名