CodeSampleX

Beispiel

@tanstack/query-core 5.90.20: hydrate

Verifiziertes Beispiel für npm @tanstack/query-core 5.90.20: hydrate. Der Vertrag lief auf node 22 · linux debian/x64 · docker und bestand.

sha256:021ab56c5e26187efdb331a0467dc0fa32b757d47b943a47051e90137bef61e1

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
verify hydrate in pkg:npm/%40tanstack/query-core@5.90.20
Pakete
Symbole
  • hydrate
Umgebung
node 22.23.2
Erstellt
2026-09-03T09:52:21Z

Contract

  1. hydrate populates query cache from dehydrated state queries
  2. hydrate ignores non-object or empty dehydrated state gracefully
  3. hydrate respects dataUpdatedAt and does not overwrite newer query data
  4. deserializeData option transforms dehydrated data during hydration
  5. hydrate restores mutations into MutationCache
  6. hydrate applies defaultOptions.queries to hydrated query options
  7. hydrate preserves query metadata across cache instances

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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 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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "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"
  }
}
spec.json
{
  "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"
  ]
}
src/index.mjs
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;
test/contract.mjs
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.');

Ursprungs-Seeder

anonym