CodeSampleX

Пример

@tanstack/query-core 5.67.1: QueryCache

Проверенный пример — npm @tanstack/query-core 5.67.1: QueryCache. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:3fdc317b45f22e6026a402acc647121b97698362e4cfd1050bd5a42f9eafbefe

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-03

Кейс

HOW
Цель
verify pkg:npm/%40tanstack/query-core@5.67.1
Пакеты
Символы
  • QueryCache
Создан
2026-09-03T12:44:36Z

Контракт

  1. assert QueryCache constructs an instance with cache lifecycle methods
  2. assert QueryCache find retrieves an active query by exact queryKey or returns undefined
  3. assert QueryCache findAll matches queries by key prefix or filter predicate
  4. assert QueryCache subscribe notifies listeners of query lifecycle events: added, updated, removed
  5. assert QueryCache remove removes a query and clear removes all cached queries
  6. assert QueryCache unsubscribe stops listener notifications on subsequent cache events

Файлы

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

Скачать артефакт с исходным кодом (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: verify pkg:npm/%40tanstack/query-core@5.67.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40tanstack/query-core@5.67.1
Demonstrate these symbols/APIs:
  - QueryCache

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:23683287f3ec6ee52b7a409673c72fe58cbd4267ff0ac27ecdaf4524b8cf46c7","contract":["assert QueryCache constructs an instance with cache lifecycle methods","assert QueryCache find retrieves an active query by exact queryKey or returns undefined","assert QueryCache findAll matches queries by key prefix or filter predicate","assert QueryCache subscribe notifies listeners of query lifecycle events: added, updated, removed","assert QueryCache remove removes a query and clear removes all cached queries","assert QueryCache unsubscribe stops listener notifications on subsequent cache events"],"goal":"verify pkg:npm/%40tanstack/query-core@5.67.1","kind":"HOW","packages":["pkg:npm/%40tanstack/query-core@5.67.1"],"schemaVersion":1,"symbols":["QueryCache"]},"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/%40tanstack/query-core@5.67.1"],"schemaVersion":1,"subject":"pkg:npm/%40tanstack/query-core@5.67.1","symbols":["QueryCache"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { QueryCache, QueryClient } from '@tanstack/query-core';

/**
 * Creates a new QueryCache instance with optional configuration.
 *
 * @param {object} [config]
 * @returns {QueryCache}
 */
export function createQueryCache(config) {
  return new QueryCache(config);
}

/**
 * Subscribes a listener to QueryCache lifecycle events.
 *
 * @param {QueryCache} cache
 * @param {Function} listener
 * @returns {Function} Unsubscribe function
 */
export function subscribeQueryCache(cache, listener) {
  return cache.subscribe(listener);
}

/**
 * Finds a query by key within a QueryCache instance.
 *
 * @param {QueryCache} cache
 * @param {Array<string | number>} queryKey
 * @param {boolean} [exact=true]
 * @returns {object | undefined}
 */
export function findQuery(cache, queryKey, exact = true) {
  return cache.find({ queryKey, exact });
}

export { QueryCache, QueryClient };
export default QueryCache;
package-lock.json
{
  "name": "sample-query-core-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-query-core-verify",
      "version": "1.0.0",
      "dependencies": {
        "@tanstack/query-core": "5.67.1"
      }
    },
    "node_modules/@tanstack/query-core": {
      "version": "5.67.1",
      "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.67.1.tgz",
      "integrity": "sha512-AkFmuukVejyqVIjEQoFhLb3q+xHl7JG8G9cANWTMe3s8iKzD9j1VBSYXgCjy6vm6xM8cUCR9zP2yqWxY9pTWOA==",
      "license": "MIT",
      "funding": {
        "type": "github",
        "url": "https://github.com/sponsors/tannerlinsley"
      }
    }
  }
}
package.json
{
  "name": "sample-query-core-verify",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "@tanstack/query-core": "5.67.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40tanstack/query-core@5.67.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40tanstack/query-core@5.67.1"
  ],
  "symbols": [
    "QueryCache"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { QueryCache, QueryClient, createQueryCache, subscribeQueryCache, findQuery } from '../index.mjs';

// 1. assert QueryCache constructs an instance with cache lifecycle methods
{
  const cache = createQueryCache();
  assert.ok(cache instanceof QueryCache);
  assert.strictEqual(typeof cache.find, 'function');
  assert.strictEqual(typeof cache.findAll, 'function');
  assert.strictEqual(typeof cache.subscribe, 'function');
  assert.strictEqual(typeof cache.clear, 'function');
  assert.strictEqual(typeof cache.getAll, 'function');
}

// 2. assert QueryCache find retrieves an active query by exact queryKey or returns undefined
{
  const cache = new QueryCache();
  const client = new QueryClient({ queryCache: cache });

  client.setQueryData(['users', 1], { id: 1, name: 'Alice' });

  const found = findQuery(cache, ['users', 1], true);
  assert.ok(found);
  assert.deepStrictEqual(found.state.data, { id: 1, name: 'Alice' });
  assert.strictEqual(found.state.status, 'success');

  const notFound = findQuery(cache, ['users', 2], true);
  assert.strictEqual(notFound, undefined);
}

// 3. assert QueryCache findAll matches queries by key prefix or filter predicate
{
  const cache = new QueryCache();
  const client = new QueryClient({ queryCache: cache });

  client.setQueryData(['todos', 1], 'Buy milk');
  client.setQueryData(['todos', 2], 'Read book');
  client.setQueryData(['posts', 1], 'Hello world');

  const todos = cache.findAll({ queryKey: ['todos'] });
  assert.strictEqual(todos.length, 2);

  const matchedKeys = todos.map(q => q.queryKey).sort();
  assert.deepStrictEqual(matchedKeys, [['todos', 1], ['todos', 2]]);

  const posts = cache.findAll({ predicate: (q) => q.queryKey[0] === 'posts' });
  assert.strictEqual(posts.length, 1);
  assert.deepStrictEqual(posts[0].queryKey, ['posts', 1]);
}

// 4. assert QueryCache subscribe notifies listeners of query lifecycle events: added, updated, removed
{
  const cache = new QueryCache();
  const client = new QueryClient({ queryCache: cache });

  const eventTypes = [];
  const unsubscribe = subscribeQueryCache(cache, (event) => {
    eventTypes.push(event.type);
  });

  client.setQueryData(['counter'], 1);
  client.setQueryData(['counter'], 2);

  const query = findQuery(cache, ['counter']);
  assert.ok(query);

  cache.remove(query);

  assert.ok(eventTypes.includes('added'));
  assert.ok(eventTypes.includes('updated'));
  assert.ok(eventTypes.includes('removed'));

  unsubscribe();
}

// 5. assert QueryCache remove removes a query and clear removes all cached queries
{
  const cache = new QueryCache();
  const client = new QueryClient({ queryCache: cache });

  client.setQueryData(['item', 1], 'first');
  client.setQueryData(['item', 2], 'second');
  client.setQueryData(['item', 3], 'third');

  assert.strictEqual(cache.getAll().length, 3);

  const query1 = findQuery(cache, ['item', 1]);
  cache.remove(query1);

  assert.strictEqual(cache.getAll().length, 2);
  assert.strictEqual(findQuery(cache, ['item', 1]), undefined);

  cache.clear();
  assert.strictEqual(cache.getAll().length, 0);
}

// 6. assert QueryCache unsubscribe stops listener notifications on subsequent cache events
{
  const cache = new QueryCache();
  const client = new QueryClient({ queryCache: cache });

  let notificationCount = 0;
  const unsubscribe = subscribeQueryCache(cache, () => {
    notificationCount++;
  });

  client.setQueryData(['test'], 'data');
  assert.ok(notificationCount > 0);

  const countBefore = notificationCount;
  unsubscribe();

  client.setQueryData(['test2'], 'data2');
  assert.strictEqual(notificationCount, countBefore);
}

console.log('All QueryCache contract assertions passed.');

Исходный сидер

аноним