CodeSampleX

Ejemplo

@humanfs/core 0.19.2: HfsImpl

Muestra verificada para npm @humanfs/core 0.19.2: HfsImpl. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:47d54d9f66b31e16bc83ee52c622b8bcf6eced8321efde05b62ba9decaf76024

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 linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

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

Caso

HOW
Objetivo
verify HfsImpl in pkg:npm/%40humanfs/core@0.19.2
Paquetes
Símbolos
  • HfsImpl
Creado
2026-08-30T22:28:06Z

Contrato

  1. HfsImpl custom implementation supports write, bytes, append, and size operations
  2. HfsImpl directory management supports createDirectory, isDirectory, isFile, list, delete, and deleteAll
  3. HfsImpl supports file and directory copy and move operations
  4. HfsImpl tracks lastModified timestamps for files and directories
  5. Hfs validates HfsImpl interface contracts and raises NoSuchMethodError for unimplemented optional methods
  6. HfsImpl handles path normalization and URL instances across driver methods

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 HfsImpl in pkg:npm/%40humanfs/core@0.19.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40humanfs/core@0.19.2
Demonstrate these symbols/APIs:
  - HfsImpl

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:ca27ca895d78e1093e95e1b6c4a84a048af212fd29625b634b04fbdd5bb8a1bd","contract":["HfsImpl custom implementation supports write, bytes, append, and size operations","HfsImpl directory management supports createDirectory, isDirectory, isFile, list, delete, and deleteAll","HfsImpl supports file and directory copy and move operations","HfsImpl tracks lastModified timestamps for files and directories","Hfs validates HfsImpl interface contracts and raises NoSuchMethodError for unimplemented optional methods","HfsImpl handles path normalization and URL instances across driver methods"],"goal":"verify HfsImpl in pkg:npm/%40humanfs/core@0.19.2","kind":"HOW","packages":["pkg:npm/%40humanfs/core@0.19.2"],"schemaVersion":1,"symbols":["HfsImpl"]},"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/%40humanfs/core@0.19.2"],"schemaVersion":1,"subject":"pkg:npm/%40humanfs/core@0.19.2","symbols":["HfsImpl"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-humanfs-core-hfsimpl",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-humanfs-core-hfsimpl",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@humanfs/core": "0.19.2"
      }
    },
    "node_modules/@humanfs/core": {
      "version": "0.19.2",
      "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
      "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",
      "license": "Apache-2.0",
      "dependencies": {
        "@humanfs/types": "^0.15.0"
      },
      "engines": {
        "node": ">=18.18.0"
      }
    },
    "node_modules/@humanfs/types": {
      "version": "0.15.0",
      "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",
      "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",
      "license": "Apache-2.0",
      "engines": {
        "node": ">=18.18.0"
      }
    }
  }
}
package.json
{
  "name": "sample-humanfs-core-hfsimpl",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for HfsImpl from @humanfs/core",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@humanfs/core": "0.19.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify HfsImpl in pkg:npm/%40humanfs/core@0.19.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40humanfs/core@0.19.2"
  ],
  "symbols": [
    "HfsImpl"
  ]
}
src/index.js
/**
 * @fileoverview Custom implementation of HfsImpl interface for @humanfs/core.
 */

/**
 * Normalizes a path string or URL to a standardized absolute Unix-style path.
 * @param {string|URL} p
 * @returns {string}
 */
function normalizePath(p) {
  let str = p instanceof URL ? p.pathname : String(p);
  str = str.replace(/\\/g, '/').replace(/\/+/g, '/');
  if (str.length > 1 && str.endsWith('/')) {
    str = str.slice(0, -1);
  }
  return str.startsWith('/') ? str : `/${str}`;
}

/**
 * Ensures parent directories are tracked in the directories set.
 * @param {Set<string>} dirSet
 * @param {Map<string, Date>} mtimes
 * @param {string} path
 */
function ensureParentDirs(dirSet, mtimes, path) {
  const parts = path.split('/').filter(Boolean);
  let cur = '';
  for (let i = 0; i < parts.length - 1; i++) {
    cur += `/${parts[i]}`;
    if (!dirSet.has(cur)) {
      dirSet.add(cur);
      mtimes.set(cur, new Date());
    }
  }
}

/**
 * In-memory filesystem driver implementing the full HfsImpl interface.
 * @implements {import('@humanfs/types').HfsImpl}
 */
class MemoryHfsImpl {
  constructor() {
    /** @type {Map<string, Uint8Array>} */
    this.files = new Map();
    /** @type {Set<string>} */
    this.directories = new Set(['/']);
    /** @type {Map<string, Date>} */
    this.mtimes = new Map([['/', new Date()]]);
  }

  /**
   * Writes byte contents to a file.
   * @param {string|URL} filePath
   * @param {Uint8Array} data
   * @returns {Promise<void>}
   */
  async write(filePath, data) {
    const p = normalizePath(filePath);
    this.files.set(p, new Uint8Array(data));
    this.mtimes.set(p, new Date());
    ensureParentDirs(this.directories, this.mtimes, p);
  }

  /**
   * Reads byte contents from a file.
   * @param {string|URL} filePath
   * @returns {Promise<Uint8Array|undefined>}
   */
  async bytes(filePath) {
    const p = normalizePath(filePath);
    const data = this.files.get(p);
    return data ? new Uint8Array(data) : undefined;
  }

  /**
   * Appends byte contents to a file.
   * @param {string|URL} filePath
   * @param {Uint8Array} data
   * @returns {Promise<void>}
   */
  async append(filePath, data) {
    const p = normalizePath(filePath);
    const existing = this.files.get(p);
    if (!existing) {
      await this.write(p, data);
      return;
    }
    const combined = new Uint8Array(existing.length + data.length);
    combined.set(existing, 0);
    combined.set(data, existing.length);
    this.files.set(p, combined);
    this.mtimes.set(p, new Date());
  }

  /**
   * Checks if a file exists.
   * @param {string|URL} filePath
   * @returns {Promise<boolean>}
   */
  async isFile(filePath) {
    const p = normalizePath(filePath);
    return this.files.has(p);
  }

  /**
   * Checks if a directory exists.
   * @param {string|URL} dirPath
   * @returns {Promise<boolean>}
   */
  async isDirectory(dirPath) {
    const p = normalizePath(dirPath);
    return this.directories.has(p);
  }

  /**
   * Creates a directory.
   * @param {string|URL} dirPath
   * @returns {Promise<void>}
   */
  async createDirectory(dirPath) {
    const p = normalizePath(dirPath);
    this.directories.add(p);
    this.mtimes.set(p, new Date());
    ensureParentDirs(this.directories, this.mtimes, p);
  }

  /**
   * Deletes a file or empty directory.
   * @param {string|URL} fileOrDirPath
   * @returns {Promise<boolean>}
   */
  async delete(fileOrDirPath) {
    const p = normalizePath(fileOrDirPath);
    if (this.files.has(p)) {
      this.files.delete(p);
      this.mtimes.delete(p);
      return true;
    }
    if (this.directories.has(p)) {
      const prefix = p === '/' ? '/' : `${p}/`;
      for (const d of this.directories) {
        if (d !== p && d.startsWith(prefix)) return false;
      }
      for (const f of this.files.keys()) {
        if (f.startsWith(prefix)) return false;
      }
      this.directories.delete(p);
      this.mtimes.delete(p);
      return true;
    }
    return false;
  }

  /**
   * Deletes a file or directory recursively.
   * @param {string|URL} fileOrDirPath
   * @returns {Promise<boolean>}
   */
  async deleteAll(fileOrDirPath) {
    const p = normalizePath(fileOrDirPath);
    let deleted = false;
    if (this.files.has(p)) {
      this.files.delete(p);
      this.mtimes.delete(p);
      deleted = true;
    }
    const prefix = p === '/' ? '/' : `${p}/`;
    for (const f of Array.from(this.files.keys())) {
      if (f.startsWith(prefix)) {
        this.files.delete(f);
        this.mtimes.delete(f);
        deleted = true;
      }
    }
    for (const d of Array.from(this.directories)) {
      if (d === p || d.startsWith(prefix)) {
        this.directories.delete(d);
        this.mtimes.delete(d);
        deleted = true;
      }
    }
    return deleted;
  }

  /**
   * Lists entries in a directory.
   * @param {string|URL} dirPath
   * @returns {AsyncIterable<import('@humanfs/types').HfsDirectoryEntry>}
   */
  async *list(dirPath) {
    const p = normalizePath(dirPath);
    const prefix = p === '/' ? '/' : `${p}/`;
    /** @type {Map<string, import('@humanfs/types').HfsDirectoryEntry>} */
    const entries = new Map();

    for (const d of this.directories) {
      if (d !== p && d.startsWith(prefix)) {
        const rest = d.slice(prefix.length);
        const name = rest.split('/')[0];
        if (name && !entries.has(name)) {
          entries.set(name, {
            name,
            isDirectory: true,
            isFile: false,
            isSymlink: false
          });
        }
      }
    }

    for (const f of this.files.keys()) {
      if (f.startsWith(prefix)) {
        const rest = f.slice(prefix.length);
        const parts = rest.split('/');
        if (parts.length === 1) {
          entries.set(parts[0], {
            name: parts[0],
            isDirectory: false,
            isFile: true,
            isSymlink: false
          });
        } else if (!entries.has(parts[0])) {
          entries.set(parts[0], {
            name: parts[0],
            isDirectory: true,
            isFile: false,
            isSymlink: false
          });
        }
      }
    }

    for (const entry of entries.values()) {
      yield entry;
    }
  }

  /**
   * Returns the size of a file in bytes.
   * @param {string|URL} filePath
   * @returns {Promise<number|undefined>}
   */
  async size(filePath) {
    const p = normalizePath(filePath);
    const file = this.files.get(p);
    return file ? file.length : undefined;
  }

  /**
   * Returns the last modified date of a file or directory.
   * @param {string|URL} fileOrDirPath
   * @returns {Promise<Date|undefined>}
   */
  async lastModified(fileOrDirPath) {
    const p = normalizePath(fileOrDirPath);
    return this.mtimes.get(p);
  }

  /**
   * Copies a file from source to destination.
   * @param {string|URL} source
   * @param {string|URL} destination
   * @returns {Promise<void>}
   */
  async copy(source, destination) {
    const src = normalizePath(source);
    const dest = normalizePath(destination);
    const data = this.files.get(src);
    if (!data) {
      throw new Error(`Source file "${src}" does not exist.`);
    }
    await this.write(dest, data);
  }

  /**
   * Copies a directory tree recursively.
   * @param {string|URL} source
   * @param {string|URL} destination
   * @returns {Promise<void>}
   */
  async copyAll(source, destination) {
    const src = normalizePath(source);
    const dest = normalizePath(destination);
    if (this.files.has(src)) {
      await this.copy(src, dest);
      return;
    }
    if (!this.directories.has(src)) {
      throw new Error(`Source "${src}" does not exist.`);
    }
    await this.createDirectory(dest);
    const prefix = src === '/' ? '/' : `${src}/`;
    for (const [f, data] of this.files.entries()) {
      if (f.startsWith(prefix)) {
        const subPath = f.slice(prefix.length);
        const targetPath = `${dest}/${subPath}`;
        await this.write(targetPath, data);
      }
    }
  }

  /**
   * Moves a file from source to destination.
   * @param {string|URL} source
   * @param {string|URL} destination
   * @returns {Promise<void>}
   */
  async move(source, destination) {
    await this.copy(source, destination);
    await this.delete(source);
  }

  /**
   * Moves a file or directory tree from source to destination.
   * @param {string|URL} source
   * @param {string|URL} destination
   * @returns {Promise<void>}
   */
  async moveAll(source, destination) {
    await this.copyAll(source, destination);
    await this.deleteAll(source);
  }
}

/**
 * A minimal read-only HfsImpl implementation omitting write, append, delete methods.
 * @implements {Partial<import('@humanfs/types').HfsImpl>}
 */
class ReadOnlyHfsImpl {
  /**
   * @param {Record<string, Uint8Array>} initialFiles
   */
  constructor(initialFiles = {}) {
    /** @type {Map<string, Uint8Array>} */
    this.files = new Map();
    for (const [k, v] of Object.entries(initialFiles)) {
      this.files.set(normalizePath(k), v);
    }
  }

  /**
   * @param {string|URL} filePath
   * @returns {Promise<Uint8Array|undefined>}
   */
  async bytes(filePath) {
    const p = normalizePath(filePath);
    const data = this.files.get(p);
    return data ? new Uint8Array(data) : undefined;
  }

  /**
   * @param {string|URL} filePath
   * @returns {Promise<boolean>}
   */
  async isFile(filePath) {
    const p = normalizePath(filePath);
    return this.files.has(p);
  }

  /**
   * @param {string|URL} filePath
   * @returns {Promise<number|undefined>}
   */
  async size(filePath) {
    const p = normalizePath(filePath);
    const file = this.files.get(p);
    return file ? file.length : undefined;
  }
}

module.exports = {
  normalizePath,
  MemoryHfsImpl,
  ReadOnlyHfsImpl
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { Hfs } from '@humanfs/core';

const require = createRequire(import.meta.url);
const { normalizePath, MemoryHfsImpl, ReadOnlyHfsImpl } = require('../src/index.js');

const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();

// 1. HfsImpl custom implementation supports write, bytes, append, and size operations
{
  const impl = new MemoryHfsImpl();
  const hfs = new Hfs({ impl });

  const data1 = textEncoder.encode('Hello ');
  const data2 = textEncoder.encode('World!');

  await impl.write('/data/greeting.txt', data1);
  assert.equal(await impl.size('/data/greeting.txt'), 6);

  const readBytes1 = await impl.bytes('/data/greeting.txt');
  assert.equal(textDecoder.decode(readBytes1), 'Hello ');

  await impl.append('/data/greeting.txt', data2);
  assert.equal(await impl.size('/data/greeting.txt'), 12);

  const readBytes2 = await impl.bytes('/data/greeting.txt');
  assert.equal(textDecoder.decode(readBytes2), 'Hello World!');

  // Calling via Hfs delegates to HfsImpl
  const textFromHfs = await hfs.text('/data/greeting.txt');
  assert.equal(textFromHfs, 'Hello World!');
}

// 2. HfsImpl directory management supports createDirectory, isDirectory, isFile, list, delete, and deleteAll
{
  const impl = new MemoryHfsImpl();

  await impl.createDirectory('/project/src');
  await impl.createDirectory('/project/dist');
  await impl.write('/project/src/app.js', textEncoder.encode('console.log(1);'));
  await impl.write('/project/src/util.js', textEncoder.encode('export const x = 1;'));
  await impl.write('/project/readme.md', textEncoder.encode('# Readme'));

  assert.equal(await impl.isDirectory('/project'), true);
  assert.equal(await impl.isDirectory('/project/src'), true);
  assert.equal(await impl.isFile('/project/src/app.js'), true);
  assert.equal(await impl.isFile('/project/src'), false);
  assert.equal(await impl.isDirectory('/project/src/app.js'), false);

  const entries = [];
  for await (const entry of impl.list('/project')) {
    entries.push(entry.name);
  }
  assert.deepEqual(entries.sort(), ['dist', 'readme.md', 'src'].sort());

  const srcEntries = [];
  for await (const entry of impl.list('/project/src')) {
    srcEntries.push(entry.name);
  }
  assert.deepEqual(srcEntries.sort(), ['app.js', 'util.js'].sort());

  // Non-empty directory delete returns false
  assert.equal(await impl.delete('/project/src'), false);

  // File delete returns true
  assert.equal(await impl.delete('/project/src/app.js'), true);
  assert.equal(await impl.isFile('/project/src/app.js'), false);

  // Recursive delete removes whole subtree
  assert.equal(await impl.deleteAll('/project'), true);
  assert.equal(await impl.isDirectory('/project'), false);
  assert.equal(await impl.isFile('/project/readme.md'), false);
}

// 3. HfsImpl supports file and directory copy and move operations
{
  const impl = new MemoryHfsImpl();

  await impl.write('/source/file.txt', textEncoder.encode('original content'));
  await impl.copy('/source/file.txt', '/dest/file-copy.txt');

  assert.equal(await impl.isFile('/source/file.txt'), true);
  assert.equal(await impl.isFile('/dest/file-copy.txt'), true);
  assert.equal(textDecoder.decode(await impl.bytes('/dest/file-copy.txt')), 'original content');

  await impl.move('/source/file.txt', '/dest/file-moved.txt');
  assert.equal(await impl.isFile('/source/file.txt'), false);
  assert.equal(await impl.isFile('/dest/file-moved.txt'), true);

  // Copy directory tree
  await impl.write('/tree/a.txt', textEncoder.encode('a'));
  await impl.write('/tree/sub/b.txt', textEncoder.encode('b'));

  await impl.copyAll('/tree', '/tree-copy');
  assert.equal(textDecoder.decode(await impl.bytes('/tree-copy/a.txt')), 'a');
  assert.equal(textDecoder.decode(await impl.bytes('/tree-copy/sub/b.txt')), 'b');

  // Move directory tree
  await impl.moveAll('/tree', '/tree-moved');
  assert.equal(await impl.isDirectory('/tree'), false);
  assert.equal(textDecoder.decode(await impl.bytes('/tree-moved/a.txt')), 'a');
  assert.equal(textDecoder.decode(await impl.bytes('/tree-moved/sub/b.txt')), 'b');
}

// 4. HfsImpl tracks lastModified timestamps for files and directories
{
  const impl = new MemoryHfsImpl();
  await impl.write('/time/test.txt', textEncoder.encode('time check'));

  const fileMtime = await impl.lastModified('/time/test.txt');
  assert.ok(fileMtime instanceof Date);
  assert.ok(Date.now() - fileMtime.getTime() < 60000);

  const dirMtime = await impl.lastModified('/time');
  assert.ok(dirMtime instanceof Date);

  const missingMtime = await impl.lastModified('/nonexistent');
  assert.equal(missingMtime, undefined);
}

// 5. Hfs validates HfsImpl interface contracts and raises NoSuchMethodError for unimplemented optional methods
{
  const readOnlyImpl = new ReadOnlyHfsImpl({
    '/data/config.json': textEncoder.encode('{"active":true}')
  });

  const hfs = new Hfs({ impl: readOnlyImpl });

  // Implemented read methods work
  assert.equal(await hfs.isFile('/data/config.json'), true);
  const jsonContent = await hfs.json('/data/config.json');
  assert.deepEqual(jsonContent, { active: true });

  // Unimplemented optional write/append/delete methods throw NoSuchMethodError when invoked on Hfs
  await assert.rejects(async () => {
    await hfs.write('/data/new.txt', 'fail');
  }, (err) => {
    return err.name === 'Error' && err.message.includes('NoSuchMethodError') || err.message.includes('does not exist on impl');
  });

  await assert.rejects(async () => {
    await hfs.append('/data/config.json', 'fail');
  }, (err) => {
    return err.message.includes('does not exist on impl');
  });

  await assert.rejects(async () => {
    await hfs.delete('/data/config.json');
  }, (err) => {
    return err.message.includes('does not exist on impl');
  });
}

// 6. HfsImpl handles path normalization and URL instances across driver methods
{
  const impl = new MemoryHfsImpl();
  const fileUrl = new URL('file:///app/config.yaml');

  await impl.write(fileUrl, textEncoder.encode('key: value'));
  assert.equal(await impl.isFile('/app/config.yaml'), true);
  assert.equal(await impl.isFile(fileUrl), true);

  const content = await impl.bytes(fileUrl);
  assert.equal(textDecoder.decode(content), 'key: value');

  assert.equal(normalizePath('foo/bar'), '/foo/bar');
  assert.equal(normalizePath('/foo/bar/'), '/foo/bar');
  assert.equal(normalizePath(new URL('file:///workspace/test.js')), '/workspace/test.js');
}

console.log('All HfsImpl contract tests passed successfully.');

Seeder de origen

anónimo