CodeSampleX

示例

@tanstack/query-core 5.90.20: QueryClient.cancelQueries

已验证示例 — npm @tanstack/query-core 5.90.20: QueryClient.cancelQueries. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: @tanstack/query-core package.json…

sha256:32279b55e15fa4bcc33096e49ef0770c80ea908c309fb429770f07d461b86904

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

执行证据

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

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

验证运行环境

环境 契约 阶段 运行日期
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 QueryClient.cancelQueries in pkg:npm/%40tanstack/query-core@5.90.20
包
符号
  • QueryClient.cancelQueries
环境
node 22.23.2
创建时间
2026-09-03T09:11:28Z

契约

  1. @tanstack/query-core package.json declares export mappings and version 5.90.20
  2. QueryClient prototype defines cancelQueries as a function
  3. QueryClient cancelQueries returns a Promise that resolves when called
  4. QueryClient cancelQueries aborts the AbortSignal of an in-flight query
  5. QueryClient cancelQueries resets in-flight query fetchStatus to idle
  6. QueryClient cancelQueries filters target queries by queryKey prefix
  7. QueryClient cancelQueries supports exact queryKey matching when exact option is true
  8. QueryClient cancelQueries reverts state and returns previous cached data when revert is enabled
  9. QueryClient cancelQueries supports custom filtering via predicate function

文件

  • 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 QueryClient.cancelQueries in pkg:npm/%40tanstack/query-core@5.90.20
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40tanstack/query-core@5.90.20
Demonstrate these symbols/APIs:
  - QueryClient.cancelQueries

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:8ee7c8299daa9c4600e1482d883d027254499c9c150f717ebfa6f601cb1d614a","contract":["@tanstack/query-core package.json declares export mappings and version 5.90.20","QueryClient prototype defines cancelQueries as a function","QueryClient cancelQueries returns a Promise that resolves when called","QueryClient cancelQueries aborts the AbortSignal of an in-flight query","QueryClient cancelQueries resets in-flight query fetchStatus to idle","QueryClient cancelQueries filters target queries by queryKey prefix","QueryClient cancelQueries supports exact queryKey matching when exact option is true","QueryClient cancelQueries reverts state and returns previous cached data when revert is enabled","QueryClient cancelQueries supports custom filtering via predicate function"],"goal":"verify QueryClient.cancelQueries in pkg:npm/%40tanstack/query-core@5.90.20","kind":"HOW","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"symbols":["QueryClient.cancelQueries"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"subject":"pkg:npm/%40tanstack/query-core@5.90.20","symbols":["QueryClient.cancelQueries"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { QueryClient, isCancelledError } from '@tanstack/query-core';

/**
 * Cancels active or matching queries in the QueryClient.
 *
 * @param {QueryClient} client
 * @param {import('@tanstack/query-core').QueryFilters} [filters]
 * @param {import('@tanstack/query-core').CancelOptions} [options]
 * @returns {Promise<void>}
 */
export function cancelQueries(client, filters, options) {
  return client.cancelQueries(filters, options);
}

/**
 * Cancels queries that match the exact queryKey.
 *
 * @param {QueryClient} client
 * @param {import('@tanstack/query-core').QueryKey} queryKey
 * @param {import('@tanstack/query-core').CancelOptions} [options]
 * @returns {Promise<void>}
 */
export function cancelExactQuery(client, queryKey, options) {
  return client.cancelQueries({ queryKey, exact: true }, options);
}

/**
 * Cancels queries satisfying a custom predicate function.
 *
 * @param {QueryClient} client
 * @param {(query: import('@tanstack/query-core').Query) => boolean} predicate
 * @param {import('@tanstack/query-core').CancelOptions} [options]
 * @returns {Promise<void>}
 */
export function cancelQueriesByPredicate(client, predicate, options) {
  return client.cancelQueries({ predicate }, options);
}

export { QueryClient, isCancelledError };
package-lock.json
{
  "name": "sample-query-core-cancel-queries",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-query-core-cancel-queries",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@tanstack/query-core": "5.90.20"
      }
    },
    "node_modules/@tanstack/query-core": {
      "version": "5.90.20",
      "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.20.tgz",
      "integrity": "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==",
      "license": "MIT",
      "funding": {
        "type": "github",
        "url": "https://github.com/sponsors/tannerlinsley"
      }
    }
  }
}
package.json
{
  "name": "sample-query-core-cancel-queries",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "main": "index.mjs",
  "dependencies": {
    "@tanstack/query-core": "5.90.20"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify QueryClient.cancelQueries in pkg:npm/%40tanstack/query-core@5.90.20",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40tanstack/query-core@5.90.20"
  ],
  "symbols": [
    "QueryClient.cancelQueries"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import {
  QueryClient,
  isCancelledError,
  cancelQueries,
  cancelExactQuery,
  cancelQueriesByPredicate,
} from '../index.mjs';

const require = createRequire(import.meta.url);

async function main() {
  // Contract 1: @tanstack/query-core package.json declares export mappings and version 5.90.20
  {
    const pkgJsonPath = require.resolve('@tanstack/query-core/package.json');
    assert.ok(fs.existsSync(pkgJsonPath));
    const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
    assert.strictEqual(pkgJson.name, '@tanstack/query-core');
    assert.strictEqual(pkgJson.version, '5.90.20');
    assert.ok(pkgJson.main || pkgJson.module || pkgJson.exports);
  }

  // Contract 2: QueryClient prototype defines cancelQueries as a function
  {
    assert.strictEqual(typeof QueryClient.prototype.cancelQueries, 'function');
    const client = new QueryClient();
    assert.strictEqual(typeof client.cancelQueries, 'function');
  }

  // Contract 3: QueryClient cancelQueries returns a Promise that resolves when called
  {
    const client = new QueryClient();
    const promise = cancelQueries(client);
    assert.ok(promise instanceof Promise);
    await promise;
  }

  // Contract 4: QueryClient cancelQueries aborts the AbortSignal of an in-flight query
  {
    const client = new QueryClient();
    let capturedSignal = null;
    let startedResolve;
    const pStarted = new Promise((resolve) => {
      startedResolve = resolve;
    });

    const fetchPromise = client.fetchQuery({
      queryKey: ['contract-signal-test'],
      queryFn: ({ signal }) => {
        capturedSignal = signal;
        startedResolve();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('aborted by signal')));
        });
      },
      retry: false,
    });
    fetchPromise.catch(() => {});

    await pStarted;
    assert.ok(capturedSignal);
    assert.strictEqual(capturedSignal.aborted, false);

    await cancelQueries(client, { queryKey: ['contract-signal-test'] });
    assert.strictEqual(capturedSignal.aborted, true);

    await assert.rejects(fetchPromise, (err) => isCancelledError(err));
  }

  // Contract 5: QueryClient cancelQueries resets in-flight query fetchStatus to idle
  {
    const client = new QueryClient();
    let startedResolve;
    const pStarted = new Promise((resolve) => {
      startedResolve = resolve;
    });

    const fetchPromise = client.fetchQuery({
      queryKey: ['contract-fetch-status'],
      queryFn: ({ signal }) => {
        startedResolve();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('aborted')));
        });
      },
      retry: false,
    });
    fetchPromise.catch(() => {});

    await pStarted;
    const query = client.getQueryCache().find({ queryKey: ['contract-fetch-status'] });
    assert.ok(query);
    assert.strictEqual(query.state.fetchStatus, 'fetching');

    await client.cancelQueries({ queryKey: ['contract-fetch-status'] });
    assert.strictEqual(query.state.fetchStatus, 'idle');

    await assert.rejects(fetchPromise, (err) => isCancelledError(err));
  }

  // Contract 6: QueryClient cancelQueries filters target queries by queryKey prefix
  {
    const client = new QueryClient();
    let signalA, signalB;
    let startedA, startedB;
    const pStartedA = new Promise((r) => { startedA = r; });
    const pStartedB = new Promise((r) => { startedB = r; });

    const pA = client.fetchQuery({
      queryKey: ['prefix-match', 'item-1'],
      queryFn: ({ signal }) => {
        signalA = signal;
        startedA();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('A aborted')));
        });
      },
      retry: false,
    });
    pA.catch(() => {});

    const pB = client.fetchQuery({
      queryKey: ['other-group', 'item-2'],
      queryFn: ({ signal }) => {
        signalB = signal;
        startedB();
        return new Promise((resolve) => setTimeout(() => resolve('done-b'), 40));
      },
      retry: false,
    });

    await Promise.all([pStartedA, pStartedB]);
    await client.cancelQueries({ queryKey: ['prefix-match'] });

    assert.strictEqual(signalA.aborted, true);
    assert.strictEqual(signalB.aborted, false);

    await assert.rejects(pA, (err) => isCancelledError(err));
    const resultB = await pB;
    assert.strictEqual(resultB, 'done-b');
  }

  // Contract 7: QueryClient cancelQueries supports exact queryKey matching when exact option is true
  {
    const client = new QueryClient();
    let signalExact, signalNested;
    let started1, started2;
    const pStarted1 = new Promise((r) => { started1 = r; });
    const pStarted2 = new Promise((r) => { started2 = r; });

    const pExact = client.fetchQuery({
      queryKey: ['exact-test'],
      queryFn: ({ signal }) => {
        signalExact = signal;
        started1();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('exact aborted')));
        });
      },
      retry: false,
    });
    pExact.catch(() => {});

    const pNested = client.fetchQuery({
      queryKey: ['exact-test', 'child'],
      queryFn: ({ signal }) => {
        signalNested = signal;
        started2();
        return new Promise((resolve) => setTimeout(() => resolve('nested-done'), 40));
      },
      retry: false,
    });

    await Promise.all([pStarted1, pStarted2]);
    await cancelExactQuery(client, ['exact-test']);

    assert.strictEqual(signalExact.aborted, true);
    assert.strictEqual(signalNested.aborted, false);

    await assert.rejects(pExact, (err) => isCancelledError(err));
    const resNested = await pNested;
    assert.strictEqual(resNested, 'nested-done');
  }

  // Contract 8: QueryClient cancelQueries reverts state and returns previous cached data when revert is enabled
  {
    const client = new QueryClient();
    client.setQueryData(['contract-revert-key'], 'initial-data');
    let startedResolve;
    const pStarted = new Promise((resolve) => {
      startedResolve = resolve;
    });

    const fetchPromise = client.fetchQuery({
      queryKey: ['contract-revert-key'],
      queryFn: ({ signal }) => {
        startedResolve();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('revert test aborted')));
        });
      },
      retry: false,
    });

    await pStarted;
    await client.cancelQueries({ queryKey: ['contract-revert-key'] }, { revert: true });

    const returnedData = await fetchPromise;
    assert.strictEqual(returnedData, 'initial-data');
    assert.strictEqual(client.getQueryData(['contract-revert-key']), 'initial-data');
  }

  // Contract 9: QueryClient cancelQueries supports custom filtering via predicate function
  {
    const client = new QueryClient();
    let signalP1, signalP2;
    let started1, started2;
    const pStarted1 = new Promise((r) => { started1 = r; });
    const pStarted2 = new Promise((r) => { started2 = r; });

    const p1 = client.fetchQuery({
      queryKey: ['contract-predicate', 1],
      queryFn: ({ signal }) => {
        signalP1 = signal;
        started1();
        return new Promise((_, reject) => {
          signal.addEventListener('abort', () => reject(new Error('p1 aborted')));
        });
      },
      retry: false,
    });
    p1.catch(() => {});

    const p2 = client.fetchQuery({
      queryKey: ['contract-predicate', 2],
      queryFn: ({ signal }) => {
        signalP2 = signal;
        started2();
        return new Promise((resolve) => setTimeout(() => resolve('p2-done'), 40));
      },
      retry: false,
    });

    await Promise.all([pStarted1, pStarted2]);
    await cancelQueriesByPredicate(client, (query) => Array.isArray(query.queryKey) && query.queryKey[1] === 1);

    assert.strictEqual(signalP1.aborted, true);
    assert.strictEqual(signalP2.aborted, false);

    await assert.rejects(p1, (err) => isCancelledError(err));
    const res2 = await p2;
    assert.strictEqual(res2, 'p2-done');
  }

  console.log('All QueryClient.cancelQueries contract tests passed.');
}

main();

原始种子者

匿名