샘플
@tanstack/query-core 5.90.20: hydrate
검증된 샘플 — npm @tanstack/query-core 5.90.20: hydrate. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: hydrate populates query cache from dehydrated…
sha256:021ab56c5e26187efdb331a0467dc0fa32b757d47b943a47051e90137bef61e1
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
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 hydrate in pkg:npm/%40tanstack/query-core@5.90.20
- 심벌
-
- hydrate
- 환경
- node 22.23.2
- 생성일
- 2026-09-03T09:52:21Z
컨트랙트
- hydrate populates query cache from dehydrated state queries
- hydrate ignores non-object or empty dehydrated state gracefully
- hydrate respects dataUpdatedAt and does not overwrite newer query data
- deserializeData option transforms dehydrated data during hydration
- hydrate restores mutations into MutationCache
- hydrate applies defaultOptions.queries to hydrated query options
- hydrate preserves query metadata across cache instances
파일
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
소스
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 hydrate 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:
- hydrate
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:49c1fb990b766f79e122924fe31bf72b39bf3c9d4b05f2084986699d57772caf","contract":["hydrate populates query cache from dehydrated state queries","hydrate ignores non-object or empty dehydrated state gracefully","hydrate respects dataUpdatedAt and does not overwrite newer query data","deserializeData option transforms dehydrated data during hydration","hydrate restores mutations into MutationCache","hydrate applies defaultOptions.queries to hydrated query options","hydrate preserves query metadata across cache instances"],"goal":"verify hydrate in pkg:npm/%40tanstack/query-core@5.90.20","kind":"HOW","packages":["pkg:npm/%40tanstack/query-core@5.90.20"],"schemaVersion":1,"symbols":["hydrate"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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":["hydrate"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-query-core-hydrate",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-query-core-hydrate",
"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": "sample-query-core-hydrate",
"version": "1.0.0",
"type": "module",
"private": true,
"license": "MIT-0",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"@tanstack/query-core": "5.90.20"
}
}
{
"schemaVersion": 1,
"goal": "verify hydrate in pkg:npm/%40tanstack/query-core@5.90.20",
"kind": "HOW",
"packages": [
"pkg:npm/%40tanstack/query-core@5.90.20"
],
"symbols": [
"hydrate"
]
}
import {
QueryClient,
hydrate,
dehydrate,
} from '@tanstack/query-core';
/**
* Creates a QueryClient with optional hydrate configuration.
* @param {object} [defaultOptions] Default query client options.
* @returns {QueryClient}
*/
export function createClient(defaultOptions = {}) {
return new QueryClient(defaultOptions);
}
/**
* Hydrates a QueryClient with dehydrated state.
* @param {QueryClient} client
* @param {unknown} dehydratedState
* @param {object} [options]
*/
export function hydrateClient(client, dehydratedState, options) {
hydrate(client, dehydratedState, options);
}
/**
* Dehydrates a QueryClient state.
* @param {QueryClient} client
* @param {object} [options]
* @returns {object} Dehydrated state
*/
export function dehydrateClient(client, options) {
return dehydrate(client, options);
}
export {
QueryClient,
hydrate,
dehydrate,
};
export default hydrate;
import assert from 'node:assert/strict';
import {
QueryClient,
hydrate,
dehydrate,
} from '@tanstack/query-core';
import {
createClient,
hydrateClient,
dehydrateClient,
} from '../src/index.mjs';
// 1. hydrate populates query cache from dehydrated state queries
{
const sourceClient = new QueryClient();
sourceClient.setQueryData(['items', 1], { id: 1, name: 'Item One' });
const dehydrated = dehydrate(sourceClient);
const targetClient = new QueryClient();
hydrate(targetClient, dehydrated);
assert.deepEqual(targetClient.getQueryData(['items', 1]), { id: 1, name: 'Item One' });
const query = targetClient.getQueryCache().find({ queryKey: ['items', 1] });
assert.ok(query, 'query must be registered in query cache');
assert.equal(query.state.status, 'success');
assert.equal(query.state.fetchStatus, 'idle');
// Also test hydrateClient helper
const helperClient = createClient();
hydrateClient(helperClient, dehydrated);
assert.deepEqual(helperClient.getQueryData(['items', 1]), { id: 1, name: 'Item One' });
}
// 2. hydrate ignores non-object or empty dehydrated state gracefully
{
const client = new QueryClient();
// Should not throw or crash on null, undefined, primitives, or empty objects
assert.doesNotThrow(() => hydrate(client, null));
assert.doesNotThrow(() => hydrate(client, undefined));
assert.doesNotThrow(() => hydrate(client, 'invalid string'));
assert.doesNotThrow(() => hydrate(client, 123));
assert.doesNotThrow(() => hydrate(client, {}));
assert.doesNotThrow(() => hydrate(client, { queries: [] }));
assert.equal(client.getQueryCache().getAll().length, 0);
assert.equal(client.getMutationCache().getAll().length, 0);
}
// 3. hydrate respects dataUpdatedAt and does not overwrite newer query data
{
const client = new QueryClient();
// Query with newer timestamp (2000)
client.setQueryData(['counter'], { count: 10 }, { updatedAt: 2000 });
// Dehydrated state with older timestamp (1000)
const olderDehydrated = {
mutations: [],
queries: [
{
queryKey: ['counter'],
queryHash: JSON.stringify(['counter']),
state: {
data: { count: 5 },
dataUpdatedAt: 1000,
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, olderDehydrated);
// Newer data (count: 10) must NOT be overwritten by older data
assert.deepEqual(client.getQueryData(['counter']), { count: 10 });
// Dehydrated state with newer timestamp (3000)
const newerDehydrated = {
mutations: [],
queries: [
{
queryKey: ['counter'],
queryHash: JSON.stringify(['counter']),
state: {
data: { count: 15 },
dataUpdatedAt: 3000,
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, newerDehydrated);
// Newer data (count: 15) MUST overwrite older data
assert.deepEqual(client.getQueryData(['counter']), { count: 15 });
}
// 4. deserializeData option transforms dehydrated data during hydration
{
const client = new QueryClient();
const dehydrated = {
mutations: [],
queries: [
{
queryKey: ['events', 1],
queryHash: JSON.stringify(['events', 1]),
state: {
data: {
title: 'Conference',
date: '2026-09-03T12:00:00.000Z',
},
dataUpdatedAt: Date.now(),
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, dehydrated, {
defaultOptions: {
deserializeData: (data) => {
if (data && typeof data === 'object' && typeof data.date === 'string') {
return {
...data,
date: new Date(data.date),
};
}
return data;
},
},
});
const hydratedData = client.getQueryData(['events', 1]);
assert.equal(hydratedData.title, 'Conference');
assert.ok(hydratedData.date instanceof Date, 'date should be deserialized to a Date object');
assert.equal(hydratedData.date.toISOString(), '2026-09-03T12:00:00.000Z');
}
// 5. hydrate restores mutations into MutationCache
{
const sourceClient = new QueryClient();
sourceClient.getMutationCache().build(sourceClient, {
mutationKey: ['offline-sync', 'task-1'],
scope: { id: 'sync-scope' },
}, {
context: undefined,
data: undefined,
error: null,
failureCount: 0,
failureReason: null,
isPaused: true,
status: 'pending',
variables: { taskId: 'task-1', action: 'complete' },
submittedAt: 1700000000000,
});
const dehydrated = dehydrateClient(sourceClient);
assert.equal(dehydrated.mutations.length, 1);
const targetClient = new QueryClient();
hydrate(targetClient, dehydrated);
const mutations = targetClient.getMutationCache().getAll();
assert.equal(mutations.length, 1);
assert.deepEqual(mutations[0].options.mutationKey, ['offline-sync', 'task-1']);
assert.equal(mutations[0].state.status, 'pending');
assert.equal(mutations[0].state.isPaused, true);
assert.deepEqual(mutations[0].state.variables, { taskId: 'task-1', action: 'complete' });
}
// 6. hydrate applies defaultOptions.queries to hydrated query options
{
const client = new QueryClient();
const dehydrated = {
mutations: [],
queries: [
{
queryKey: ['configured-query'],
queryHash: JSON.stringify(['configured-query']),
state: {
data: 'sample payload',
dataUpdatedAt: Date.now(),
error: null,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
},
},
],
};
hydrate(client, dehydrated, {
defaultOptions: {
queries: {
staleTime: 60000,
gcTime: 120000,
},
},
});
const query = client.getQueryCache().find({ queryKey: ['configured-query'] });
assert.ok(query, 'query should exist in cache');
assert.equal(query.options.staleTime, 60000);
assert.equal(query.options.gcTime, 120000);
}
// 7. hydrate preserves query metadata across cache instances
{
const sourceClient = new QueryClient();
await sourceClient.prefetchQuery({
queryKey: ['meta-test'],
queryFn: () => ({ status: 'active' }),
meta: { authRequired: true, role: 'admin' },
});
const dehydrated = dehydrate(sourceClient);
assert.ok(dehydrated.queries.length > 0);
assert.deepEqual(dehydrated.queries[0].meta, { authRequired: true, role: 'admin' });
const targetClient = new QueryClient();
hydrate(targetClient, dehydrated);
const query = targetClient.getQueryCache().find({ queryKey: ['meta-test'] });
assert.ok(query, 'hydrated query must exist in target cache');
assert.deepEqual(query.meta, { authRequired: true, role: 'admin' });
}
console.log('Contract tests passed successfully.');
오리진 시더
익명