샘플
@tanstack/query-core 5.90.20: QueriesObserver
검증된 샘플 — npm @tanstack/query-core 5.90.20: QueriesObserver. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: QueriesObserver.getCurrentResult…
sha256:a4d9dc222b8472613927a3792fd231280174a009648f7adfb04453f4ea2e4b4c
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 node 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 QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20
- 심벌
-
- QueriesObserver
- 환경
- node 22.23.2
- 생성일
- 2026-09-03T09:54:00Z
컨트랙트
- QueriesObserver.getCurrentResult immediately returns cached data for primed queries and pending status for unprimed queries
- QueriesObserver.subscribe triggers fetching of pending and stale queries and notifies listeners on result updates
- QueriesObserver.setQueries preserves and reuses existing QueryObserver instances matching queryHash while destroying removed ones
- QueriesObserver.getOptimisticResult applies the combine option to aggregate and transform multiple query results
- QueriesObserver.destroy cleans up active listeners and destroys all managed child QueryObserver instances
파일
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
소스
# TanStack Query Core: QueriesObserver multi-query orchestration and observation
## Known Solution Search
- Prior network samples covered `QueryClient` imperative cache methods (`ensureQueryData`, `setQueryData`, `prefetchQuery`, `fetchQuery`) and `MutationObserver` synchronous mutation timing.
- No prior verified sample exists for `QueriesObserver` in `@tanstack/query-core@5.90.20`.
- This sample proves the multi-query lifecycle, initial caching state, subscription-triggered fetching, observer instance reuse in `setQueries`, optimistic combine transformations, and teardown cleanup.
## Pinned Release
- **Package**: `@tanstack/query-core`
- **Exact Version**: `5.90.20`
- **Symbol**: `QueriesObserver`
## Observed Behaviors and Traps
### 1. Synchronous Cache Access in `getCurrentResult`
`QueriesObserver.prototype.getCurrentResult` returns an array of `QueryObserverResult` objects corresponding to the provided queries array.
- For queries whose data already exists in the `QueryCache`, the observer immediately returns `{ status: 'success', data: ..., ... }`.
- For queries with no existing cache entry, the observer returns `{ status: 'pending', data: undefined, ... }`.
- **Trap / Naive Expectation**: Developers might assume `getCurrentResult()` triggers query fetching or returns promises. It is purely synchronous cache inspection.
### 2. Subscription Triggers Fetching for Stale and Pending Queries
When subscribing via `observer.subscribe(listener)`:
- The observer subscribes each child `QueryObserver`.
- Stale or pending queries immediately trigger background fetching through their respective `queryFn`.
- When queries resolve, the subscriber listener is invoked with the updated array of results.
- **Trap / Naive Expectation**: Assuming queries begin fetching upon `new QueriesObserver(...)` without an active subscriber or explicit fetch command.
### 3. Instance Reuse via `queryHash` in `setQueries`
`QueriesObserver.prototype.setQueries` dynamically adjusts the set of observed queries:
- Internally, `findMatchingObservers` maps existing `QueryObserver` instances by their normalized `queryHash`.
- Observers whose hash matches an item in the new query list are retained and updated with new options via `setOptions`.
- Observers omitted from the new query list are destroyed.
- **Trap / Naive Expectation**: Assuming `setQueries` throws away all state and creates new observer instances anew, causing unnecessary cache disruption and re-subscriptions.
### 4. Optimistic Aggregation via `combine`
`QueriesObserver.prototype.getOptimisticResult` accepts a `combine` function:
- It returns `[rawResult, combineResult, trackResult]`.
- Calling `combineResult` executes the transformation and memoizes the combined structure using `replaceEqualDeep`.
### 5. Cascade Cleanup in `destroy`
`QueriesObserver.prototype.destroy` clears its own listeners set and calls `destroy()` on each managed child `QueryObserver`, ensuring no leaked subscriptions in long-lived query clients.
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 QueriesObserver 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:
- QueriesObserver
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.
{"case":{"caseId":"case:sha256:215e748457f5c1dcee9487876cd552082036661470e8a29e73542a0d0424ecb2","contract":["QueriesObserver.getCurrentResult immediately returns cached data for primed queries and pending status for unprimed queries","QueriesObserver.subscribe triggers fetching of pending and stale queries and notifies listeners on result updates","QueriesObserver.setQueries preserves and reuses existing QueryObserver instances matching queryHash while destroying removed ones","QueriesObserver.getOptimisticResult applies the combine option to aggregate and transform multiple query results","QueriesObserver.destroy cleans up active listeners and destroys all managed child QueryObserver instances"],"goal":"verify QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20","kind":"HOW","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"symbols":["QueriesObserver"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"node","libc":"glibc","libcVersion":"2.39","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":["QueriesObserver"],"verifierAdapter":"node-typescript@1"}
{
"name": "npm-tanstack-query-core-queries-observer-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "npm-tanstack-query-core-queries-observer-sample",
"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"
}
}
}
}
{
"name": "npm-tanstack-query-core-queries-observer-sample",
"version": "1.0.0",
"type": "module",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"@tanstack/query-core": "5.90.20"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "verify QueriesObserver in pkg:npm/%40tanstack/query-core@5.90.20",
"kind": "HOW",
"packages": [
"pkg:npm/%40tanstack/query-core@5.90.20"
],
"symbols": [
"QueriesObserver"
]
}
import assert from 'node:assert/strict';
import { QueryClient, QueriesObserver } from '@tanstack/query-core';
async function runContract() {
const client = new QueryClient();
// 1. QueriesObserver.getCurrentResult immediately returns cached data for primed queries and pending status for unprimed queries
client.setQueryData(['items', 'primed'], { id: 1, title: 'Item 1' });
const observer = new QueriesObserver(client, [
{
queryKey: ['items', 'primed'],
queryFn: async () => ({ id: 1, title: 'Item 1 fresh' }),
},
{
queryKey: ['items', 'unprimed'],
queryFn: async () => ({ id: 2, title: 'Item 2 fresh' }),
},
]);
const initialResults = observer.getCurrentResult();
assert.strictEqual(initialResults.length, 2, 'Initial results length must match queries count');
assert.strictEqual(initialResults[0].status, 'success', 'Primed query must start with status success');
assert.deepStrictEqual(initialResults[0].data, { id: 1, title: 'Item 1' }, 'Primed query data must reflect cache');
assert.strictEqual(initialResults[1].status, 'pending', 'Unprimed query must start with status pending');
assert.strictEqual(initialResults[1].data, undefined, 'Unprimed query data must be undefined');
// 2. QueriesObserver.subscribe triggers fetching of pending and stale queries and notifies listeners on result updates
let notifyCount = 0;
const fetchCompletion = new Promise((resolve) => {
const unsubscribe = observer.subscribe((result) => {
notifyCount++;
if (result[0]?.data?.title === 'Item 1 fresh' && result[1]?.status === 'success') {
unsubscribe();
resolve();
}
});
});
await fetchCompletion;
assert.ok(notifyCount > 0, 'Listener should have been notified during query resolution');
const subscribedResults = observer.getCurrentResult();
assert.strictEqual(subscribedResults[0].status, 'success', 'Primed query should remain in success state after refetch');
assert.deepStrictEqual(subscribedResults[0].data, { id: 1, title: 'Item 1 fresh' }, 'Stale primed query should refetch and update');
assert.strictEqual(subscribedResults[1].status, 'success', 'Unprimed query should resolve to success after fetching');
assert.deepStrictEqual(subscribedResults[1].data, { id: 2, title: 'Item 2 fresh' }, 'Unprimed query should carry fetched data');
// 3. QueriesObserver.setQueries preserves and reuses existing QueryObserver instances matching queryHash while destroying removed ones
const initialObservers = observer.getObservers();
assert.strictEqual(initialObservers.length, 2, 'Should hold two child observers');
const retainedObserver = initialObservers[0];
observer.setQueries([
{
queryKey: ['items', 'primed'],
queryFn: async () => ({ id: 1, title: 'Item 1 modified' }),
},
{
queryKey: ['items', 'new'],
queryFn: async () => ({ id: 3, title: 'Item 3 fresh' }),
},
]);
const updatedObservers = observer.getObservers();
assert.strictEqual(updatedObservers.length, 2, 'Should hold two child observers after reconfiguration');
assert.strictEqual(updatedObservers[0], retainedObserver, 'Query observer with unchanged queryHash must be retained');
assert.notStrictEqual(updatedObservers[1], initialObservers[1], 'Omitted query observer must be replaced with new instance');
const reconfiguredResults = observer.getCurrentResult();
assert.strictEqual(reconfiguredResults.length, 2);
assert.deepStrictEqual(reconfiguredResults[0].data, { id: 1, title: 'Item 1 fresh' });
assert.strictEqual(reconfiguredResults[1].status, 'pending');
// 4. QueriesObserver.getOptimisticResult applies the combine option to aggregate and transform multiple query results
const [rawResult, combineResult] = observer.getOptimisticResult(
[
{ queryKey: ['items', 'primed'] },
{ queryKey: ['items', 'new'] },
],
(results) => ({
totalCount: results.length,
hasPending: results.some((r) => r.isPending),
firstId: results[0]?.data?.id ?? null,
})
);
assert.strictEqual(rawResult.length, 2, 'Raw optimistic result length should match queries length');
const combined = combineResult(rawResult);
assert.deepStrictEqual(
combined,
{
totalCount: 2,
hasPending: true,
firstId: 1,
},
'combineResult should return computed aggregate data structure'
);
// 5. QueriesObserver.destroy cleans up active listeners and destroys all managed child QueryObserver instances
observer.destroy();
assert.strictEqual(observer.hasListeners(), false, 'destroy() must remove all active listeners');
console.log('QueriesObserver contract passed successfully.');
}
runContract().catch((err) => {
console.error('Contract test failed:', err);
process.exit(1);
});
오리진 시더
익명