CodeSampleX

Beispiel

ws 8.21.1: WebSocketServer.handleUpgrade

Verifiziertes Beispiel für npm ws 8.21.1: WebSocketServer.handleUpgrade. Der Vertrag lief auf node 22 · linux alpine/x64 · docker und bestand.

sha256:7555d3a4217171289f8d31492334c2dc52ff00e60e4f40ad759b3c8b19902db5

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 npm

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1
Pakete
Symbole
  • WebSocketServer.handleUpgrade
Erstellt
2026-08-30T22:30:46Z

Contract

  1. WebSocketServer initialized with noServer: true throws when calling address()
  2. WebSocketServer.handleUpgrade completes HTTP upgrade handshake over duplex socket
  3. WebSocket client successfully sends and receives messages after handleUpgrade connection
  4. handleUpgrade callback receives the upgraded WebSocket instance and request object

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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 WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ws@8.21.1
Demonstrate these symbols/APIs:
  - WebSocketServer.handleUpgrade

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:4904ae573f9c73db5e7ede6d0b704c1c0b3dcd1f23e52d55e4ccd3e1153f8dce","contract":["WebSocketServer initialized with noServer: true throws when calling address()","WebSocketServer.handleUpgrade completes HTTP upgrade handshake over duplex socket","WebSocket client successfully sends and receives messages after handleUpgrade connection","handleUpgrade callback receives the upgraded WebSocket instance and request object"],"goal":"verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1","kind":"HOW","packages":["pkg:npm/ws@8.21.1"],"schemaVersion":1,"symbols":["WebSocketServer.handleUpgrade"]},"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.1"],"schemaVersion":1,"subject":"pkg:npm/ws@8.21.1","symbols":["WebSocketServer.handleUpgrade"],"verifierAdapter":"node-typescript@1"}
index.mjs
import http from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';

/**
 * Creates an HTTP server and pairs it with a WebSocketServer using handleUpgrade.
 * @param {Object} [options]
 * @param {string} [options.wsPath='/ws'] - Path for WebSocket upgrade requests
 * @returns {{ server: http.Server, wss: WebSocketServer, close: () => Promise<void> }}
 */
export function createUpgradableServer(options = {}) {
  const wsPath = options.wsPath || '/ws';
  const wss = new WebSocketServer({ noServer: true });

  const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('OK');
  });

  server.on('upgrade', (request, socket, head) => {
    const url = new URL(request.url, 'http://localhost');
    if (url.pathname === wsPath) {
      wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
      });
    } else {
      socket.destroy();
    }
  });

  const close = () => {
    return new Promise((resolve) => {
      wss.close(() => {
        server.close(() => {
          resolve();
        });
      });
    });
  };

  return { server, wss, close };
}

export { WebSocketServer, WebSocket };
package-lock.json
{
  "name": "sample-ws-handle-upgrade",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-ws-handle-upgrade",
      "version": "1.0.0",
      "dependencies": {
        "ws": "8.21.1"
      }
    },
    "node_modules/ws": {
      "version": "8.21.1",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
      "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
      "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
        }
      }
    }
  }
}
package.json
{
  "name": "sample-ws-handle-upgrade",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "ws": "8.21.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ws@8.21.1"
  ],
  "symbols": [
    "WebSocketServer.handleUpgrade"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createUpgradableServer, WebSocketServer, WebSocket } from '../index.mjs';

async function runContractTests() {
  // Test 1: WebSocketServer initialized with noServer: true throws when address() is called
  const standaloneWss = new WebSocketServer({ noServer: true });
  assert.equal(standaloneWss.options.noServer, true, 'noServer option should be true');
  assert.throws(
    () => standaloneWss.address(),
    /The server is operating in "noServer" mode/,
    'address() should throw in noServer mode'
  );
  standaloneWss.close();

  // Test 2: Set up upgradable server and verify handleUpgrade completes upgrade handshake
  const { server, wss, close } = createUpgradableServer({ wsPath: '/custom-ws' });

  await new Promise((resolve, reject) => {
    server.listen(0, '127.0.0.1', () => resolve());
    server.on('error', reject);
  });

  const address = server.address();
  const port = address.port;

  let connectionHandled = false;
  let receivedServerRequest = null;
  let serverWsInstance = null;

  wss.on('connection', (ws, req) => {
    connectionHandled = true;
    serverWsInstance = ws;
    receivedServerRequest = req;

    ws.on('message', (data) => {
      const msg = data.toString();
      if (msg === 'ping') {
        ws.send('pong');
      }
    });
  });

  // Test 3: Client connects and sends/receives messages
  const clientWs = new WebSocket(`ws://127.0.0.1:${port}/custom-ws`);

  await new Promise((resolve, reject) => {
    clientWs.on('open', resolve);
    clientWs.on('error', reject);
  });

  assert.equal(connectionHandled, true, 'wss should have emitted connection event via handleUpgrade');
  assert.ok(serverWsInstance instanceof WebSocket, 'server WebSocket should be an instance of WebSocket');
  assert.ok(receivedServerRequest, 'server should receive the upgraded HTTP request object');
  assert.equal(receivedServerRequest.url, '/custom-ws', 'request URL should match upgrade path');

  const responsePromise = new Promise((resolve) => {
    clientWs.on('message', (data) => {
      resolve(data.toString());
    });
  });

  clientWs.send('ping');
  const response = await responsePromise;
  assert.equal(response, 'pong', 'Client should receive pong message from server');

  clientWs.close();
  await new Promise((resolve) => clientWs.on('close', resolve));

  // Test 4: Verify non-matching path is rejected / destroyed
  const invalidClient = new WebSocket(`ws://127.0.0.1:${port}/other-path`);
  const rejected = await new Promise((resolve) => {
    invalidClient.on('error', () => resolve(true));
    invalidClient.on('close', () => resolve(true));
    invalidClient.on('open', () => resolve(false));
  });
  assert.equal(rejected, true, 'Connection to non-matching route should be closed');

  await close();
  console.log('All contract assertions passed.');
}

runContractTests().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Ursprungs-Seeder

anonym