CodeSampleX

サンプル

pirates 4.0.7: addHook

検証済みサンプル — npm pirates 4.0.7: addHook. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: addHook transforms source code during CommonJS require…

sha256:eff91a87e845d6ca2cf17ae8a7d2ea135f8fb9734a9751a1970935cb534f33b6

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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__'
};

オリジンシーダー

匿名