CodeSampleX

示例

pirates 4.0.7: addHook

已验证示例 — npm pirates 4.0.7: addHook. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: addHook transforms source code during CommonJS require execution

sha256:eff91a87e845d6ca2cf17ae8a7d2ea135f8fb9734a9751a1970935cb534f33b6

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
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-27

案例

HOW
目标
verify pirates.addHook in pkg:npm/pirates@4.0.7
包
符号
  • pirates.addHook
创建时间
2026-08-27T11:09:39Z

契约

  1. addHook transforms source code during CommonJS require execution
  2. revert function restores original module loader and removes transformation
  3. exts option allows adding require hooks for custom file extensions
  4. matcher function selectively determines whether a file should be transformed
  5. createReplacerHook utility correctly transforms targeted code and reverts
  6. hook returning a non-string value throws an Error
  7. passing a non-string extension throws a TypeError

文件

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.js
  • test/fixtures/custom.ext
  • test/fixtures/ignored.js
  • test/fixtures/sample.js

下载源代码构件 (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 pirates.addHook in pkg:npm/pirates@4.0.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/pirates@4.0.7
Demonstrate these symbols/APIs:
  - pirates.addHook

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:be1abcae5eca11736948e571587f261780b77f12353b7fb1518d973e2804c1b4","contract":["addHook transforms source code during CommonJS require execution","revert function restores original module loader and removes transformation","exts option allows adding require hooks for custom file extensions","matcher function selectively determines whether a file should be transformed","createReplacerHook utility correctly transforms targeted code and reverts","hook returning a non-string value throws an Error","passing a non-string extension throws a TypeError"],"goal":"verify pirates.addHook in pkg:npm/pirates@4.0.7","kind":"HOW","packages":["pkg:npm/pirates@4.0.7"],"schemaVersion":1,"symbols":["pirates.addHook"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/pirates@4.0.7"],"schemaVersion":1,"subject":"pkg:npm/pirates@4.0.7","symbols":["pirates.addHook"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const { addHook } = require('pirates');

/**
 * Creates and registers a string replacement require hook.
 * @param {string|RegExp} pattern
 * @param {string} replacement
 * @param {object} [options]
 * @returns {() => void} revert function
 */
function createReplacerHook(pattern, replacement, options) {
  return addHook(
    (code) => code.replace(pattern, replacement),
    options
  );
}

module.exports = {
  addHook,
  createReplacerHook,
};
package-lock.json
{
  "name": "sample-pirates",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pirates",
      "version": "1.0.0",
      "dependencies": {
        "pirates": "4.0.7"
      }
    },
    "node_modules/pirates": {
      "version": "4.0.7",
      "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",
      "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
      "license": "MIT",
      "engines": {
        "node": ">= 6"
      }
    }
  }
}
package.json
{
  "name": "sample-pirates",
  "version": "1.0.0",
  "description": "Clean-room verification sample for pirates",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "pirates": "4.0.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pirates.addHook in pkg:npm/pirates@4.0.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pirates@4.0.7"
  ],
  "symbols": [
    "pirates.addHook"
  ]
}
test/contract.js
const assert = require('node:assert/strict');
const path = require('node:path');
const { addHook, createReplacerHook } = require('../index.js');

const fixtureSample = path.join(__dirname, 'fixtures', 'sample.js');
const fixtureCustom = path.join(__dirname, 'fixtures', 'custom.ext');
const fixtureIgnored = path.join(__dirname, 'fixtures', 'ignored.js');

// 1. addHook transforms source code during CommonJS require execution
{
  const revert = addHook((code, filename) => {
    return code.replace('__GREETING__', 'HELLO_FROM_HOOK');
  });

  const result = require(fixtureSample);
  assert.equal(result.message, 'HELLO_FROM_HOOK');

  // 2. revert function restores original module loader and removes transformation
  revert();
  delete require.cache[require.resolve(fixtureSample)];

  const original = require(fixtureSample);
  assert.equal(original.message, '__GREETING__');
}

// 3. exts option allows adding require hooks for custom file extensions
{
  const revert = addHook((code, filename) => {
    return code.replace('CUSTOM_RAW_CONTENT', 'PARSED_CUSTOM_CONTENT');
  }, { exts: ['.ext'] });

  const custom = require(fixtureCustom);
  assert.equal(custom.content, 'PARSED_CUSTOM_CONTENT');

  revert();
  delete require.cache[require.resolve(fixtureCustom)];
}

// 4. matcher function selectively determines whether a file should be transformed
{
  const revert = addHook((code, filename) => {
    return 'module.exports = { message: "MATCHED_ONLY" };';
  }, {
    matcher: (filename) => filename.endsWith('sample.js')
  });

  delete require.cache[require.resolve(fixtureSample)];
  delete require.cache[require.resolve(fixtureIgnored)];

  const matched = require(fixtureSample);
  assert.equal(matched.message, 'MATCHED_ONLY');

  const ignored = require(fixtureIgnored);
  assert.equal(ignored.message, 'IGNORED_FILE');

  revert();
  delete require.cache[require.resolve(fixtureSample)];
  delete require.cache[require.resolve(fixtureIgnored)];
}

// 5. createReplacerHook utility correctly transforms targeted code and reverts
{
  const revert = createReplacerHook('__GREETING__', 'UTILITY_TRANSFORMED');

  delete require.cache[require.resolve(fixtureSample)];
  const transformed = require(fixtureSample);
  assert.equal(transformed.message, 'UTILITY_TRANSFORMED');

  revert();
  delete require.cache[require.resolve(fixtureSample)];
  const restored = require(fixtureSample);
  assert.equal(restored.message, '__GREETING__');
}

// 6. hook returning a non-string value throws an Error
{
  const revert = addHook((code, filename) => {
    return 12345; // non-string return value
  });

  delete require.cache[require.resolve(fixtureSample)];
  assert.throws(
    () => {
      require(fixtureSample);
    },
    (err) => {
      return err instanceof Error && err.message.includes('[Pirates] A hook returned a non-string');
    }
  );

  revert();
  delete require.cache[require.resolve(fixtureSample)];
}

// 7. passing a non-string extension throws a TypeError
{
  assert.throws(
    () => {
      addHook(() => {}, { exts: [42] });
    },
    {
      name: 'TypeError',
      message: 'Invalid Extension: 42'
    }
  );
}

console.log('All pirates.addHook contract assertions passed.');
test/fixtures/custom.ext
module.exports = {
  content: 'CUSTOM_RAW_CONTENT'
};
test/fixtures/ignored.js
module.exports = {
  message: 'IGNORED_FILE'
};
test/fixtures/sample.js
module.exports = {
  message: '__GREETING__'
};

原始种子者

匿名