CodeSampleX

サンプル

bare-process 4.5.1: arch, cpuUsage, cwd

検証済みサンプル — npm bare-process 4.5.1: arch, cpuUsage, cwd. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: package manifest defines exports for root…

sha256:18ad42dd289aa6d1e14d2c4cf81a74583dd5e7443d550e90365e83d21c20884d

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。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 pkg:npm/bare-process@4.5.1
パッケージ
シンボル
  • arch
  • cpuUsage
  • cwd
  • memoryUsage
  • nextTick
  • pid
  • platform
  • uptime
作成日
2026-08-27T13:29:17Z

コントラクト

  1. package manifest defines exports for root, global, and package paths with dependencies on Bare subsystem packages
  2. declares Process interface with arch, cpuUsage, cwd, memoryUsage, nextTick, pid, platform, and uptime in index.d.ts and global.d.ts
  3. instantiates Process class with Bare lifecycle event forwarding, signal listeners, and initial high-resolution start time
  4. provides system getters for platform, arch, pid, ppid, title, argv, version, and cwd delegating to bare-os and Bare runtime
  5. calculates process uptime in seconds from high-resolution start timestamp and returns CPU and memory utilization statistics
  6. schedules asynchronous microtask callbacks with bound arguments via nextTick

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • 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 pkg:npm/bare-process@4.5.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-process@4.5.1
Demonstrate these symbols/APIs:
  - arch
  - cpuUsage
  - cwd
  - memoryUsage
  - nextTick
  - pid
  - platform
  - uptime

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:ffcbd60c2510832907400889b8f7003abee03b462567689126e22f8d07554826","contract":["package manifest defines exports for root, global, and package paths with dependencies on Bare subsystem packages","declares Process interface with arch, cpuUsage, cwd, memoryUsage, nextTick, pid, platform, and uptime in index.d.ts and global.d.ts","instantiates Process class with Bare lifecycle event forwarding, signal listeners, and initial high-resolution start time","provides system getters for platform, arch, pid, ppid, title, argv, version, and cwd delegating to bare-os and Bare runtime","calculates process uptime in seconds from high-resolution start timestamp and returns CPU and memory utilization statistics","schedules asynchronous microtask callbacks with bound arguments via nextTick"],"goal":"verify pkg:npm/bare-process@4.5.1","kind":"HOW","packages":["pkg:npm/bare-process@4.5.1"],"schemaVersion":1,"symbols":["arch","cpuUsage","cwd","memoryUsage","nextTick","pid","platform","uptime"]},"contractCommand":["node","test/contract.mjs"],"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/bare-process@4.5.1"],"schemaVersion":1,"subject":"pkg:npm/bare-process@4.5.1","symbols":["arch","cpuUsage","cwd","memoryUsage","nextTick","pid","platform","uptime"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-bare-process",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bare-process",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bare-process": "4.5.1"
      }
    },
    "node_modules/b4a": {
      "version": "1.8.1",
      "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz",
      "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==",
      "license": "Apache-2.0",
      "peerDependencies": {
        "react-native-b4a": "*"
      },
      "peerDependenciesMeta": {
        "react-native-b4a": {
          "optional": true
        }
      }
    },
    "node_modules/bare-abort": {
      "version": "2.0.13",
      "resolved": "https://registry.npmjs.org/bare-abort/-/bare-abort-2.0.13.tgz",
      "integrity": "sha512-zdc8l88eB11Jsz5rDd6sCAgv2kUFXgdrZWoMlgU6JMkfAi1/uuGFC3IEHswKbIRQTk5H3T5CMuechsXYxiaHlQ==",
      "license": "Apache-2.0"
    },
    "node_modules/bare-env": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/bare-env/-/bare-env-3.0.1.tgz",
      "integrity": "sha512-BdoLvnzaWR0YyyJreEx4zG2Od0AC/s9JSZ+EXyMZKunpn8zEgR/dGv37hdFUaY1bjDkcRKvcKkFyJIwlJ0CaYA==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-os": "^3.0.1"
      }
    },
    "node_modules/bare-events": {
      "version": "2.9.2",
      "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",
      "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
      "license": "Apache-2.0",
      "peerDependencies": {
        "bare-abort-controller": "*"
      },
      "peerDependenciesMeta": {
        "bare-abort-controller": {
          "optional": true
        }
      }
    },
    "node_modules/bare-fs": {
      "version": "4.8.1",
      "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.1.tgz",
      "integrity": "sha512-N1nnXdHZAOSstz0XiHikGS4HGMH4CnSwhqWdGQQMqqdvp4Jybm9sE3R1WVnpWVd4SFkc8ryPDBLViNLwiEqECg==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.5.4",
        "bare-path": "^3.0.0",
        "bare-stream": "^2.6.4",
        "bare-url": "^2.2.2",
        "fast-fifo": "^1.3.2"
      },
      "engines": {
        "bare": ">=1.28.0"
      },
      "peerDependencies": {
        "bare-buffer": "*"
      },
      "peerDependenciesMeta": {
        "bare-buffer": {
          "optional": true
        }
      }
    },
    "node_modules/bare-hrtime": {
      "version": "2.1.1",
      "resolved": "https://registry.npmjs.org/bare-hrtime/-/bare-hrtime-2.1.1.tgz",
      "integrity": "sha512-VMb3tHo05gsnbu3OXTmkDiwTjMlOsbQmKoysKqKEyR09m77TuDrYFbj3Q5GGk10dAKsUHrnXmwCaeJqzVpB5ZA==",
      "license": "Apache-2.0"
    },
    "node_modules/bare-os": {
      "version": "3.9.3",
      "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.9.3.tgz",
      "integrity": "sha512-fF4Q7QsyKVF5Rj0qvI8BgUNjqzC2JvQlpTaPLjVJVxYVUX5Zr9un+y3w1HmA4nNKdFmRBT8z/WmrjvXzXVerKQ==",
      "license": "Apache-2.0",
      "engines": {
        "bare": ">=1.14.0"
      }
    },
    "node_modules/bare-path": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.1.tgz",
      "integrity": "sha512-JprUlveX3QjApC1cTpsUOiscADftCGVWkzitbHsRqv84hzYwYHw2mbluddsq5TvI8mH/8Ov1f4BiMAdcB0oYnQ==",
      "license": "Apache-2.0"
    },
    "node_modules/bare-pipe": {
      "version": "4.2.3",
      "resolved": "https://registry.npmjs.org/bare-pipe/-/bare-pipe-4.2.3.tgz",
      "integrity": "sha512-MJYji+Vy8cNMAB2fwg1WQAm1hFIOe5ojw5V9EhEa/wEEYpKT8c36WjHBDwgkgAZfUSX6wQcEFX+Q7wN09SgRow==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.0.0",
        "bare-stream": "^2.0.0"
      },
      "engines": {
        "bare": ">=1.16.0"
      }
    },
    "node_modules/bare-posix": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/bare-posix/-/bare-posix-1.0.1.tgz",
      "integrity": "sha512-b4quA8dyRVvX0aFIAIiev5zFATHwIUGr42Gmt+CqiBNg/bdsNkrj4bbkeotMOMiljJS4DCME5kywJO/TFwKo1A==",
      "license": "Apache-2.0"
    },
    "node_modules/bare-process": {
      "version": "4.5.1",
      "resolved": "https://registry.npmjs.org/bare-process/-/bare-process-4.5.1.tgz",
      "integrity": "sha512-CaAvy1trputD49mtwfJ6G75vydhnirLrW/F3Sznp4H556e1uZn8YMo9ELicBTrGYy7RBNUgPl9bpB/ERzRCiDw==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-abort": "^2.0.13",
        "bare-env": "^3.0.0",
        "bare-events": "^2.3.1",
        "bare-hrtime": "^2.0.0",
        "bare-os": "^3.7.1",
        "bare-posix": "^1.0.1",
        "bare-signals": "^5.0.0",
        "bare-stdio": "^1.0.1"
      }
    },
    "node_modules/bare-signals": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/bare-signals/-/bare-signals-5.0.0.tgz",
      "integrity": "sha512-8Gn8bBFUh2AUCJ9wWWFjSGWIo1HIUSIQnXRJGSm/f7GCDMqsuJhRmR1dT+HtDaDBkeu2l8Koxt2JLurfJ5yHVw==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.5.3"
      },
      "engines": {
        "bare": ">=1.7.0"
      }
    },
    "node_modules/bare-stdio": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/bare-stdio/-/bare-stdio-1.0.3.tgz",
      "integrity": "sha512-8BRMx7RWMWCbBmKhyHgBco62J+Pgss7+EPI21L3R9+w0UpwDYWUUcbE0YTOesGyt7M6N7VtoshYbzwrP0pI52Q==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-fs": "^4.5.2",
        "bare-pipe": "^4.1.5",
        "bare-tty": "^5.0.3"
      }
    },
    "node_modules/bare-stream": {
      "version": "2.13.4",
      "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz",
      "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==",
      "license": "Apache-2.0",
      "dependencies": {
        "b4a": "^1.8.1",
        "streamx": "^2.25.0",
        "teex": "^1.0.1"
      },
      "peerDependencies": {
        "bare-abort-controller": "*",
        "bare-buffer": "*",
        "bare-events": "*"
      },
      "peerDependenciesMeta": {
        "bare-abort-controller": {
          "optional": true
        },
        "bare-buffer": {
          "optional": true
        },
        "bare-events": {
          "optional": true
        }
      }
    },
    "node_modules/bare-tty": {
      "version": "5.1.2",
      "resolved": "https://registry.npmjs.org/bare-tty/-/bare-tty-5.1.2.tgz",
      "integrity": "sha512-wDHPU/yVQtrDCUrKVdIVOLmfIw7dFPETz30UayuFlROvgz8Juv2SmISSMhqxYQVO+fVnG/1ZoLcbGh/35eAjDA==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.2.0",
        "bare-signals": "^5.0.0",
        "bare-stream": "^2.0.0"
      },
      "engines": {
        "bare": ">=1.16.0"
      }
    },
    "node_modules/bare-url": {
      "version": "2.5.2",
      "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.2.tgz",
      "integrity": "sha512-L13PCJzKG8RGvx8V1/DdMi12ERhC3tprr7/8a94BxpmnRsFqxh5XZNdhtMxu5HPkRshYOOWRGY8lDP7ZhpG9Cg==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-path": "^3.0.0"
      }
    },
    "node_modules/events-universal": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
      "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.7.0"
      }
    },
    "node_modules/fast-fifo": {
      "version": "1.3.2",
      "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
      "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
      "license": "MIT"
    },
    "node_modules/streamx": {
      "version": "2.28.1",
      "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz",
      "integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==",
      "license": "MIT",
      "dependencies": {
        "events-universal": "^1.0.0",
        "fast-fifo": "^1.3.2",
        "text-decoder": "^1.1.0"
      }
    },
    "node_modules/teex": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
      "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
      "license": "MIT",
      "dependencies": {
        "streamx": "^2.12.5"
      }
    },
    "node_modules/text-decoder": {
      "version": "1.2.7",
      "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
      "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
      "license": "Apache-2.0",
      "dependencies": {
        "b4a": "^1.6.4"
      }
    }
  }
}
package.json
{
  "name": "sample-bare-process",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "bare-process": "4.5.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/bare-process@4.5.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-process@4.5.1"
  ],
  "symbols": [
    "arch",
    "cpuUsage",
    "cwd",
    "memoryUsage",
    "nextTick",
    "pid",
    "platform",
    "uptime"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import path from 'node:path';
import EventEmitter from 'node:events';

const require = createRequire(import.meta.url);

// 1. Resolve bare-process package manifest and verify exports and metadata
const pkgPath = require.resolve('bare-process/package');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));

assert.equal(pkg.name, 'bare-process', 'Package name must be bare-process');
assert.equal(pkg.version, '4.5.1', 'Package version must be 4.5.1');
assert.equal(pkg.license, 'Apache-2.0', 'Package license must be Apache-2.0');

assert.ok(pkg.exports, 'Package must define exports');
assert.equal(pkg.exports['.'].types, './index.d.ts', 'Root export must specify ./index.d.ts types');
assert.equal(pkg.exports['.'].default, './index.js', 'Root export must specify ./index.js default');
assert.equal(pkg.exports['./global'].types, './global.d.ts', './global export must specify ./global.d.ts types');
assert.equal(pkg.exports['./global'].default, './global.js', './global export must specify ./global.js default');
assert.equal(pkg.exports['./package'], './package.json', 'Package export must point to ./package.json');

assert.deepEqual(
  pkg.files,
  ['index.js', 'index.d.ts', 'global.js', 'global.d.ts'],
  'Package files array must contain expected source and declaration files'
);

const expectedDependencies = [
  'bare-abort',
  'bare-env',
  'bare-events',
  'bare-hrtime',
  'bare-os',
  'bare-posix',
  'bare-signals',
  'bare-stdio'
];
for (const dep of expectedDependencies) {
  assert.ok(pkg.dependencies[dep], `Package must depend on ${dep}`);
}

const pkgDir = path.dirname(pkgPath);

// 2. Verify TypeScript declarations (index.d.ts and global.d.ts)
const indexDtsPath = path.join(pkgDir, 'index.d.ts');
assert.ok(fs.existsSync(indexDtsPath), 'index.d.ts must exist');
const indexDts = fs.readFileSync(indexDtsPath, 'utf8');

assert.ok(indexDts.includes('interface ProcessEvents extends EventMap'), 'index.d.ts must define ProcessEvents');
assert.ok(indexDts.includes('interface Process<M extends ProcessEvents = ProcessEvents> extends EventEmitter<M>'), 'index.d.ts must define Process interface');
assert.ok(indexDts.includes('readonly arch: ReturnType<typeof os.arch>'), 'index.d.ts must declare arch getter');
assert.ok(indexDts.includes('readonly platform: ReturnType<typeof os.platform>'), 'index.d.ts must declare platform getter');
assert.ok(indexDts.includes('readonly pid: number'), 'index.d.ts must declare pid getter');
assert.ok(indexDts.includes('readonly ppid: number'), 'index.d.ts must declare ppid getter');
assert.ok(indexDts.includes('readonly argv: string[]'), 'index.d.ts must declare argv getter');
assert.ok(indexDts.includes('readonly env: Record<string, string>'), 'index.d.ts must declare env getter');
assert.ok(indexDts.includes('cwd(): string'), 'index.d.ts must declare cwd() method');
assert.ok(indexDts.includes('uptime(): number'), 'index.d.ts must declare uptime() method');
assert.ok(indexDts.includes('cpuUsage: typeof os.cpuUsage'), 'index.d.ts must declare cpuUsage method');
assert.ok(indexDts.includes('memoryUsage: typeof os.memoryUsage'), 'index.d.ts must declare memoryUsage method');
assert.ok(indexDts.includes('nextTick<T extends unknown[]>(cb: (...args: T) => unknown, ...args: T): void'), 'index.d.ts must declare nextTick method');
assert.ok(indexDts.includes('export = process'), 'index.d.ts must export process');

const globalDtsPath = path.join(pkgDir, 'global.d.ts');
assert.ok(fs.existsSync(globalDtsPath), 'global.d.ts must exist');
const globalDts = fs.readFileSync(globalDtsPath, 'utf8');
assert.ok(globalDts.includes('const process: Process'), 'global.d.ts must declare global process');

// 3. Verify JavaScript implementation source (index.js and global.js)
const indexJsPath = path.join(pkgDir, 'index.js');
assert.ok(fs.existsSync(indexJsPath), 'index.js must exist');
const indexJsCode = fs.readFileSync(indexJsPath, 'utf8');

assert.ok(indexJsCode.includes('class Process extends EventEmitter'), 'index.js must define Process class');
assert.ok(indexJsCode.includes("this._startTime = hrtime.bigint()"), 'index.js must capture _startTime in constructor');
assert.ok(indexJsCode.includes('module.exports = new Process()'), 'index.js must export new Process()');

const globalJsPath = path.join(pkgDir, 'global.js');
assert.ok(fs.existsSync(globalJsPath), 'global.js must exist');
const globalJsCode = fs.readFileSync(globalJsPath, 'utf8');
assert.ok(globalJsCode.includes("global.process = require('.')"), 'global.js must assign global.process');

// 4. Test Process instance and methods in an isolated execution harness
const mockBare = new EventEmitter();
mockBare.argv = ['bare', 'app.js', '--flag'];
mockBare.version = '1.31.0';
mockBare.versions = { bare: '1.31.0', uv: '1.48.0' };
mockBare.exitCode = 0;
let exitedCode = null;
mockBare.exit = (code) => { exitedCode = code; };
let suspended = false;
mockBare.suspend = () => { suspended = true; };
let resumed = false;
mockBare.resume = () => { resumed = true; };

let simulatedTimeBigInt = 1000000000n;
const mockHrtime = {
  bigint: () => simulatedTimeBigInt
};

let currentTitle = 'bare-app';
let currentCwd = 'mock-workspace-dir';
const mockOs = {
  platform: () => 'linux',
  arch: () => 'x64',
  pid: () => 4242,
  ppid: () => 101,
  execPath: () => 'bare',
  cwd: () => currentCwd,
  chdir: (dir) => { currentCwd = dir; },
  getProcessTitle: () => currentTitle,
  setProcessTitle: (t) => { currentTitle = t; },
  kill: (pid, signal) => { killedProcess = { pid, signal }; },
  cpuUsage: (prev) => ({ user: 12000, system: 3000 }),
  threadCpuUsage: (prev) => ({ user: 6000, system: 1500 }),
  resourceUsage: () => ({ maxRSS: 32768 }),
  availableMemory: () => 8589934592,
  constrainedMemory: () => 0,
  memoryUsage: () => ({ rss: 33554432, heapTotal: 16777216, heapUsed: 8388608 }),
  constants: {
    signals: { SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }
  }
};

let killedProcess = null;
let aborted = false;
const mockAbort = () => { aborted = true; };

class MockSignalEmitter extends EventEmitter {
  unref() {}
}

const mockSignals = {
  Emitter: MockSignalEmitter
};

class MockEventEmitter extends EventEmitter {
  static forward(source, target, events) {
    for (const event of events) {
      source.on(event, (...args) => {
        target.emit(event, ...args);
      });
    }
  }
}

const mockEnv = { NODE_ENV: 'test', FOO: 'bar' };
const mockStdio = { in: { isTTY: false }, out: { isTTY: true }, err: { isTTY: true } };
const mockPosix = {
  getgid: () => 1000,
  setgid: (id) => {},
  getegid: () => 1000,
  setegid: (id) => {},
  getuid: () => 1000,
  setuid: (id) => {},
  geteuid: () => 1000,
  seteuid: (id) => {},
  getgroups: () => [1000, 4, 27]
};

const customRequire = (id) => {
  if (id === 'bare-abort') return mockAbort;
  if (id === 'bare-events') return MockEventEmitter;
  if (id === 'bare-signals') return mockSignals;
  if (id === 'bare-os') return mockOs;
  if (id === 'bare-env') return mockEnv;
  if (id === 'bare-hrtime') return mockHrtime;
  if (id === 'bare-stdio') return mockStdio;
  if (id === 'bare-posix') return mockPosix;
  return require(id);
};

const cjsModule = { exports: {} };
const fn = new Function('Bare', 'require', 'module', 'exports', indexJsCode);
fn(mockBare, customRequire, cjsModule, cjsModule.exports);
const processInstance = cjsModule.exports;

// 5. Verify system getters and properties
assert.equal(processInstance.platform, 'linux', 'platform must return linux from bare-os');
assert.equal(processInstance.arch, 'x64', 'arch must return x64 from bare-os');
assert.equal(processInstance.pid, 4242, 'pid must return 4242 from bare-os');
assert.equal(processInstance.ppid, 101, 'ppid must return 101 from bare-os');
assert.equal(processInstance.title, 'bare-app', 'title must return process title');
processInstance.title = 'updated-app';
assert.equal(currentTitle, 'updated-app', 'setting title must update bare-os process title');
assert.equal(processInstance.execPath, 'bare', 'execPath must return bare');
assert.deepEqual(processInstance.execArgv, [], 'execArgv must return empty array');
assert.deepEqual(processInstance.argv, ['bare', 'app.js', '--flag'], 'argv must return Bare.argv');
assert.equal(processInstance.version, '1.31.0', 'version must return Bare.version');
assert.deepEqual(processInstance.versions, { bare: '1.31.0', uv: '1.48.0' }, 'versions must return Bare.versions');
assert.equal(processInstance.exitCode, 0, 'exitCode must return Bare.exitCode');
processInstance.exitCode = 1;
assert.equal(mockBare.exitCode, 1, 'setting exitCode must update Bare.exitCode');
assert.equal(processInstance.env, mockEnv, 'env must return bare-env instance');
assert.equal(processInstance.hrtime, mockHrtime, 'hrtime must return bare-hrtime instance');
assert.equal(processInstance.stdin, mockStdio.in, 'stdin must return stdio.in');
assert.equal(processInstance.stdout, mockStdio.out, 'stdout must return stdio.out');
assert.equal(processInstance.stderr, mockStdio.err, 'stderr must return stdio.err');

// 6. Verify filesystem and process management methods
assert.equal(processInstance.cwd(), 'mock-workspace-dir', 'cwd() must return current working directory');
processInstance.chdir('mock-workspace-subdir');
assert.equal(currentCwd, 'mock-workspace-subdir', 'chdir() must change working directory');

// 7. Verify uptime() calculation
// start time was captured as 1000000000n (1s). Advance simulated time by 2.5 seconds (2500000000n).
simulatedTimeBigInt = 3500000000n;
assert.equal(processInstance.uptime(), 2.5, 'uptime() must return elapsed seconds based on hrtime.bigint');

// 8. Verify resource and memory metrics
const cpu = processInstance.cpuUsage();
assert.deepEqual(cpu, { user: 12000, system: 3000 }, 'cpuUsage() must return user and system microseconds');
const threadCpu = processInstance.threadCpuUsage();
assert.deepEqual(threadCpu, { user: 6000, system: 1500 }, 'threadCpuUsage() must return thread CPU usage');
const mem = processInstance.memoryUsage();
assert.deepEqual(mem, { rss: 33554432, heapTotal: 16777216, heapUsed: 8388608 }, 'memoryUsage() must return memory metrics');
assert.equal(processInstance.availableMemory(), 8589934592, 'availableMemory() must return available bytes');
assert.equal(processInstance.constrainedMemory(), 0, 'constrainedMemory() must return 0 or limit');
assert.deepEqual(processInstance.resourceUsage(), { maxRSS: 32768 }, 'resourceUsage() must return resource usage struct');

// 9. Verify POSIX identity methods
assert.equal(processInstance.getgid(), 1000, 'getgid() must return GID');
assert.equal(processInstance.getegid(), 1000, 'getegid() must return effective GID');
assert.equal(processInstance.getuid(), 1000, 'getuid() must return UID');
assert.equal(processInstance.geteuid(), 1000, 'geteuid() must return effective UID');
assert.deepEqual(processInstance.getgroups(), [1000, 4, 27], 'getgroups() must return group IDs');

// 10. Verify lifecycle and process control methods
processInstance.kill(999, 'SIGTERM');
assert.deepEqual(killedProcess, { pid: 999, signal: 'SIGTERM' }, 'kill() must forward to bare-os.kill');

processInstance.exit(42);
assert.equal(exitedCode, 42, 'exit() must call Bare.exit with code');

processInstance.suspend();
assert.equal(suspended, true, 'suspend() must call Bare.suspend');

processInstance.resume();
assert.equal(resumed, true, 'resume() must call Bare.resume');

processInstance.abort();
assert.equal(aborted, true, 'abort() must call bare-abort');

// 11. Verify event forwarding from Bare
let receivedExitCode = null;
processInstance.on('exit', (code) => {
  receivedExitCode = code;
});
mockBare.emit('exit', 0);
assert.equal(receivedExitCode, 0, 'Lifecycle event exit must be forwarded from Bare');

let receivedException = null;
processInstance.on('uncaughtException', (err) => {
  receivedException = err;
});
const testError = new Error('test uncaught error');
mockBare.emit('uncaughtException', testError);
assert.equal(receivedException, testError, 'uncaughtException must be forwarded from Bare');

// 12. Verify nextTick asynchronous scheduling
const nextTickResult = await new Promise((resolve) => {
  processInstance.nextTick((a, b, c) => {
    resolve({ a, b, c });
  }, 1, 'two', { three: 3 });
});
assert.deepEqual(nextTickResult, { a: 1, b: 'two', c: { three: 3 } }, 'nextTick() must execute microtask with passed arguments');

// 13. Verify bare inspection symbol
const inspectFn = processInstance[Symbol.for('bare.inspect')];
assert.equal(typeof inspectFn, 'function', 'process must implement bare.inspect symbol method');
const inspected = inspectFn.call(processInstance);
assert.equal(inspected.platform, 'linux', 'inspected object must contain platform');
assert.equal(inspected.arch, 'x64', 'inspected object must contain arch');
assert.equal(inspected.pid, 4242, 'inspected object must contain pid');

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

オリジンシーダー

匿名