CodeSampleX

示例

socket.io-parser 4.2.7: encode and decode event packet with Encoder and Decoder

已验证示例 — npm socket.io-parser 4.2.7: encode and decode event packet with Encoder and Decoder. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:a9d7ec427d9b8ce8793119bf25aedc4352c352752515218698ce678fd8b4403e

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
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-27

案例

HOW
目标
encode and decode event packet with Encoder and Decoder
包
符号
  • Decoder
  • Encoder
  • PacketType
创建时间
2026-08-27T12:23:29Z

契约

  1. PacketType exports standard protocol packet constants CONNECT, DISCONNECT, EVENT, ACK, CONNECT_ERROR, BINARY_EVENT, and BINARY_ACK
  2. Encoder.prototype.encode encodes a plain event packet into an array containing a single wire-format string
  3. Encoder.prototype.encode supports custom namespaces, packet IDs, and JSON payloads
  4. Decoder.prototype.add decodes wire-format string packets and emits 'decoded' event with packet type, namespace, id, and data
  5. Encoder and Decoder round-trip binary payloads by deconstructing into placeholders and reconstructing Buffers
  6. Decoder decodes ACK, CONNECT, and CONNECT_ERROR packets with appropriate payload formats
  7. Decoder throws an error when fed an unknown packet type or invalid reserved event payload

文件

  • 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: encode and decode event packet with Encoder and Decoder
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/socket.io-parser@4.2.7
Demonstrate these symbols/APIs:
  - Decoder
  - Encoder
  - PacketType

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:7d7f2f0bccc5aa17eedf862a5a9ec3133a412b3726d72dc447069d4a12137468","contract":["PacketType exports standard protocol packet constants CONNECT, DISCONNECT, EVENT, ACK, CONNECT_ERROR, BINARY_EVENT, and BINARY_ACK","Encoder.prototype.encode encodes a plain event packet into an array containing a single wire-format string","Encoder.prototype.encode supports custom namespaces, packet IDs, and JSON payloads","Decoder.prototype.add decodes wire-format string packets and emits 'decoded' event with packet type, namespace, id, and data","Encoder and Decoder round-trip binary payloads by deconstructing into placeholders and reconstructing Buffers","Decoder decodes ACK, CONNECT, and CONNECT_ERROR packets with appropriate payload formats","Decoder throws an error when fed an unknown packet type or invalid reserved event payload"],"goal":"encode and decode event packet with Encoder and Decoder","kind":"HOW","packages":["pkg:npm/socket.io-parser@4.2.7"],"schemaVersion":1,"symbols":["Decoder","Encoder","PacketType"]},"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/socket.io-parser@4.2.7"],"schemaVersion":1,"subject":"pkg:npm/socket.io-parser@4.2.7","symbols":["Decoder","Encoder","PacketType"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-socket-io-parser",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-socket-io-parser",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "socket.io-parser": "4.2.7"
      }
    },
    "node_modules/@socket.io/component-emitter": {
      "version": "3.1.2",
      "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
      "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
      "license": "MIT"
    },
    "node_modules/debug": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
      "license": "MIT",
      "dependencies": {
        "ms": "^2.1.3"
      },
      "engines": {
        "node": ">=6.0"
      },
      "peerDependenciesMeta": {
        "supports-color": {
          "optional": true
        }
      }
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    },
    "node_modules/socket.io-parser": {
      "version": "4.2.7",
      "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz",
      "integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==",
      "license": "MIT",
      "dependencies": {
        "@socket.io/component-emitter": "~3.1.0",
        "debug": "~4.4.1"
      },
      "engines": {
        "node": ">=10.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-socket-io-parser",
  "version": "1.0.0",
  "description": "encode and decode event packet with Encoder and Decoder",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "socket.io-parser": "4.2.7"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "encode and decode event packet with Encoder and Decoder",
  "kind": "HOW",
  "packages": [
    "pkg:npm/socket.io-parser@4.2.7"
  ],
  "symbols": [
    "Decoder",
    "Encoder",
    "PacketType"
  ]
}
src/index.js
const { Encoder, Decoder, PacketType, protocol } = require('socket.io-parser');

/**
 * Encodes a socket.io packet into wire-format chunks using Encoder.
 *
 * @param {object} packet - The packet object (type, nsp, id, data).
 * @param {function} [replacer] - Optional JSON replacer function.
 * @returns {Array<string|Buffer>} Array of wire-format chunks.
 */
function encodePacket(packet, replacer) {
  const encoder = new Encoder(replacer);
  return encoder.encode(packet);
}

/**
 * Decodes wire-format chunks back into a packet object using Decoder.
 *
 * @param {string|Buffer|Array<string|Buffer>} chunks - Wire-format chunk or array of chunks.
 * @param {object|function} [options] - Decoder options or reviver function.
 * @returns {Promise<object>} Promise resolving to the decoded packet.
 */
function decodePacket(chunks, options) {
  return new Promise((resolve, reject) => {
    const decoder = new Decoder(options);
    let resolved = false;

    decoder.on('decoded', (packet) => {
      resolved = true;
      resolve(packet);
    });

    try {
      const chunkList = Array.isArray(chunks) ? chunks : [chunks];
      for (const chunk of chunkList) {
        decoder.add(chunk);
      }
    } catch (err) {
      decoder.destroy();
      return reject(err);
    }

    if (!resolved && !Array.isArray(chunks)) {
      // Single chunk provided but packet requires more attachments
    }
  });
}

/**
 * Creates a standard EVENT packet object.
 *
 * @param {string} eventName - Name of the event.
 * @param {*} data - Payload data.
 * @param {object} [options={}] - Optional nsp and id.
 * @returns {object} Formatted EVENT packet.
 */
function createEventPacket(eventName, data, options = {}) {
  return {
    type: PacketType.EVENT,
    nsp: options.nsp || '/',
    id: options.id !== undefined ? options.id : undefined,
    data: data !== undefined ? [eventName, data] : [eventName]
  };
}

/**
 * Creates a standard ACK packet object.
 *
 * @param {number} id - Packet ack id.
 * @param {Array<*>} data - Ack data array.
 * @param {object} [options={}] - Optional nsp.
 * @returns {object} Formatted ACK packet.
 */
function createAckPacket(id, data = [], options = {}) {
  return {
    type: PacketType.ACK,
    nsp: options.nsp || '/',
    id: id,
    data: data
  };
}

module.exports = {
  Encoder,
  Decoder,
  PacketType,
  protocol,
  encodePacket,
  decodePacket,
  createEventPacket,
  createAckPacket
};
test/contract.js
const assert = require('assert');
const {
  Encoder,
  Decoder,
  PacketType,
  protocol,
  encodePacket,
  decodePacket,
  createEventPacket,
  createAckPacket
} = require('../src/index');

async function runContractTests() {
  // 1. PacketType constants match standard protocol values
  {
    assert.strictEqual(PacketType.CONNECT, 0);
    assert.strictEqual(PacketType.DISCONNECT, 1);
    assert.strictEqual(PacketType.EVENT, 2);
    assert.strictEqual(PacketType.ACK, 3);
    assert.strictEqual(PacketType.CONNECT_ERROR, 4);
    assert.strictEqual(PacketType.BINARY_EVENT, 5);
    assert.strictEqual(PacketType.BINARY_ACK, 6);
    assert.strictEqual(protocol, 5);
  }

  // 2. Encoder encodes plain event packet into wire-format string array
  {
    const packet = createEventPacket('greet', { message: 'hello world' });
    const encoded = encodePacket(packet);

    assert(Array.isArray(encoded), 'Encoder output must be an array');
    assert.strictEqual(encoded.length, 1, 'Non-binary event must encode to 1 chunk');
    assert.strictEqual(typeof encoded[0], 'string', 'Encoded chunk must be a string');
    assert.strictEqual(encoded[0], '2["greet",{"message":"hello world"}]');
  }

  // 3. Encoder supports custom namespace and message id
  {
    const packet = createEventPacket('join', { room: 'lobby' }, { nsp: '/admin', id: 101 });
    const encoded = encodePacket(packet);

    assert(Array.isArray(encoded));
    assert.strictEqual(encoded.length, 1);
    assert.strictEqual(encoded[0], '2/admin,101["join",{"room":"lobby"}]');
  }

  // 4. Decoder decodes wire-format string into structured packet object via decoded event
  {
    const wireString = '2/admin,101["join",{"room":"lobby"}]';
    const decoded = await decodePacket(wireString);

    assert.strictEqual(decoded.type, PacketType.EVENT);
    assert.strictEqual(decoded.nsp, '/admin');
    assert.strictEqual(decoded.id, 101);
    assert.deepStrictEqual(decoded.data, ['join', { room: 'lobby' }]);
  }

  // 5. Encoder and Decoder round-trip binary event packets with Buffer attachments
  {
    const sampleBuffer = Buffer.from([10, 20, 30, 40, 50]);
    const packet = {
      type: PacketType.EVENT,
      nsp: '/',
      id: 7,
      data: ['file_chunk', { chunkIndex: 1, buffer: sampleBuffer }]
    };

    const encoded = encodePacket(packet);
    assert(Array.isArray(encoded));
    assert.strictEqual(encoded.length, 2, 'Binary packet must produce placeholder string and 1 buffer');
    assert.strictEqual(typeof encoded[0], 'string');
    assert(encoded[0].startsWith('51-7['), 'Binary header should specify 1 attachment and id 7');
    assert(Buffer.isBuffer(encoded[1]), 'Second chunk must be raw Buffer');
    assert.deepStrictEqual(encoded[1], sampleBuffer);

    const decoded = await decodePacket(encoded);
    assert.strictEqual(decoded.type, PacketType.EVENT);
    assert.strictEqual(decoded.nsp, '/');
    assert.strictEqual(decoded.id, 7);
    assert.strictEqual(decoded.data[0], 'file_chunk');
    assert.strictEqual(decoded.data[1].chunkIndex, 1);
    assert(Buffer.isBuffer(decoded.data[1].buffer), 'Reconstructed payload must contain Buffer');
    assert.deepStrictEqual(decoded.data[1].buffer, sampleBuffer);
  }

  // 6. Decoder decodes ACK, CONNECT, and CONNECT_ERROR packets correctly
  {
    // ACK packet
    const ackPacket = createAckPacket(42, ['received', true], { nsp: '/custom' });
    const encodedAck = encodePacket(ackPacket);
    assert.strictEqual(encodedAck[0], '3/custom,42["received",true]');
    const decodedAck = await decodePacket(encodedAck[0]);
    assert.strictEqual(decodedAck.type, PacketType.ACK);
    assert.strictEqual(decodedAck.id, 42);
    assert.strictEqual(decodedAck.nsp, '/custom');
    assert.deepStrictEqual(decodedAck.data, ['received', true]);

    // CONNECT packet
    const decodedConnect = await decodePacket('0/custom,{"token":"auth123"}');
    assert.strictEqual(decodedConnect.type, PacketType.CONNECT);
    assert.strictEqual(decodedConnect.nsp, '/custom');
    assert.deepStrictEqual(decodedConnect.data, { token: 'auth123' });

    // CONNECT_ERROR packet
    const decodedError = await decodePacket('4{"message":"Unauthorized"}');
    assert.strictEqual(decodedError.type, PacketType.CONNECT_ERROR);
    assert.strictEqual(decodedError.nsp, '/');
    assert.deepStrictEqual(decodedError.data, { message: 'Unauthorized' });
  }

  // 7. Decoder throws Error on unknown packet type or invalid payload format
  {
    assert.throws(
      () => {
        const decoder = new Decoder();
        decoder.add('9["invalid_type"]');
      },
      (err) => {
        return err instanceof Error && /unknown packet type/.test(err.message);
      },
      'Unknown packet type must throw Error'
    );

    assert.throws(
      () => {
        const decoder = new Decoder();
        decoder.add('2["connect"]'); // "connect" is a reserved event name
      },
      (err) => {
        return err instanceof Error && /invalid payload/.test(err.message);
      },
      'Reserved event name in EVENT packet must throw invalid payload Error'
    );
  }

  console.log('All socket.io-parser contract assertions passed successfully.');
}

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

原始种子者

匿名