CodeSampleX

Exemple

i18next 24.2.3

Échantillon vérifié pour npm i18next 24.2.3. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi : i18next exports createInstance…

sha256:9bd66cfbbf2a09f3c7acb386c778f6581c5d8ff1055eca8247b890b34eddade8

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21

Cas

HOW
Objectif
verify pkg:npm/i18next@24.2.3
Paquets
Créé
2026-08-21T14:12:09Z

Contrat

  1. i18next exports createInstance and init functions
  2. init configures language and translation resources for basic string resolution
  3. translate supports variable interpolation into translation templates
  4. translate supports pluralization rules for singular and plural counts
  5. translate resolves nested key hierarchies using dot notation
  6. translate falls back to fallbackLng when translation is missing in active language
  7. changeLanguage dynamically switches the active language for translations
  8. addResourceBundle adds translation resources dynamically at runtime
  9. translate supports context-specific keys using context options

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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/i18next@24.2.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/i18next@24.2.3

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:f4ac1702becfcd4de2c52b045d7a9866136217190e55b4ba7827132a53349d54","contract":["i18next exports createInstance and init functions","init configures language and translation resources for basic string resolution","translate supports variable interpolation into translation templates","translate supports pluralization rules for singular and plural counts","translate resolves nested key hierarchies using dot notation","translate falls back to fallbackLng when translation is missing in active language","changeLanguage dynamically switches the active language for translations","addResourceBundle adds translation resources dynamically at runtime","translate supports context-specific keys using context options"],"goal":"verify pkg:npm/i18next@24.2.3","kind":"HOW","packages":["pkg:npm/i18next@24.2.3"],"schemaVersion":1},"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/i18next@24.2.3"],"schemaVersion":1,"subject":"pkg:npm/i18next@24.2.3","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "verify-i18next",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-i18next",
      "version": "1.0.0",
      "dependencies": {
        "i18next": "24.2.3"
      }
    },
    "node_modules/@babel/runtime": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
      "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/i18next": {
      "version": "24.2.3",
      "resolved": "https://registry.npmjs.org/i18next/-/i18next-24.2.3.tgz",
      "integrity": "sha512-lfbf80OzkocvX7nmZtu7nSTNbrTYR52sLWxPtlXX1zAhVw8WEnFk4puUkCR4B1dNQwbSpEHHHemcZu//7EcB7A==",
      "funding": [
        {
          "type": "individual",
          "url": "https://locize.com"
        },
        {
          "type": "individual",
          "url": "https://locize.com/i18next.html"
        },
        {
          "type": "individual",
          "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "@babel/runtime": "^7.26.10"
      },
      "peerDependencies": {
        "typescript": "^5"
      },
      "peerDependenciesMeta": {
        "typescript": {
          "optional": true
        }
      }
    }
  }
}
package.json
{
  "name": "verify-i18next",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "i18next": "24.2.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/i18next@24.2.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/i18next@24.2.3"
  ]
}
src/index.mjs
import i18next from 'i18next';

/**
 * Creates and initializes a new isolated i18next instance.
 * @param {object} options - Initialization options for i18next.
 * @returns {Promise<import('i18next').i18n>} The initialized i18next instance.
 */
export async function createI18nInstance(options = {}) {
  const instance = i18next.createInstance();
  await instance.init(options);
  return instance;
}

/**
 * Translates a key using the provided i18next instance.
 * @param {import('i18next').i18n} instance - The i18next instance.
 * @param {string|string[]} key - The translation key.
 * @param {object} [options] - Options such as interpolation values or fallback.
 * @returns {string} The translated string.
 */
export function translate(instance, key, options) {
  return instance.t(key, options);
}

/**
 * Changes the active language of an i18next instance.
 * @param {import('i18next').i18n} instance - The i18next instance.
 * @param {string} lng - Language code to switch to.
 * @returns {Promise<Function>} T function resolved after language switch.
 */
export async function switchLanguage(instance, lng) {
  return await instance.changeLanguage(lng);
}

/**
 * Adds a resource bundle to the i18next instance.
 * @param {import('i18next').i18n} instance - The i18next instance.
 * @param {string} lng - Language code.
 * @param {string} ns - Namespace.
 * @param {object} resources - Key-value translation dictionary.
 * @param {boolean} [deep=true] - Whether to deep merge.
 * @param {boolean} [overwrite=true] - Whether to overwrite existing keys.
 */
export function addTranslations(instance, lng, ns, resources, deep = true, overwrite = true) {
  instance.addResourceBundle(lng, ns, resources, deep, overwrite);
}

export default i18next;
test/contract.mjs
import assert from 'node:assert';
import i18next, {
  createI18nInstance,
  translate,
  switchLanguage,
  addTranslations
} from '../src/index.mjs';

// 1. i18next default export and instance creation
assert.strictEqual(typeof i18next.createInstance, 'function', 'i18next.createInstance must be a function');
assert.strictEqual(typeof i18next.init, 'function', 'i18next.init must be a function');

const i18n = await createI18nInstance({
  lng: 'en',
  fallbackLng: 'en',
  resources: {
    en: {
      translation: {
        hello: 'Hello World',
        greeting: 'Hello, {{name}}!',
        item_one: '{{count}} item',
        item_other: '{{count}} items',
        user: {
          profile: {
            title: 'User Profile'
          }
        },
        friend: 'A friend',
        friend_male: 'A boyfriend',
        friend_female: 'A girlfriend',
        only_in_en: 'English only fallback'
      }
    },
    de: {
      translation: {
        hello: 'Hallo Welt',
        greeting: 'Hallo, {{name}}!',
        item_one: '{{count}} Element',
        item_other: '{{count}} Elemente',
        user: {
          profile: {
            title: 'Benutzerprofil'
          }
        }
      }
    }
  },
  interpolation: {
    escapeValue: false
  }
});

// 2. Basic key translation
assert.strictEqual(translate(i18n, 'hello'), 'Hello World', 'Translates basic string key');

// 3. Variable interpolation
assert.strictEqual(
  translate(i18n, 'greeting', { name: 'Alice' }),
  'Hello, Alice!',
  'Interpolates variables into translation template'
);

// 4. Pluralization support
assert.strictEqual(translate(i18n, 'item', { count: 1 }), '1 item', 'Handles singular plural form');
assert.strictEqual(translate(i18n, 'item', { count: 5 }), '5 items', 'Handles plural form');

// 5. Nested key resolution with dot notation
assert.strictEqual(
  translate(i18n, 'user.profile.title'),
  'User Profile',
  'Resolves nested key hierarchy'
);

// 6. Fallback language lookup
assert.strictEqual(
  i18n.t('only_in_en', { lng: 'de' }),
  'English only fallback',
  'Falls back to fallbackLng when translation is missing in active language'
);

// 7. Dynamic language switching
await switchLanguage(i18n, 'de');
assert.strictEqual(i18n.language, 'de', 'Active language updated to de');
assert.strictEqual(translate(i18n, 'hello'), 'Hallo Welt', 'Translates according to switched language');
assert.strictEqual(translate(i18n, 'item', { count: 2 }), '2 Elemente', 'Pluralization in German');

// 8. Runtime resource bundle addition
addTranslations(i18n, 'fr', 'translation', {
  hello: 'Bonjour le monde'
});
assert.strictEqual(i18n.hasResourceBundle('fr', 'translation'), true, 'French resource bundle added');
assert.strictEqual(i18n.t('hello', { lng: 'fr' }), 'Bonjour le monde', 'Translates dynamically added resource');

// 9. Context-based translation
assert.strictEqual(
  i18n.t('friend', { lng: 'en', context: 'male' }),
  'A boyfriend',
  'Translates context key with male context'
);
assert.strictEqual(
  i18n.t('friend', { lng: 'en', context: 'female' }),
  'A girlfriend',
  'Translates context key with female context'
);

console.log('Contract tests passed successfully.');

Seeder d'origine

anonyme