CodeSampleX

Exemplo

@jest/diff-sequences 30.4.0: diffSequence

Amostra verificada para npm @jest/diff-sequences 30.4.0: diffSequence. O contrato rodou em node 22 · linux alpine/x64 · docker e passou.

sha256:f8b1ee685a45971153cbb54dc3f49fc39110a6e24663d8bc3bbf05531dd01b3f

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-27

Caso

HOW
Objetivo
verify pkg:npm/%40jest/diff-sequences@30.4.0
Pacotes
Símbolos
  • diffSequence
Ambiente
node 22.23.2
Criado
2026-08-27T22:40:30Z

Contrato

  1. diffSequence invokes foundSubsequence callback with length and starting indices for each common chunk between two sequences
  2. diffSequence validates that aLength and bLength are non-negative safe integers and throws TypeError or RangeError otherwise
  3. diffSequence validates that isCommon and foundSubsequence are functions and throws TypeError otherwise
  4. diffSequence handles identical sequences by emitting a single common chunk spanning the entire length
  5. diffSequence handles completely disjoint sequences without invoking foundSubsequence
  6. diffSequence handles empty sequences without error or callback invocations
  7. findCommonSubsequences extracts all matched contiguous intervals between arrays or strings
  8. computeEditScript generates ordered delete, insert, and common operations transforming sequence A into sequence B
  9. longestCommonSubsequence reconstructs the longest shared subsequence of items

Arquivos

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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 pkg:npm/%40jest/diff-sequences@30.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40jest/diff-sequences@30.4.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:2b1a6dbd0c7ad270935d621c77e5817991954595113037e530aa0e9f017a7159","constraints":{"executionContext":"node"},"contract":["diffSequence invokes foundSubsequence callback with length and starting indices for each common chunk between two sequences","diffSequence validates that aLength and bLength are non-negative safe integers and throws TypeError or RangeError otherwise","diffSequence validates that isCommon and foundSubsequence are functions and throws TypeError otherwise","diffSequence handles identical sequences by emitting a single common chunk spanning the entire length","diffSequence handles completely disjoint sequences without invoking foundSubsequence","diffSequence handles empty sequences without error or callback invocations","findCommonSubsequences extracts all matched contiguous intervals between arrays or strings","computeEditScript generates ordered delete, insert, and common operations transforming sequence A into sequence B","longestCommonSubsequence reconstructs the longest shared subsequence of items"],"goal":"verify pkg:npm/%40jest/diff-sequences@30.4.0","kind":"HOW","packages":["pkg:npm/%40jest/diff-sequences@30.4.0"],"schemaVersion":1,"symbols":["diffSequence"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40jest/diff-sequences@30.4.0"],"schemaVersion":1,"subject":"pkg:npm/%40jest/diff-sequences@30.4.0","symbols":["diffSequence"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const diffSequenceImport = require('@jest/diff-sequences');
const diffSequence = typeof diffSequenceImport === 'function'
  ? diffSequenceImport
  : diffSequenceImport.default;

/**
 * Low-level Myers diff-sequences algorithm.
 * @param {number} aLength - Length of sequence A
 * @param {number} bLength - Length of sequence B
 * @param {(aIndex: number, bIndex: number) => boolean} isCommon - Comparator callback
 * @param {(nCommon: number, aCommon: number, bCommon: number) => void} foundSubsequence - Match callback
 */
function diffSequences(aLength, bLength, isCommon, foundSubsequence) {
  return diffSequence(aLength, bLength, isCommon, foundSubsequence);
}

/**
 * Finds all common subsequences between two indexable sequences (arrays or strings).
 * @param {Array|string} a - First sequence
 * @param {Array|string} b - Second sequence
 * @param {(itemA: any, itemB: any) => boolean} [customCompare] - Optional comparator
 * @returns {Array<{ nCommon: number, aCommon: number, bCommon: number, items: Array|string }>}
 */
function findCommonSubsequences(a, b, customCompare) {
  const isCommon = customCompare
    ? (aIdx, bIdx) => customCompare(a[aIdx], b[bIdx])
    : (aIdx, bIdx) => a[aIdx] === b[bIdx];

  const matches = [];
  diffSequence(a.length, b.length, isCommon, (nCommon, aCommon, bCommon) => {
    const items = typeof a === 'string'
      ? a.slice(aCommon, aCommon + nCommon)
      : a.slice(aCommon, aCommon + nCommon);
    matches.push({
      nCommon,
      aCommon,
      bCommon,
      items
    });
  });
  return matches;
}

/**
 * Computes an edit script of common, delete, and insert operations to transform `a` into `b`.
 * @param {Array|string} a - Source sequence
 * @param {Array|string} b - Target sequence
 * @param {(itemA: any, itemB: any) => boolean} [customCompare] - Optional comparator
 * @returns {Array<{ type: 'common'|'delete'|'insert', aStart: number, aEnd: number, bStart: number, bEnd: number, items: Array|string }>}
 */
function computeEditScript(a, b, customCompare) {
  const commonBlocks = findCommonSubsequences(a, b, customCompare);
  const edits = [];
  let aPos = 0;
  let bPos = 0;

  for (const block of commonBlocks) {
    if (aPos < block.aCommon) {
      edits.push({
        type: 'delete',
        aStart: aPos,
        aEnd: block.aCommon,
        bStart: bPos,
        bEnd: bPos,
        items: a.slice(aPos, block.aCommon)
      });
      aPos = block.aCommon;
    }
    if (bPos < block.bCommon) {
      edits.push({
        type: 'insert',
        aStart: aPos,
        aEnd: aPos,
        bStart: bPos,
        bEnd: block.bCommon,
        items: b.slice(bPos, block.bCommon)
      });
      bPos = block.bCommon;
    }
    edits.push({
      type: 'common',
      aStart: block.aCommon,
      aEnd: block.aCommon + block.nCommon,
      bStart: block.bCommon,
      bEnd: block.bCommon + block.nCommon,
      items: block.items
    });
    aPos = block.aCommon + block.nCommon;
    bPos = block.bCommon + block.nCommon;
  }

  if (aPos < a.length) {
    edits.push({
      type: 'delete',
      aStart: aPos,
      aEnd: a.length,
      bStart: bPos,
      bEnd: bPos,
      items: a.slice(aPos)
    });
  }
  if (bPos < b.length) {
    edits.push({
      type: 'insert',
      aStart: a.length,
      aEnd: a.length,
      bStart: bPos,
      bEnd: b.length,
      items: b.slice(bPos)
    });
  }

  return edits;
}

/**
 * Returns the longest common subsequence of two sequences.
 * @param {Array|string} a - First sequence
 * @param {Array|string} b - Second sequence
 * @param {(itemA: any, itemB: any) => boolean} [customCompare] - Optional comparator
 * @returns {Array|string}
 */
function longestCommonSubsequence(a, b, customCompare) {
  const commonBlocks = findCommonSubsequences(a, b, customCompare);
  if (typeof a === 'string') {
    return commonBlocks.map(block => block.items).join('');
  }
  return commonBlocks.flatMap(block => block.items);
}

module.exports = {
  diffSequence,
  diffSequences,
  findCommonSubsequences,
  computeEditScript,
  longestCommonSubsequence
};
package-lock.json
{
  "name": "sample-jest-diff-sequences",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-diff-sequences",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@jest/diff-sequences": "30.4.0"
      }
    },
    "node_modules/@jest/diff-sequences": {
      "version": "30.4.0",
      "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz",
      "integrity": "sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g==",
      "license": "MIT",
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-jest-diff-sequences",
  "version": "1.0.0",
  "private": true,
  "description": "compute diff and longest common subsequence using @jest/diff-sequences",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "@jest/diff-sequences": "30.4.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40jest/diff-sequences@30.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40jest/diff-sequences@30.4.0"
  ],
  "symbols": [
    "diffSequence"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  diffSequence,
  diffSequences,
  findCommonSubsequences,
  computeEditScript,
  longestCommonSubsequence
} = require('../index.js');

function testDiffSequenceBasic() {
  const a = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'];
  const b = ['alpha', 'omega', 'gamma', 'sigma', 'epsilon'];
  const recorded = [];

  diffSequence(
    a.length,
    b.length,
    (aIdx, bIdx) => a[aIdx] === b[bIdx],
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 3, 'Should record 3 common subsequences');
  assert.deepStrictEqual(recorded[0], { nCommon: 1, aCommon: 0, bCommon: 0 });
  assert.deepStrictEqual(recorded[1], { nCommon: 1, aCommon: 2, bCommon: 2 });
  assert.deepStrictEqual(recorded[2], { nCommon: 1, aCommon: 4, bCommon: 4 });
}

function testDiffSequenceIdentical() {
  const seq = ['x', 'y', 'z'];
  const recorded = [];

  diffSequences(
    seq.length,
    seq.length,
    (aIdx, bIdx) => seq[aIdx] === seq[bIdx],
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 1);
  assert.deepStrictEqual(recorded[0], { nCommon: 3, aCommon: 0, bCommon: 0 });
}

function testDiffSequenceDisjoint() {
  const a = [1, 2, 3];
  const b = [4, 5, 6];
  const recorded = [];

  diffSequence(
    a.length,
    b.length,
    (aIdx, bIdx) => a[aIdx] === b[bIdx],
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 0, 'No common subsequences should be found');
}

function testDiffSequenceEmpty() {
  const recorded = [];

  diffSequence(
    0,
    0,
    () => true,
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 0);
}

function testDiffSequenceValidation() {
  assert.throws(
    () => diffSequence('3', 3, () => true, () => {}),
    TypeError,
    'aLength must be a number'
  );
  assert.throws(
    () => diffSequence(-1, 3, () => true, () => {}),
    RangeError,
    'aLength must be non-negative'
  );
  assert.throws(
    () => diffSequence(1.5, 3, () => true, () => {}),
    RangeError,
    'aLength must be an integer'
  );
  assert.throws(
    () => diffSequence(3, null, () => true, () => {}),
    TypeError,
    'bLength must be a number'
  );
  assert.throws(
    () => diffSequence(3, 3, null, () => {}),
    TypeError,
    'isCommon must be a function'
  );
  assert.throws(
    () => diffSequence(3, 3, () => true, 'invalid'),
    TypeError,
    'foundSubsequence must be a function'
  );
}

function testFindCommonSubsequences() {
  const s1 = 'ABCDE';
  const s2 = 'ABXDE';
  const matches = findCommonSubsequences(s1, s2);

  assert.strictEqual(matches.length, 2);
  assert.deepStrictEqual(matches[0], {
    nCommon: 2,
    aCommon: 0,
    bCommon: 0,
    items: 'AB'
  });
  assert.deepStrictEqual(matches[1], {
    nCommon: 2,
    aCommon: 3,
    bCommon: 3,
    items: 'DE'
  });
}

function testComputeEditScript() {
  const a = ['apple', 'banana', 'cherry'];
  const b = ['banana', 'date'];
  const edits = computeEditScript(a, b);

  assert.strictEqual(edits.length, 4);
  assert.deepStrictEqual(edits[0], {
    type: 'delete',
    aStart: 0,
    aEnd: 1,
    bStart: 0,
    bEnd: 0,
    items: ['apple']
  });
  assert.deepStrictEqual(edits[1], {
    type: 'common',
    aStart: 1,
    aEnd: 2,
    bStart: 0,
    bEnd: 1,
    items: ['banana']
  });
  assert.deepStrictEqual(edits[2], {
    type: 'delete',
    aStart: 2,
    aEnd: 3,
    bStart: 1,
    bEnd: 1,
    items: ['cherry']
  });
  assert.deepStrictEqual(edits[3], {
    type: 'insert',
    aStart: 3,
    aEnd: 3,
    bStart: 1,
    bEnd: 2,
    items: ['date']
  });
}

function testLongestCommonSubsequence() {
  const strLcs = longestCommonSubsequence('gac', 'agcat');
  assert.strictEqual(strLcs, 'ac');

  const arrLcs = longestCommonSubsequence([1, 2, 3, 4], [2, 4, 6]);
  assert.deepStrictEqual(arrLcs, [2, 4]);
}

function testCustomComparator() {
  const a = ['HELLO', 'WORLD'];
  const b = ['hello', 'everyone'];
  const caseInsensitiveCompare = (x, y) => x.toLowerCase() === y.toLowerCase();

  const matches = findCommonSubsequences(a, b, caseInsensitiveCompare);
  assert.strictEqual(matches.length, 1);
  assert.deepStrictEqual(matches[0], {
    nCommon: 1,
    aCommon: 0,
    bCommon: 0,
    items: ['HELLO']
  });
}

function runAll() {
  testDiffSequenceBasic();
  testDiffSequenceIdentical();
  testDiffSequenceDisjoint();
  testDiffSequenceEmpty();
  testDiffSequenceValidation();
  testFindCommonSubsequences();
  testComputeEditScript();
  testLongestCommonSubsequence();
  testCustomComparator();
  console.log('All diff-sequences contract tests passed successfully.');
}

runAll();

Seeder de origem

anônimo