CodeSampleX

示例

tar-stream 3.2.2

已验证示例 — npm tar-stream 3.2.2. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: tar.pack() and tar.extract() round-trip directory, file, binary, and…

sha256:07f18eba430d3fc91b58556db37f37d8c58976d7965bc437c16bfa42997f6bc3

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-11-22

案例

HOW
目标
verify pkg:npm/tar-stream@3.2.2
包
环境
node 22.23.2
创建时间
2026-11-22T19:03:35Z

契约

  1. tar.pack() and tar.extract() round-trip directory, file, binary, and symlink entries in 512-byte blocks terminated by a 1024-byte zero block while preserving mode, mtime, size, and linkname
  2. pack.entry({ name, size }) streams multi-chunk payloads when written byte count matches header.size and fails with a Size mismatch error on both pack and sink when written bytes differ
  3. pack.entry() throws already finalized or destroyed after pack.finalize(), and writing a non-empty body to a directory entry emits No body allowed for this entry
  4. tar.pack() and tar.extract() encode and decode PAX headers for paths exceeding 100 bytes, non-ASCII UTF-8 filenames, and custom header.pax metadata
  5. tar.extract() supports async iteration yielding entry streams with sequential header, offset, byteOffset, and payload bytes
  6. tar.extract() rejects corrupted headers with Invalid tar header, truncated streams with Unexpected end of data, and propagates errors passed to the entry next callback to both extract and the active entry stream

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.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 pkg:npm/tar-stream@3.2.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tar-stream@3.2.2
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:102ec4b528a65f1224dc602efb97f82ce741104b5752d224b112613585d0ff70","constraints":{"executionContext":"node"},"contract":["tar.pack() and tar.extract() round-trip directory, file, binary, and symlink entries in 512-byte blocks terminated by a 1024-byte zero block while preserving mode, mtime, size, and linkname","pack.entry({ name, size }) streams multi-chunk payloads when written byte count matches header.size and fails with a Size mismatch error on both pack and sink when written bytes differ","pack.entry() throws already finalized or destroyed after pack.finalize(), and writing a non-empty body to a directory entry emits No body allowed for this entry","tar.pack() and tar.extract() encode and decode PAX headers for paths exceeding 100 bytes, non-ASCII UTF-8 filenames, and custom header.pax metadata","tar.extract() supports async iteration yielding entry streams with sequential header, offset, byteOffset, and payload bytes","tar.extract() rejects corrupted headers with Invalid tar header, truncated streams with Unexpected end of data, and propagates errors passed to the entry next callback to both extract and the active entry stream"],"goal":"verify pkg:npm/tar-stream@3.2.2","kind":"HOW","packages":["pkg:npm/tar-stream@3.2.2"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/tar-stream@3.2.2"],"schemaVersion":1,"subject":"pkg:npm/tar-stream@3.2.2","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "tar-stream-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "tar-stream-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tar-stream": "3.2.2"
      }
    },
    "node_modules/b4a": {
      "version": "1.9.0",
      "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz",
      "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==",
      "license": "Apache-2.0",
      "peerDependencies": {
        "react-native-b4a": "*"
      },
      "peerDependenciesMeta": {
        "react-native-b4a": {
          "optional": true
        }
      }
    },
    "node_modules/bare-buffer": {
      "version": "3.7.3",
      "resolved": "https://registry.npmjs.org/bare-buffer/-/bare-buffer-3.7.3.tgz",
      "integrity": "sha512-77owW16RX6YgdOzddHtM0oGz8wsd0/F9k/0coz6TPmjUHnr/9FwWODVMNKwyYWM/a/ESdTum855nfQxnsKUygA==",
      "license": "Apache-2.0",
      "engines": {
        "bare": ">=1.20.0"
      }
    },
    "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.5",
      "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.5.tgz",
      "integrity": "sha512-5gborbd4IEFpnyqAiwD0tl6sH9fvPvIaK2hdM8DXU+xAMxSB7B3D3D04CD21k4T5C6u5Oxw3iajkBQhNLxINKg==",
      "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-path": {
      "version": "3.1.3",
      "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.3.tgz",
      "integrity": "sha512-8r+FVU/o4zcFmpCDqbqAYhHHbtXPP+cyZKo7DRGRWc7OLlNs4TMaSQEpXL/sIdzyEG0M7RHw4B7xYMGrTc+qrg==",
      "license": "Apache-2.0"
    },
    "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-url": {
      "version": "2.5.8",
      "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.8.tgz",
      "integrity": "sha512-G5KTe5Bj6z5pqIxcn3lWlIFIv0rkXbccx0T0Xuf7t4RapfSWvFlcVbrwYXxFZ00PC4lp57OCIk6uXP/r3GbpDw==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-buffer": "^3.0.0",
        "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/tar-stream": {
      "version": "3.2.2",
      "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.2.tgz",
      "integrity": "sha512-+8NeqHRjQWH9nYlwo2gamAMImZCVzI4UoEgDpWorBt9OEfppiZn+uSkskzQKPWIZyji/C8fpWO7u69G0DX0tbg==",
      "license": "MIT",
      "dependencies": {
        "b4a": "^1.9.0",
        "bare-fs": "^4.8.2",
        "fast-fifo": "^1.3.2",
        "streamx": "^2.28.1"
      }
    },
    "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": "tar-stream-sample",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "tar-stream": "3.2.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/tar-stream@3.2.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tar-stream@3.2.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict'

const tar = require('tar-stream')

function collectReadable (stream) {
  return new Promise((resolve, reject) => {
    const chunks = []
    stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
    stream.on('error', reject)
    stream.on('end', () => resolve(Buffer.concat(chunks)))
  })
}

function packEntries (entries) {
  const pack = tar.pack()
  const outputPromise = collectReadable(pack)

  for (const item of entries) {
    if (item.chunks) {
      const sink = pack.entry(item.header)
      for (const chunk of item.chunks) {
        sink.write(chunk)
      }
      sink.end()
    } else if (item.body !== undefined) {
      pack.entry(item.header, item.body)
    } else {
      pack.entry(item.header)
    }
  }

  pack.finalize()
  return outputPromise
}

function extractArchive (archiveBuffer, opts) {
  return new Promise((resolve, reject) => {
    const extract = tar.extract(opts)
    const entries = []

    extract.on('entry', (header, stream, next) => {
      const chunks = []
      stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
      stream.on('error', (err) => next(err))
      stream.on('end', () => {
        entries.push({
          header,
          body: Buffer.concat(chunks)
        })
        next()
      })
      stream.resume()
    })

    extract.on('error', reject)
    extract.on('finish', () => resolve(entries))

    extract.end(archiveBuffer)
  })
}

async function extractArchiveAsync (archiveBuffer, opts) {
  const extract = tar.extract(opts)
  const entries = []

  extract.end(archiveBuffer)

  for await (const entry of extract) {
    const chunks = []
    for await (const chunk of entry) {
      chunks.push(Buffer.from(chunk))
    }
    entries.push({
      header: entry.header,
      offset: entry.offset,
      body: Buffer.concat(chunks)
    })
  }

  return entries
}

module.exports = {
  collectReadable,
  packEntries,
  extractArchive,
  extractArchiveAsync
}
test/contract.js
'use strict'

const assert = require('node:assert/strict')
const tar = require('tar-stream')
const {
  collectReadable,
  packEntries,
  extractArchive,
  extractArchiveAsync
} = require('../src/index')

async function testRoundTripEntries () {
  const fixedDate = new Date(Date.UTC(2025, 0, 15, 12, 0, 0))
  const archive = await packEntries([
    {
      header: { name: 'docs/', type: 'directory', mtime: fixedDate }
    },
    {
      header: { name: 'docs/hello.txt', mode: 0o640, mtime: fixedDate },
      body: 'hello tar-stream'
    },
    {
      header: { name: 'docs/latest.txt', type: 'symlink', linkname: 'hello.txt', mtime: fixedDate }
    },
    {
      header: { name: 'docs/binary.bin', mtime: fixedDate },
      body: Buffer.from([0x00, 0x01, 0xfe, 0xff])
    }
  ])

  assert.equal(archive.length % 512, 0)
  assert.ok(archive.subarray(archive.length - 1024).equals(Buffer.alloc(1024)))

  const extracted = await extractArchive(archive)
  assert.equal(extracted.length, 4)

  assert.equal(extracted[0].header.name, 'docs/')
  assert.equal(extracted[0].header.type, 'directory')
  assert.equal(extracted[0].header.mode, 0o755)
  assert.equal(extracted[0].header.size, 0)
  assert.equal(extracted[0].body.length, 0)

  assert.equal(extracted[1].header.name, 'docs/hello.txt')
  assert.equal(extracted[1].header.type, 'file')
  assert.equal(extracted[1].header.mode, 0o640)
  assert.equal(extracted[1].header.size, 16)
  assert.equal(extracted[1].header.mtime.getTime(), fixedDate.getTime())
  assert.equal(extracted[1].body.toString('utf8'), 'hello tar-stream')

  assert.equal(extracted[2].header.name, 'docs/latest.txt')
  assert.equal(extracted[2].header.type, 'symlink')
  assert.equal(extracted[2].header.linkname, 'hello.txt')
  assert.equal(extracted[2].header.size, 0)

  assert.equal(extracted[3].header.name, 'docs/binary.bin')
  assert.ok(extracted[3].body.equals(Buffer.from([0x00, 0x01, 0xfe, 0xff])))
}

async function testStreamingSinkAndSizeMismatch () {
  const archive = await packEntries([
    {
      header: { name: 'streamed.txt', size: 11 },
      chunks: [Buffer.from('first '), Buffer.from('chunk')]
    }
  ])

  const extracted = await extractArchive(archive)
  assert.equal(extracted.length, 1)
  assert.equal(extracted[0].header.name, 'streamed.txt')
  assert.equal(extracted[0].body.toString('utf8'), 'first chunk')

  const badPack = tar.pack()
  const packErrPromise = collectReadable(badPack).then(
    () => null,
    (err) => err
  )
  const sinkErrPromise = new Promise((resolve) => {
    const sink = badPack.entry({ name: 'mismatch.txt', size: 10 }, (err) => resolve(err))
    sink.on('error', () => {})
    sink.end(Buffer.from('short'))
  })

  const [packErr, sinkErr] = await Promise.all([packErrPromise, sinkErrPromise])
  assert.ok(packErr instanceof Error)
  assert.match(packErr.message, /Size mismatch/)
  assert.ok(sinkErr instanceof Error)
  assert.match(sinkErr.message, /Size mismatch/)
}

async function testFinalizeAndVoidEntryGuards () {
  const pack = tar.pack()
  const done = collectReadable(pack)
  pack.finalize()
  assert.throws(
    () => pack.entry({ name: 'late.txt' }, 'nope'),
    /already finalized or destroyed/
  )
  const emptyArchive = await done
  assert.equal(emptyArchive.length, 1024)

  const dirPack = tar.pack()
  const dirPackErr = collectReadable(dirPack).then(
    () => null,
    (err) => err
  )
  const voidErr = await new Promise((resolve) => {
    const sink = dirPack.entry({ name: 'folder/', type: 'directory' })
    sink.on('error', resolve)
    sink.write(Buffer.from('unexpected'))
  })
  assert.match(voidErr.message, /No body allowed for this entry/)
  await dirPackErr
}

async function testPaxHeadersLongAndUtf8Paths () {
  const longName = 'nested/' + 'segment-'.repeat(16) + 'file.txt'
  const utf8Name = 'notes/café-αβγ.txt'

  const archive = await packEntries([
    {
      header: { name: longName, pax: { comment: 'long-path-entry' } },
      body: 'long content'
    },
    {
      header: { name: utf8Name },
      body: 'utf8 content'
    }
  ])

  const extracted = await extractArchive(archive)
  assert.equal(extracted.length, 2)
  assert.equal(extracted[0].header.name, longName)
  assert.equal(extracted[0].header.pax.comment, 'long-path-entry')
  assert.equal(extracted[0].body.toString('utf8'), 'long content')

  assert.equal(extracted[1].header.name, utf8Name)
  assert.equal(extracted[1].body.toString('utf8'), 'utf8 content')
}

async function testAsyncIteration () {
  const archive = await packEntries([
    { header: { name: 'a.txt' }, body: 'alpha' },
    { header: { name: 'b.txt' }, body: 'beta' }
  ])

  const entries = await extractArchiveAsync(archive)
  assert.equal(entries.length, 2)
  assert.equal(entries[0].header.name, 'a.txt')
  assert.equal(entries[0].offset, 0)
  assert.equal(entries[0].header.byteOffset, 512)
  assert.equal(entries[0].body.toString('utf8'), 'alpha')

  assert.equal(entries[1].header.name, 'b.txt')
  assert.equal(entries[1].offset, 1024)
  assert.equal(entries[1].header.byteOffset, 1536)
  assert.equal(entries[1].body.toString('utf8'), 'beta')
}

async function testExtractErrorHandling () {
  const corrupt = Buffer.alloc(512, 0x41)
  await assert.rejects(
    () => extractArchive(corrupt),
    /Invalid tar header/
  )

  const valid = await packEntries([
    { header: { name: 'truncated.txt' }, body: 'complete payload data' }
  ])
  const truncated = valid.subarray(0, 512 + 5)
  await assert.rejects(
    () => extractArchive(truncated),
    /Unexpected end of data/
  )

  let sourceErr = null
  await assert.rejects(
    () => new Promise((resolve, reject) => {
      const extract = tar.extract()
      extract.on('entry', (header, stream, next) => {
        stream.on('error', (err) => { sourceErr = err })
        next(new Error('entry rejected'))
      })
      extract.on('error', reject)
      extract.on('finish', resolve)
      extract.end(valid)
    }),
    /entry rejected/
  )
  assert.ok(sourceErr instanceof Error)
  assert.match(sourceErr.message, /entry rejected/)
}

async function main () {
  await testRoundTripEntries()
  await testStreamingSinkAndSizeMismatch()
  await testFinalizeAndVoidEntryGuards()
  await testPaxHeadersLongAndUtf8Paths()
  await testAsyncIteration()
  await testExtractErrorHandling()
  console.log('contract passed')
}

main().catch((err) => {
  console.error(err)
  process.exitCode = 1
})

原始种子者

匿名