DocsCore
API client and hashing
The Generic Translation class for calling the REST API from JavaScript, plus the hashing functions.
On this page
Hashing
import { hashSource, hashSourceSync } from "@generic-translation/core";
function hashSource(input: { source: string; context?: string; dataFormat?: "ICU" | "STRING" }): Promise<string>;
function hashSourceSync(input: { source: string; context?: string; dataFormat?: "ICU" | "STRING" }): string;
Both return the 32-character content hash and always agree with each other. hashSource uses WebCrypto. hashSourceSync is a pure-JavaScript SHA-256 for synchronous code paths.
The GenericTranslation client
A small typed wrapper over the REST API. It works anywhere fetch exists.
import { GenericTranslation } from "@generic-translation/core";
const genericTranslation = new GenericTranslation({
projectId: process.env.GENERIC_TRANSLATION_PROJECT_ID,
apiKey: process.env.GENERIC_TRANSLATION_API_KEY,
});
Options
| Option | Default | Meaning |
|---|---|---|
projectId |
GENERIC_TRANSLATION_PROJECT_ID |
Project to act on. When unset, authenticated calls use the literal current, which resolves to the API key’s own project. |
apiKey |
GENERIC_TRANSLATION_API_KEY |
A project API key (gt-api-…). |
baseUrl |
GENERIC_TRANSLATION_API_URL, then DEFAULT_BASE_URL |
Change it to target a self-hosted API. |
sourceLocale |
none | Sent as sourceLocale on requests that accept it. |
fetch |
global fetch |
A custom implementation for tests, proxies or older runtimes. |
Never construct a client with an API key in browser code. In the browser, the only method you should need is
fetchCdn, which sends no credentials.
Runtime translation
const result = await genericTranslation.translate("Save changes", "fr", { context: "Button label" });
// { success: true, translation: "Enregistrer les modifications", hash: "…", cached: false }
const results = await genericTranslation.translateMany(
[{ source: "Save" }, { source: "Cancel" }, { source: "{count, plural, one {# file} other {# files}}" }],
"ja",
);
translate(source, targetLocale, metadata?)translates one string.metadatamay carrycontext,dataFormatandid.translateMany(requests, targetLocale)translates a list. Results line up with the requests by index. The API accepts 50 per call; the client splits longer lists into batches of 50 and sends them one after another.- Results are cached on the server by hash and locale, so repeating a call is cheap.
cachedtells you whether this one was. - A string that fails comes back as
{ success: false, error }rather than throwing, so one bad string does not sink a batch.
Requires the translations:generate permission.
Batch jobs
const { jobId, total, cached } = await genericTranslation.submitEntries({
locales: ["es", "fr"],
entries: [
{ source: "Hello <0>{name}</0>", context: "Dashboard greeting" },
{ source: "Sign out", id: "nav.signout" },
],
});
const job = await genericTranslation.waitForJob(jobId, {
onProgress: (j) => console.log(`${j.completed}/${j.total}`),
});
if (job.status === "failed") throw new Error(job.error);
const es = await genericTranslation.getTranslations("es");
| Method | Returns | Notes |
|---|---|---|
submitEntries(body) |
{ jobId, total, cached } |
Up to 2000 entries per call. total counts entry × locale pairs that needed work; cached counts pairs that already had a translation. Needs translations:enqueue. |
getJob(jobId) |
Job |
One poll. |
waitForJob(jobId, opts?) |
Job |
Polls until completed or failed. intervalMs defaults to 1500 and timeoutMs to 10 minutes; on timeout it rejects with a GenericTranslationApiError whose code is timeout. Check job.status on the result. |
getTranslations(locale, { branch }?) |
Record<hash, string> |
The latest map, including unpublished translations. Needs project:read. |
Publishing and the CDN
await genericTranslation.publish({ locales: ["es", "fr"] }); // { published: ["es", "fr"], version }
const map = await genericTranslation.fetchCdn("es"); // public, no key needed
publish needs translations:write. Omit locales to publish every project locale. fetchCdn needs a real projectId (not current), because it is unauthenticated.
Files
const { fileId, jobId } = await genericTranslation.uploadFile({
fileName: "guide.md",
fileFormat: "md",
content: await readFile("docs/guide.md", "utf8"),
locales: ["de"],
});
await genericTranslation.waitForJob(jobId);
const file = await genericTranslation.downloadFile(fileId, "de");
if (file.status === "ready") await writeFile("docs/de/guide.md", file.content!);
listFiles() returns every file in the project with per-locale status. See files for formats.
Project
getProject() returns the Project the client is configured for.
Errors
Every non-2xx response is thrown as a GenericTranslationApiError.
import { GenericTranslationApiError } from "@generic-translation/core";
try {
await genericTranslation.publish();
} catch (e) {
if (e instanceof GenericTranslationApiError && e.code === "permission_missing") {
// the key lacks translations:write
} else {
throw e;
}
}
| Property | Meaning |
|---|---|
status |
HTTP status, or 0 for failures that never got a response. |
code |
One of the API error codes, or a client-side code: network_error, invalid_response, timeout. |
message |
Human-readable text from the API. |
Types
All request and response shapes are exported as types: Project, ProjectStats, Job, TranslationResult, SubmitEntriesBody, UploadFileBody, FileRecord, StringRecord, CdnManifest, WebhookEvent, ApiKeyPermission, OrgRole, FileFormat, GenericTranslationConfig and more.
import type { Job, Project, WebhookEvent } from "@generic-translation/core";
Something wrong or unclear on this page? Open an issue.