Exemplo
ws 8.21.3: WebSocketServer
Amostra verificada para npm ws 8.21.3: WebSocketServer. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: assert WebSocketServer initializes…
sha256:b63c15525b0b1789e9035f51fb518f460758705c779648dd279ac6ee99f5a1fc
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
- 2
- 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 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-23 |
| 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-07 |
Caso
HOW- Objetivo
- verify ws.WebSocketServer in pkg:npm/ws@8.21.3
- Pacotes
- Símbolos
-
- ws.WebSocketServer
- Criado
- 2026-08-23T06:05:22Z
Contrato
- assert WebSocketServer initializes with port and host
- assert WebSocketServer emits connection event with socket and incoming request
- assert WebSocketServer tracks active clients in clients Set and removes on disconnect
- assert WebSocketServer broadcasts messages to multiple connected clients
- assert WebSocketServer closes cleanly and emits close event
Arquivos
- PROMPT.md
- csx.json
- index.mjs
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
Código-fonte
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 ws.WebSocketServer in pkg:npm/ws@8.21.3
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/ws@8.21.3
Demonstrate these symbols/APIs:
- ws.WebSocketServer
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.
{"case":{"caseId":"case:sha256:42637672fd8bc0e232a8257eac9423bc17372a231178775f2495719fa748d7b7","contract":["assert WebSocketServer initializes with port and host","assert WebSocketServer emits connection event with socket and incoming request","assert WebSocketServer tracks active clients in clients Set and removes on disconnect","assert WebSocketServer broadcasts messages to multiple connected clients","assert WebSocketServer closes cleanly and emits close event"],"goal":"verify ws.WebSocketServer in pkg:npm/ws@8.21.3","kind":"HOW","packages":["pkg:npm/ws@8.21.3"],"schemaVersion":1,"symbols":["ws.WebSocketServer"]},"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/ws@8.21.3"],"schemaVersion":1,"subject":"pkg:npm/ws@8.21.3","symbols":["ws.WebSocketServer"],"verifierAdapter":"node-typescript@1"}
import WebSocket, { WebSocketServer } from 'ws';
/**
* Creates and starts a WebSocketServer instance.
* @param {import('ws').ServerOptions} [options]
* @param {Function} [callback]
* @returns {WebSocketServer}
*/
export function createWebSocketServer(options = {}, callback) {
return new WebSocketServer(options, callback);
}
/**
* Broadcasts a message to all connected clients on a WebSocketServer.
* @param {WebSocketServer} server
* @param {any} data
* @param {object} [options]
*/
export function broadcast(server, data, options) {
for (const client of server.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data, options);
}
}
}
export { WebSocket, WebSocketServer };
{
"name": "sample-ws-websocketserver",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-ws-websocketserver",
"version": "1.0.0",
"dependencies": {
"ws": "8.21.3"
}
},
"node_modules/ws": {
"version": "8.21.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
"integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
{
"name": "sample-ws-websocketserver",
"version": "1.0.0",
"private": true,
"type": "module",
"dependencies": {
"ws": "8.21.3"
}
}
{
"schemaVersion": 1,
"goal": "verify ws.WebSocketServer in pkg:npm/ws@8.21.3",
"kind": "HOW",
"packages": [
"pkg:npm/ws@8.21.3"
],
"symbols": [
"ws.WebSocketServer"
]
}
import assert from 'node:assert/strict';
import { createWebSocketServer, broadcast, WebSocket, WebSocketServer } from '../index.mjs';
// 1. assert WebSocketServer initializes with port and host
{
const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
await new Promise((resolve) => wss.on('listening', resolve));
const address = wss.address();
assert.strictEqual(typeof address, 'object');
assert.strictEqual(address.address, '127.0.0.1');
assert.ok(address.port > 0);
await new Promise((resolve) => wss.close(resolve));
}
// 2. assert WebSocketServer emits connection event with socket and incoming request
{
const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
await new Promise((resolve) => wss.on('listening', resolve));
const port = wss.address().port;
let serverReqUrl = null;
let serverWs = null;
wss.on('connection', (ws, req) => {
serverWs = ws;
serverReqUrl = req.url;
});
const client = new WebSocket(`ws://127.0.0.1:${port}/test-path?param=val`);
await new Promise((resolve, reject) => {
client.on('open', resolve);
client.on('error', reject);
});
assert.ok(serverWs !== null);
assert.strictEqual(serverWs.readyState, WebSocket.OPEN);
assert.strictEqual(serverReqUrl, '/test-path?param=val');
client.close();
await new Promise((r) => client.on('close', r));
await new Promise((r) => wss.close(r));
}
// 3. assert WebSocketServer tracks active clients in clients Set and removes on disconnect
{
const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
await new Promise((resolve) => wss.on('listening', resolve));
const port = wss.address().port;
assert.strictEqual(wss.clients.size, 0);
const client1 = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise((r) => client1.on('open', r));
assert.strictEqual(wss.clients.size, 1);
const client2 = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise((r) => client2.on('open', r));
assert.strictEqual(wss.clients.size, 2);
client1.close();
await new Promise((r) => client1.on('close', r));
await new Promise((r) => setTimeout(r, 50));
assert.strictEqual(wss.clients.size, 1);
client2.close();
await new Promise((r) => client2.on('close', r));
await new Promise((r) => setTimeout(r, 50));
assert.strictEqual(wss.clients.size, 0);
await new Promise((r) => wss.close(r));
}
// 4. assert WebSocketServer broadcasts messages to multiple connected clients
{
const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
await new Promise((resolve) => wss.on('listening', resolve));
const port = wss.address().port;
const client1 = new WebSocket(`ws://127.0.0.1:${port}`);
const client2 = new WebSocket(`ws://127.0.0.1:${port}`);
await Promise.all([
new Promise((r) => client1.on('open', r)),
new Promise((r) => client2.on('open', r))
]);
const msgPromise1 = new Promise((resolve) => client1.on('message', (d) => resolve(d.toString('utf8'))));
const msgPromise2 = new Promise((resolve) => client2.on('message', (d) => resolve(d.toString('utf8'))));
broadcast(wss, 'broadcast payload');
const [res1, res2] = await Promise.all([msgPromise1, msgPromise2]);
assert.strictEqual(res1, 'broadcast payload');
assert.strictEqual(res2, 'broadcast payload');
client1.close();
client2.close();
await Promise.all([
new Promise((r) => client1.on('close', r)),
new Promise((r) => client2.on('close', r))
]);
await new Promise((r) => wss.close(r));
}
// 5. assert WebSocketServer closes cleanly and emits close event
{
const wss = createWebSocketServer({ host: '127.0.0.1', port: 0 });
await new Promise((resolve) => wss.on('listening', resolve));
let closeEventFired = false;
wss.on('close', () => {
closeEventFired = true;
});
await new Promise((resolve) => wss.close(resolve));
assert.strictEqual(closeEventFired, true);
}
console.log('Contract tests passed successfully.');
Seeder de origem
anônimo