CodeSampleX

Exemplo

whatwg-url 16.0.1

Amostra verificada para npm whatwg-url 16.0.1. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: URL constructor parses absolute URLs and…

sha256:80f6c9546b218dbf495727bcdb22e1e0eae1021c65ce815035419a55289bcf18

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

Ambientes das execuções de verificação

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

Caso

HOW
Objetivo
verify pkg:npm/whatwg-url@16.0.1
Pacotes
Ambiente
node 22.23.2
Criado
2026-08-28T09:55:48Z

Contrato

  1. URL constructor parses absolute URLs and provides standard component accessors (protocol, username, password, host, hostname, port, pathname, search, hash, origin, href)
  2. mutating URL properties updates the serialized href and origin accordingly
  3. URL.canParse and URL.parse validate URL strings without throwing exceptions
  4. URL constructor throws TypeError on invalid or unparseable URL strings
  5. URLSearchParams provides query parameter lookup, addition, modification, deletion, and serialization
  6. mutating searchParams on a URL instance updates the URL search query and href
  7. parseURL parses URL strings into WHATWG URL record objects and serializeURL produces standard URL strings

Arquivos

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

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 pkg:npm/whatwg-url@16.0.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/whatwg-url@16.0.1

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:c99b0de7cfef83e2cadda056764f4b92247bffa4ff209bb7a2463dcef1ac952e","contract":["URL constructor parses absolute URLs and provides standard component accessors (protocol, username, password, host, hostname, port, pathname, search, hash, origin, href)","mutating URL properties updates the serialized href and origin accordingly","URL.canParse and URL.parse validate URL strings without throwing exceptions","URL constructor throws TypeError on invalid or unparseable URL strings","URLSearchParams provides query parameter lookup, addition, modification, deletion, and serialization","mutating searchParams on a URL instance updates the URL search query and href","parseURL parses URL strings into WHATWG URL record objects and serializeURL produces standard URL strings"],"goal":"verify pkg:npm/whatwg-url@16.0.1","kind":"HOW","packages":["pkg:npm/whatwg-url@16.0.1"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/whatwg-url@16.0.1"],"schemaVersion":1,"subject":"pkg:npm/whatwg-url@16.0.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-whatwg-url",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-whatwg-url",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "whatwg-url": "16.0.1"
      }
    },
    "node_modules/@exodus/bytes": {
      "version": "1.15.1",
      "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",
      "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",
      "license": "MIT",
      "engines": {
        "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
      },
      "peerDependencies": {
        "@noble/hashes": "^1.8.0 || ^2.0.0"
      },
      "peerDependenciesMeta": {
        "@noble/hashes": {
          "optional": true
        }
      }
    },
    "node_modules/punycode": {
      "version": "2.3.1",
      "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
      "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/tr46": {
      "version": "6.0.0",
      "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",
      "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",
      "license": "MIT",
      "dependencies": {
        "punycode": "^2.3.1"
      },
      "engines": {
        "node": ">=20"
      }
    },
    "node_modules/webidl-conversions": {
      "version": "8.0.1",
      "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
      "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=20"
      }
    },
    "node_modules/whatwg-url": {
      "version": "16.0.1",
      "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",
      "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",
      "license": "MIT",
      "dependencies": {
        "@exodus/bytes": "^1.11.0",
        "tr46": "^6.0.0",
        "webidl-conversions": "^8.0.1"
      },
      "engines": {
        "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-whatwg-url",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "description": "Clean-room verification sample for whatwg-url",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "whatwg-url": "16.0.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/whatwg-url@16.0.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/whatwg-url@16.0.1"
  ]
}
src/index.js
import {
  URL,
  URLSearchParams,
  parseURL,
  basicURLParse,
  serializeURL,
  serializeURLOrigin
} from 'whatwg-url';

/**
 * Creates and returns a new URL instance.
 * @param {string} input
 * @param {string|URL} [base]
 * @returns {URL}
 */
export function createURL(input, base) {
  return new URL(input, base);
}

/**
 * Checks if a given input and optional base can be parsed into a valid URL.
 * @param {string} input
 * @param {string|URL} [base]
 * @returns {boolean}
 */
export function isValidURL(input, base) {
  return URL.canParse(input, base);
}

/**
 * Parses a URL string safely without throwing, returning a URL instance or null.
 * @param {string} input
 * @param {string|URL} [base]
 * @returns {URL|null}
 */
export function parseURLString(input, base) {
  return URL.parse(input, base);
}

/**
 * Creates and returns a new URLSearchParams instance.
 * @param {string|string[][]|Record<string, string>|URLSearchParams} [init]
 * @returns {URLSearchParams}
 */
export function createSearchParams(init) {
  return new URLSearchParams(init);
}

/**
 * Parses an input string into a WHATWG URL record and serializes it back to string.
 * @param {string} input
 * @returns {string|null}
 */
export function parseAndSerialize(input) {
  const record = parseURL(input);
  if (!record) return null;
  return serializeURL(record);
}

export {
  URL,
  URLSearchParams,
  parseURL,
  basicURLParse,
  serializeURL,
  serializeURLOrigin
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  URL,
  URLSearchParams,
  parseURL,
  basicURLParse,
  serializeURL,
  serializeURLOrigin,
  createURL,
  isValidURL,
  parseURLString,
  createSearchParams,
  parseAndSerialize
} from '../src/index.js';

// 1. URL constructor parses absolute URLs and provides standard component accessors
const url = createURL('https://example.com:8443/api/v1/items?filter=active&sort=desc#section2');
assert.ok(url instanceof URL, 'url must be an instance of URL');
assert.equal(url.protocol, 'https:', 'protocol must match');
assert.equal(url.hostname, 'example.com', 'hostname must match');
assert.equal(url.port, '8443', 'port must match');
assert.equal(url.host, 'example.com:8443', 'host must match');
assert.equal(url.pathname, '/api/v1/items', 'pathname must match');
assert.equal(url.search, '?filter=active&sort=desc', 'search query must match');
assert.equal(url.hash, '#section2', 'hash fragment must match');
assert.equal(url.origin, 'https://example.com:8443', 'origin must match');
assert.equal(url.href, 'https://example.com:8443/api/v1/items?filter=active&sort=desc#section2', 'href must match');

// 2. Mutating URL properties updates the serialized href and origin accordingly
url.pathname = '/api/v2/users';
url.search = '?page=2';
url.port = '9443';
assert.equal(url.pathname, '/api/v2/users', 'updated pathname must reflect');
assert.equal(url.search, '?page=2', 'updated search must reflect');
assert.equal(url.port, '9443', 'updated port must reflect');
assert.equal(url.origin, 'https://example.com:9443', 'updated origin must reflect port change');
assert.equal(url.href, 'https://example.com:9443/api/v2/users?page=2#section2', 'updated href must reflect all changes');

// 3. URL.canParse and URL.parse validate URL strings without throwing exceptions
assert.equal(isValidURL('https://example.com/valid/path'), true, 'valid absolute URL should return true');
assert.equal(isValidURL('/relative/path', 'https://example.com'), true, 'valid relative URL with base should return true');
assert.equal(isValidURL('https://'), false, 'incomplete special scheme URL should return false');
assert.equal(isValidURL('https://example.com:invalidport'), false, 'invalid port in URL should return false');
assert.equal(isValidURL('not a valid url'), false, 'unparseable string should return false');

const parsedValid = parseURLString('https://example.com/test');
assert.ok(parsedValid instanceof URL, 'parseURLString must return URL instance for valid input');
assert.equal(parsedValid.pathname, '/test', 'parsed pathname must match');

const parsedInvalid = parseURLString('https://');
assert.equal(parsedInvalid, null, 'parseURLString must return null for invalid URL');

// 4. URL constructor throws TypeError on invalid or unparseable URL strings
assert.throws(
  () => {
    createURL('https://');
  },
  {
    name: 'TypeError'
  },
  'URL constructor must throw TypeError on invalid URL string'
);

// 5. URLSearchParams provides query parameter lookup, addition, modification, deletion, and serialization
const params = createSearchParams('category=books&tag=scifi&tag=fantasy');
assert.ok(params instanceof URLSearchParams, 'params must be instance of URLSearchParams');
assert.equal(params.get('category'), 'books', 'get returns single value');
assert.deepEqual(params.getAll('tag'), ['scifi', 'fantasy'], 'getAll returns array of all values');
assert.equal(params.has('category'), true, 'has returns true for existing key');
assert.equal(params.has('author'), false, 'has returns false for missing key');

params.append('tag', 'cyberpunk');
assert.deepEqual(params.getAll('tag'), ['scifi', 'fantasy', 'cyberpunk'], 'append adds additional value');

params.set('category', 'novels');
assert.equal(params.get('category'), 'novels', 'set replaces existing value');

params.delete('tag');
assert.equal(params.has('tag'), false, 'delete removes key');
assert.equal(params.toString(), 'category=novels', 'toString serializes parameters');

// 6. Mutating searchParams on a URL instance updates the URL search query and href
const searchUrl = createURL('https://example.com/search?q=javascript');
searchUrl.searchParams.set('page', '1');
searchUrl.searchParams.append('sort', 'asc');
assert.equal(searchUrl.search, '?q=javascript&page=1&sort=asc', 'search query must update when searchParams mutate');
assert.equal(searchUrl.href, 'https://example.com/search?q=javascript&page=1&sort=asc', 'href must update when searchParams mutate');

// 7. parseURL parses URL strings into WHATWG URL record objects and serializeURL produces standard URL strings
const urlRecord = parseURL('https://example.com:3000/data?id=123#view');
assert.ok(urlRecord !== null, 'parseURL must return non-null record for valid URL');
assert.equal(serializeURL(urlRecord), 'https://example.com:3000/data?id=123#view', 'serializeURL must match original URL');
assert.equal(serializeURLOrigin(urlRecord), 'https://example.com:3000', 'serializeURLOrigin must match origin');

const helperSerialized = parseAndSerialize('https://example.com/path');
assert.equal(helperSerialized, 'https://example.com/path', 'parseAndSerialize helper must serialize correctly');
assert.equal(parseAndSerialize('https://'), null, 'parseAndSerialize must return null on invalid input');

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

Seeder de origem

anônimo