CodeSampleX

Exemplo

sanitize-filename 1.6.4: sanitize

Amostra verificada para npm sanitize-filename 1.6.4: sanitize. O contrato rodou em node 22 · linux debian/x64 · docker e passou.

sha256:55d5e2c587f0a81e869fa3600666d32cc5c4a529bb0b7361ee1dff06915f02c0

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-09-01

Caso

HOW
Objetivo
verify sanitize in pkg:npm/sanitize-filename@1.6.4
Pacotes
Símbolos
  • sanitize
Criado
2026-09-01T11:41:30Z

Contrato

  1. sanitize removes illegal filename characters including slashes, colons, angle brackets, and question marks
  2. sanitize replaces illegal characters with a custom replacement string when specified in options
  3. sanitize replaces illegal characters dynamically using a custom replacement function
  4. sanitize removes Windows reserved filenames such as COM1, AUX, and NUL
  5. sanitize strips trailing dots and spaces that are invalid on Windows filesystems
  6. sanitize truncates filenames exceeding 255 bytes to 255 bytes using UTF-8 aware truncation
  7. sanitize leaves already valid filenames unchanged
  8. sanitize throws an Error when passed a non-string input

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.js

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 sanitize in pkg:npm/sanitize-filename@1.6.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/sanitize-filename@1.6.4
Demonstrate these symbols/APIs:
  - sanitize

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:ad5d5e2fe766105b34e4e48c10558a67e92ebfa009c07507e4acc7c8790b79d3","contract":["sanitize removes illegal filename characters including slashes, colons, angle brackets, and question marks","sanitize replaces illegal characters with a custom replacement string when specified in options","sanitize replaces illegal characters dynamically using a custom replacement function","sanitize removes Windows reserved filenames such as COM1, AUX, and NUL","sanitize strips trailing dots and spaces that are invalid on Windows filesystems","sanitize truncates filenames exceeding 255 bytes to 255 bytes using UTF-8 aware truncation","sanitize leaves already valid filenames unchanged","sanitize throws an Error when passed a non-string input"],"goal":"verify sanitize in pkg:npm/sanitize-filename@1.6.4","kind":"HOW","packages":["pkg:npm/sanitize-filename@1.6.4"],"schemaVersion":1,"symbols":["sanitize"]},"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/sanitize-filename@1.6.4"],"schemaVersion":1,"subject":"pkg:npm/sanitize-filename@1.6.4","symbols":["sanitize"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-sanitize-filename",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-sanitize-filename",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "sanitize-filename": "1.6.4"
      }
    },
    "node_modules/sanitize-filename": {
      "version": "1.6.4",
      "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.4.tgz",
      "integrity": "sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==",
      "license": "WTFPL OR ISC",
      "dependencies": {
        "truncate-utf8-bytes": "^1.0.0"
      }
    },
    "node_modules/truncate-utf8-bytes": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz",
      "integrity": "sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==",
      "license": "WTFPL",
      "dependencies": {
        "utf8-byte-length": "^1.0.1"
      }
    },
    "node_modules/utf8-byte-length": {
      "version": "1.0.5",
      "resolved": "https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.5.tgz",
      "integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",
      "license": "(WTFPL OR MIT)"
    }
  }
}
package.json
{
  "name": "sample-sanitize-filename",
  "version": "1.0.0",
  "private": true,
  "description": "verify sanitize in pkg:npm/sanitize-filename@1.6.4",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "sanitize-filename": "1.6.4"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify sanitize in pkg:npm/sanitize-filename@1.6.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/sanitize-filename@1.6.4"
  ],
  "symbols": [
    "sanitize"
  ]
}
src/index.js
'use strict';

const sanitize = require('sanitize-filename');

/**
 * Sanitizes a string to make it safe for use as a filename.
 * @param {string} input - The input string to sanitize.
 * @param {object} [options={}] - Options object for sanitization.
 * @param {string|Function} [options.replacement=""] - Replacement for invalid characters.
 * @returns {string} Sanitized filename string.
 */
function sanitizeFileName(input, options = {}) {
  return sanitize(input, options);
}

module.exports = {
  sanitize,
  sanitizeFileName,
};
test/contract.js
'use strict';

const assert = require('node:assert/strict');
const { sanitize, sanitizeFileName } = require('../src/index.js');

// 1. sanitize removes illegal filename characters including slashes, colons, angle brackets, and question marks
{
  const input = 'report/2026:09<draft>?v1*bar|qux"test.pdf';
  const result = sanitize(input);
  assert.equal(result, 'report202609draftv1barquxtest.pdf');

  const helperResult = sanitizeFileName('hello/world\\test');
  assert.equal(helperResult, 'helloworldtest');
}

// 2. sanitize replaces illegal characters with a custom replacement string when specified in options
{
  const input = 'foo/bar:baz?qux';
  const result = sanitize(input, { replacement: '_' });
  assert.equal(result, 'foo_bar_baz_qux');

  const hyphenResult = sanitizeFileName('chapter:1/intro', { replacement: '-' });
  assert.equal(hyphenResult, 'chapter-1-intro');
}

// 3. sanitize replaces illegal characters dynamically using a custom replacement function
{
  const input = 'a/b:c';
  const result = sanitize(input, {
    replacement: (match) => (match === '/' ? '-' : '_'),
  });
  assert.equal(result, 'a-b_c');
}

// 4. sanitize removes Windows reserved filenames such as COM1, AUX, and NUL
{
  assert.equal(sanitize('COM1'), '');
  assert.equal(sanitize('aux.txt'), '');
  assert.equal(sanitize('NUL'), '');
  assert.equal(sanitize('prn.dat'), '');
  assert.equal(sanitize('lpt1.log'), '');
}

// 5. sanitize strips trailing dots and spaces that are invalid on Windows filesystems
{
  assert.equal(sanitize('filename...'), 'filename');
  assert.equal(sanitize('filename   '), 'filename');
  assert.equal(sanitize('filename. . .'), 'filename');
}

// 6. sanitize truncates filenames exceeding 255 bytes to 255 bytes using UTF-8 aware truncation
{
  const longName = 'a'.repeat(300);
  const result = sanitize(longName);
  assert.equal(result.length, 255);
  assert.equal(result, 'a'.repeat(255));

  // Multi-byte UTF-8 characters
  const multiByte = '한'.repeat(100); // each '한' is 3 bytes (300 bytes total)
  const multiByteResult = sanitize(multiByte);
  const byteLength = Buffer.byteLength(multiByteResult, 'utf8');
  assert.ok(byteLength <= 255, 'Truncated byte length should not exceed 255');
  assert.equal(byteLength, 255);
  assert.equal(multiByteResult.length, 85); // 85 * 3 = 255 bytes
}

// 7. sanitize leaves already valid filenames unchanged
{
  const valid = 'my-valid_filename.123.tar.gz';
  assert.equal(sanitize(valid), valid);
  assert.equal(sanitizeFileName('document.pdf'), 'document.pdf');
}

// 8. sanitize throws an Error when passed a non-string input
{
  assert.throws(
    () => {
      sanitize(12345);
    },
    {
      name: 'Error',
      message: 'Input must be string',
    },
    'Should throw when passed a number'
  );

  assert.throws(
    () => {
      sanitize(null);
    },
    {
      name: 'Error',
      message: 'Input must be string',
    },
    'Should throw when passed null'
  );

  assert.throws(
    () => {
      sanitize(undefined);
    },
    {
      name: 'Error',
      message: 'Input must be string',
    },
    'Should throw when passed undefined'
  );

  assert.throws(
    () => {
      sanitize({});
    },
    {
      name: 'Error',
      message: 'Input must be string',
    },
    'Should throw when passed an object'
  );
}

Seeder de origem

anônimo