generaltranslation 9.5.5 → 9.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/adapter/createGtApi.d.ts +2 -2
- package/dist/adapter/createGtApi.js +2 -2
- package/dist/{derive-CS-paSZ9.cjs → derive-DPDgh_1v.cjs} +4 -4
- package/dist/derive-DPDgh_1v.cjs.map +1 -0
- package/dist/{derive-Ctj9wXCT.mjs → derive-DZR18WqK.mjs} +4 -4
- package/dist/derive-DZR18WqK.mjs.map +1 -0
- package/dist/id.d.cts +1 -1
- package/dist/id.d.mts +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +2 -2
- package/dist/internal.cjs +3 -3
- package/dist/internal.cjs.map +1 -1
- package/dist/internal.d.cts +3 -3
- package/dist/internal.d.mts +3 -3
- package/dist/internal.mjs +3 -3
- package/dist/internal.mjs.map +1 -1
- package/dist/logging/errors.d.ts +0 -1
- package/dist/logging/errors.js +0 -9
- package/dist/runtime.cjs +1 -1
- package/dist/runtime.d.cts +1 -1
- package/dist/runtime.d.mts +1 -1
- package/dist/runtime.mjs +1 -1
- package/dist/{runtimeTranslate-_gLYFBvE.cjs → runtimeTranslate-B8BLxD_U.cjs} +3 -34
- package/dist/runtimeTranslate-B8BLxD_U.cjs.map +1 -0
- package/dist/{runtimeTranslate-CI936gg9.mjs → runtimeTranslate-CRWJMYly.mjs} +3 -34
- package/dist/runtimeTranslate-CRWJMYly.mjs.map +1 -0
- package/dist/translate/runtimeTranslate.js +1 -10
- package/dist/translate/utils/unwrapApiResult.d.ts +0 -3
- package/dist/translate/utils/unwrapApiResult.js +0 -3
- package/dist/{types-CEsh60Yt.d.mts → types-BxgnFr8M.d.cts} +3 -3
- package/dist/{types-yByDbKnV.d.cts → types-Ix4SHG5H.d.mts} +3 -3
- package/dist/types-dir/transformations.d.ts +2 -2
- package/dist/types.d.cts +1 -1
- package/dist/types.d.mts +1 -1
- package/dist/utils/minify.js +1 -1
- package/package.json +2 -2
- package/dist/derive-CS-paSZ9.cjs.map +0 -1
- package/dist/derive-Ctj9wXCT.mjs.map +0 -1
- package/dist/runtimeTranslate-CI936gg9.mjs.map +0 -1
- package/dist/runtimeTranslate-_gLYFBvE.cjs.map +0 -1
- package/dist/translate/utils/validateResponse.d.ts +0 -1
- package/dist/translate/utils/validateResponse.js +0 -72
package/dist/internal.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.mjs","names":[],"sources":["../src/settings/plurals.ts","../src/locales/getPluralForm.ts","../src/utils/minify.ts","../src/derive/indexVars.ts","../src/derive/extractVars.ts","../src/derive/condenseVars.ts"],"sourcesContent":["export const pluralForms = [\n 'singular',\n 'plural',\n 'dual',\n 'zero',\n 'one',\n 'two',\n 'few',\n 'many',\n 'other',\n] as const;\nexport type PluralType = (typeof pluralForms)[number];\nexport function isAcceptedPluralForm(form: string): form is PluralType {\n return pluralForms.includes(form as (typeof pluralForms)[number]);\n}\n","import { getCachedPluralRules } from '@generaltranslation/format/internal';\n\nimport { pluralForms, PluralType } from '../settings/plurals';\nimport { libraryDefaultLocale } from '../settings/settings';\n\n/**\n * Given a number and a list of allowed plural forms, return the plural form that best fits the number.\n *\n * @param {number} n - The number to determine the plural form for.\n * @param {PluralType[]} forms - The allowed plural forms.\n * @returns {PluralType} The determined plural form, or an empty string if none fit.\n */\nexport function _getPluralForm(\n n: number,\n forms: readonly PluralType[] = pluralForms,\n locales: string[] = [libraryDefaultLocale]\n): PluralType | '' {\n const pluralRules = getCachedPluralRules(locales);\n const provisionalBranchName = pluralRules.select(n);\n // aliases\n const absN = Math.abs(n);\n // 0\n if (absN === 0 && forms.includes('zero')) return 'zero'; // override\n // 1\n if (absN === 1) {\n if (forms.includes('singular')) return 'singular'; // override\n if (forms.includes('one')) return 'one'; // override\n }\n if (provisionalBranchName === 'one' && forms.includes('singular'))\n return 'singular';\n // 2\n if (absN === 2) {\n if (forms.includes('dual')) return 'dual'; // override\n if (forms.includes('two')) return 'two'; // override\n }\n if (provisionalBranchName === 'two' && forms.includes('dual')) return 'dual';\n // fallbacks\n if (forms.includes(provisionalBranchName)) return provisionalBranchName;\n if (forms.includes('plural')) return 'plural';\n if (forms.includes('other')) return 'other';\n return '';\n}\n","import { VariableTransformationSuffix, VariableType } from '../types';\n\nconst VARIABLE_TRANSFORMATION_SUFFIXES_TO_MINIFIED_NAMES = {\n variable: 'v',\n number: 'n',\n datetime: 'd',\n currency: 'c',\n
|
|
1
|
+
{"version":3,"file":"internal.mjs","names":[],"sources":["../src/settings/plurals.ts","../src/locales/getPluralForm.ts","../src/utils/minify.ts","../src/derive/indexVars.ts","../src/derive/extractVars.ts","../src/derive/condenseVars.ts"],"sourcesContent":["export const pluralForms = [\n 'singular',\n 'plural',\n 'dual',\n 'zero',\n 'one',\n 'two',\n 'few',\n 'many',\n 'other',\n] as const;\nexport type PluralType = (typeof pluralForms)[number];\nexport function isAcceptedPluralForm(form: string): form is PluralType {\n return pluralForms.includes(form as (typeof pluralForms)[number]);\n}\n","import { getCachedPluralRules } from '@generaltranslation/format/internal';\n\nimport { pluralForms, PluralType } from '../settings/plurals';\nimport { libraryDefaultLocale } from '../settings/settings';\n\n/**\n * Given a number and a list of allowed plural forms, return the plural form that best fits the number.\n *\n * @param {number} n - The number to determine the plural form for.\n * @param {PluralType[]} forms - The allowed plural forms.\n * @returns {PluralType} The determined plural form, or an empty string if none fit.\n */\nexport function _getPluralForm(\n n: number,\n forms: readonly PluralType[] = pluralForms,\n locales: string[] = [libraryDefaultLocale]\n): PluralType | '' {\n const pluralRules = getCachedPluralRules(locales);\n const provisionalBranchName = pluralRules.select(n);\n // aliases\n const absN = Math.abs(n);\n // 0\n if (absN === 0 && forms.includes('zero')) return 'zero'; // override\n // 1\n if (absN === 1) {\n if (forms.includes('singular')) return 'singular'; // override\n if (forms.includes('one')) return 'one'; // override\n }\n if (provisionalBranchName === 'one' && forms.includes('singular'))\n return 'singular';\n // 2\n if (absN === 2) {\n if (forms.includes('dual')) return 'dual'; // override\n if (forms.includes('two')) return 'two'; // override\n }\n if (provisionalBranchName === 'two' && forms.includes('dual')) return 'dual';\n // fallbacks\n if (forms.includes(provisionalBranchName)) return provisionalBranchName;\n if (forms.includes('plural')) return 'plural';\n if (forms.includes('other')) return 'other';\n return '';\n}\n","import { VariableTransformationSuffix, VariableType } from '../types';\n\nconst VARIABLE_TRANSFORMATION_SUFFIXES_TO_MINIFIED_NAMES = {\n variable: 'v',\n number: 'n',\n datetime: 'd',\n currency: 'c',\n relativetime: 'rt',\n} as const;\n\nexport function minifyVariableType(\n variableType: VariableTransformationSuffix\n): VariableType {\n return VARIABLE_TRANSFORMATION_SUFFIXES_TO_MINIFIED_NAMES[variableType];\n}\n","import { VAR_IDENTIFIER } from './utils/constants';\nimport { traverseIcu } from './utils/traverseIcu';\nimport { GTUnindexedSelectElement } from './utils/types';\nimport { isGTUnindexedSelectElement } from './utils/traverseHelpers';\nimport type { IcuMessage } from '@generaltranslation/format/types';\n\ntype Location = {\n start: number;\n end: number;\n otherStart: number;\n otherEnd: number;\n};\n\n/**\n * Given an ICU string adds identifiers to each _gt_ placeholder\n * indexVars('Hello {_gt_} {_gt_} World') => 'Hello {_gt_1_} {_gt_2_} World'\n */\nexport function indexVars(icuString: IcuMessage): string {\n // Check if the string contains _gt_\n if (!icuString.includes(VAR_IDENTIFIER)) {\n return icuString;\n }\n\n // Record the location of the variable\n const variableLocations: Location[] = [];\n function visitor(child: GTUnindexedSelectElement): void {\n variableLocations.push({\n start: child.location?.start.offset ?? 0,\n end: child.location?.end.offset ?? 0,\n otherStart: child.options.other.location?.start.offset ?? 0,\n otherEnd: child.options.other.location?.end.offset ?? 0,\n });\n }\n\n // Find all variable identifiers.\n traverseIcu({\n icuString,\n shouldVisit: isGTUnindexedSelectElement,\n visitor,\n options: { recurseIntoVisited: false, captureLocation: true },\n });\n\n // Index each variable and collapse the other option.\n const result = [];\n let current = 0;\n for (let i = 0; i < variableLocations.length; i++) {\n const { start, end, otherStart, otherEnd } = variableLocations[i];\n // Before the variable\n result.push(icuString.slice(current, start));\n // Replace the variable with the new identifier (+1 is for the curly brace)\n result.push(icuString.slice(start, start + VAR_IDENTIFIER.length + 1));\n\n // Add the new identifier.\n result.push(String(i + 1));\n // After the variable\n result.push(icuString.slice(start + VAR_IDENTIFIER.length + 1, otherStart));\n // Before the other option\n result.push('{}');\n // The other option\n result.push(icuString.slice(otherEnd, end));\n current = end;\n }\n result.push(icuString.slice(current, icuString.length));\n\n return result.join('');\n}\n","import { VAR_IDENTIFIER } from './utils/constants';\nimport { isGTUnindexedSelectElement } from './utils/traverseHelpers';\nimport { traverseIcu } from './utils/traverseIcu';\nimport { GTUnindexedSelectElement } from './utils/types';\n/**\n * Given an unindexed ICU string, extracts all the _gt_ variables and an indexed mapping of the variable to the values\n *\n * extractVars('Hello {_gt_, select, other {World}}') => { _gt_1: 'World' }\n *\n * @param {string} icuString - The ICU string to extract variables from.\n * @returns {Record<string, string>} A mapping of the variable to the value.\n */\nexport function extractVars(icuString: string): Record<string, string> {\n // Check if the string contains _gt_\n if (!icuString.includes(VAR_IDENTIFIER)) {\n return {};\n }\n\n // Extract all the _gt_# variables\n let index = 1;\n const variables: Record<string, string> = {};\n function visitor(child: GTUnindexedSelectElement): void {\n variables[child.value + index] = child.options.other.value.length\n ? child.options.other.value[0]?.value\n : '';\n index += 1;\n }\n\n traverseIcu({\n icuString,\n shouldVisit: isGTUnindexedSelectElement,\n visitor,\n options: { recurseIntoVisited: false },\n });\n\n return variables;\n}\n","import { printAST, TYPE, type ArgumentElement } from '@generaltranslation/icu';\nimport { traverseIcu } from './utils/traverseIcu';\nimport { VAR_IDENTIFIER } from './utils/constants';\nimport { GTIndexedSelectElement } from './utils/types';\nimport { isGTIndexedSelectElement } from './utils/traverseHelpers';\ninterface GTIndexedArgumentElement extends ArgumentElement {\n value: `${typeof VAR_IDENTIFIER}${number}`;\n}\n\nconst CONTAINS_INDEXED_GT_REGEX = new RegExp(`${VAR_IDENTIFIER}\\\\d+`);\n\n/**\n * Given an indexed ICU string, condenses any select to an argument\n * Unindexed _gt_ source strings and indexed _gt_# translation strings\n * are mutually exclusive.\n * indexVars('Hello {_gt_1, select, other {World}}') => 'Hello {_gt_1}'\n * @param {string} icuString - The ICU string to condense.\n * @returns {string} The condensed ICU string.\n */\nexport function condenseVars(icuString: string): string {\n // Check if the string contains an indexed _gt_ identifier.\n if (!CONTAINS_INDEXED_GT_REGEX.test(icuString)) {\n return icuString;\n }\n\n // Replace with argument\n function visitor(child: GTIndexedSelectElement): void {\n (child as unknown as GTIndexedArgumentElement).type = TYPE.argument;\n Reflect.deleteProperty(child, 'options');\n }\n\n const ast = traverseIcu({\n icuString,\n shouldVisit: isGTIndexedSelectElement,\n visitor,\n options: { recurseIntoVisited: false },\n });\n\n // Serialize\n return printAST(ast);\n}\n"],"mappings":";;;;;;;;AAAA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAgB,qBAAqB,MAAkC;AACrE,QAAO,YAAY,SAAS,KAAqC;;;;;;;;;;;ACDnE,SAAgB,eACd,GACA,QAA+B,aAC/B,UAAoB,CAAA,KAAsB,EACzB;CAEjB,MAAM,wBADc,qBAAqB,QACA,CAAC,OAAO,EAAE;CAEnD,MAAM,OAAO,KAAK,IAAI,EAAE;AAExB,KAAI,SAAS,KAAK,MAAM,SAAS,OAAO,CAAE,QAAO;AAEjD,KAAI,SAAS,GAAG;AACd,MAAI,MAAM,SAAS,WAAW,CAAE,QAAO;AACvC,MAAI,MAAM,SAAS,MAAM,CAAE,QAAO;;AAEpC,KAAI,0BAA0B,SAAS,MAAM,SAAS,WAAW,CAC/D,QAAO;AAET,KAAI,SAAS,GAAG;AACd,MAAI,MAAM,SAAS,OAAO,CAAE,QAAO;AACnC,MAAI,MAAM,SAAS,MAAM,CAAE,QA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,YAAU;;AAEZ,QAAO,KAAK,UAAU,MAAM,SAAS,UAAU,OAAO,CAAC;AAEvD,QAAO,OAAO,KAAK,GAAG;;;;;;;;;;;;ACpDxB,SAAgB,YAAY,WAA2C;AAErE,KAAI,CAAC,UAAU,SAAA,OAAwB,CACrC,QAAO,EAAE;CAIX,IAAI,QAAQ;CACZ,MAAM,YAAoC,EAAE;CAC5C,SAAS,QAAQ,OAAuC;AACtD,YAAU,MAAM,QAAQ,SAAS,MAAM,QAAQ,MAAM,MAAM,SACvD,MAAM,QAAQ,MAAM,MAAM,IAAI,QAC9B;AACJ,WAAS;;AAGX,aAAY;EACV;EACA,aAAa;EACb;EACA,SAAS,EAAE,oBAAoB,OAAO;EACvC,CAAC;AAEF,QAAO;;;;AC1BT,MAAM,4BAA4B,IAAI,OAAO,GAAG,eAAe,MAAM;;;;;;;;;AAUrE,SAAgB,aAAa,WAA2B;AAEtD,KAAI,CAAC,0BAA0B,KAAK,UAAU,CAC5C,QAAO;CAIT,SAAS,QAAQ,OAAqC;AACnD,QAA8C,OAAO,KAAK;AAC3D,UAAQ,eAAe,OAAO,UAAU;;AAW1C,QAAO,SARK,YAAY;EACtB;EACA,aAAa;EACb;EACA,SAAS,EAAE,oBAAoB,OAAO;EACvC,CAGkB,CAAC"}
|
package/dist/logging/errors.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
export declare const translationTimeoutError: (timeout: number) => string;
|
|
2
2
|
export declare const translationRequestFailedError: (error: string) => string;
|
|
3
|
-
export declare const apiError: (status: number, statusText: string, error: string) => string;
|
|
4
3
|
export declare const noTargetLocaleProvidedError: (functionName: string) => string;
|
|
5
4
|
export declare const noSourceLocaleProvidedError: (functionName: string) => string;
|
|
6
5
|
export declare const noProjectIdProvidedError: (functionName: string) => string;
|
package/dist/logging/errors.js
CHANGED
|
@@ -17,15 +17,6 @@ export var translationRequestFailedError = function (error) {
|
|
|
17
17
|
details: error,
|
|
18
18
|
});
|
|
19
19
|
};
|
|
20
|
-
export var apiError = function (status, statusText, error) {
|
|
21
|
-
return createDiagnosticMessage({
|
|
22
|
-
source: GT_SOURCE,
|
|
23
|
-
severity: 'Error',
|
|
24
|
-
whatHappened: "The translation API returned ".concat(status, " ").concat(statusText),
|
|
25
|
-
fix: 'Check the request configuration and try again',
|
|
26
|
-
details: error,
|
|
27
|
-
});
|
|
28
|
-
};
|
|
29
20
|
export var noTargetLocaleProvidedError = function (functionName) {
|
|
30
21
|
return createDiagnosticMessage({
|
|
31
22
|
source: GT_SOURCE,
|
package/dist/runtime.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_runtimeTranslate = require("./runtimeTranslate-
|
|
2
|
+
const require_runtimeTranslate = require("./runtimeTranslate-B8BLxD_U.cjs");
|
|
3
3
|
let _generaltranslation_format = require("@generaltranslation/format");
|
|
4
4
|
//#region src/runtime.ts
|
|
5
5
|
/**
|
package/dist/runtime.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as TranslationRequestConfig, Ft as TranslateManyEntry, It as TranslateOptions, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult } from "./types-
|
|
1
|
+
import { D as TranslationRequestConfig, Ft as TranslateManyEntry, It as TranslateOptions, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult } from "./types-BxgnFr8M.cjs";
|
|
2
2
|
import { UserTokenProvider } from "@generaltranslation/api";
|
|
3
3
|
import { CustomMapping, CustomRegionMapping, CutoffFormatOptions, FormatVariables, LocaleProperties, StringFormat } from "@generaltranslation/format/types";
|
|
4
4
|
import { LocaleConfig } from "@generaltranslation/format";
|
package/dist/runtime.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as TranslationRequestConfig, Ft as TranslateManyEntry, It as TranslateOptions, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult } from "./types-
|
|
1
|
+
import { D as TranslationRequestConfig, Ft as TranslateManyEntry, It as TranslateOptions, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult } from "./types-Ix4SHG5H.mjs";
|
|
2
2
|
import { UserTokenProvider } from "@generaltranslation/api";
|
|
3
3
|
import { LocaleConfig } from "@generaltranslation/format";
|
|
4
4
|
import { CustomMapping, CustomRegionMapping, CutoffFormatOptions, FormatVariables, LocaleProperties, StringFormat } from "@generaltranslation/format/types";
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as noSourceLocaleProvidedError, f as noTargetLocaleProvidedError, l as invalidLocaleError, n as translateMany, t as translate, u as invalidLocalesError } from "./runtimeTranslate-
|
|
1
|
+
import { d as noSourceLocaleProvidedError, f as noTargetLocaleProvidedError, l as invalidLocaleError, n as translateMany, t as translate, u as invalidLocalesError } from "./runtimeTranslate-CRWJMYly.mjs";
|
|
2
2
|
import { LocaleConfig, getRegionProperties, isValidLocale, requiresTranslation, resolveAliasLocale, resolveCanonicalLocale } from "@generaltranslation/format";
|
|
3
3
|
//#region src/runtime.ts
|
|
4
4
|
/**
|
|
@@ -19,13 +19,6 @@ const translationTimeoutError = (timeout) => require_diagnostics.createDiagnosti
|
|
|
19
19
|
whatHappened: `Translation request timed out after ${timeout}ms`,
|
|
20
20
|
fix: "Try again, or increase the request timeout if the source content is large"
|
|
21
21
|
});
|
|
22
|
-
const apiError = (status, statusText, error) => require_diagnostics.createDiagnosticMessage({
|
|
23
|
-
source: GT_SOURCE,
|
|
24
|
-
severity: "Error",
|
|
25
|
-
whatHappened: `The translation API returned ${status} ${statusText}`,
|
|
26
|
-
fix: "Check the request configuration and try again",
|
|
27
|
-
details: error
|
|
28
|
-
});
|
|
29
22
|
const noTargetLocaleProvidedError = (functionName) => require_diagnostics.createDiagnosticMessage({
|
|
30
23
|
source: GT_SOURCE,
|
|
31
24
|
severity: "Error",
|
|
@@ -306,9 +299,6 @@ async function fetchWithTimeout(url, options, timeoutMs = defaultTimeout, fetchI
|
|
|
306
299
|
function isErrorResult(error) {
|
|
307
300
|
return typeof error === "object" && error !== null && "error" in error && typeof error.error === "string";
|
|
308
301
|
}
|
|
309
|
-
function hasDecodedError(result) {
|
|
310
|
-
return isErrorResult(result.error) || typeof result.error === "string";
|
|
311
|
-
}
|
|
312
302
|
/**
|
|
313
303
|
* Unwraps a `@generaltranslation/api` SDK result, returning its data or
|
|
314
304
|
* throwing an `ApiError` built from the failed response.
|
|
@@ -319,22 +309,6 @@ function unwrapApiResult(result) {
|
|
|
319
309
|
throw result.error;
|
|
320
310
|
}
|
|
321
311
|
//#endregion
|
|
322
|
-
//#region src/translate/utils/validateResponse.ts
|
|
323
|
-
async function validateResponse(response) {
|
|
324
|
-
if (!response.ok) {
|
|
325
|
-
let errorMsg = "Unknown error";
|
|
326
|
-
try {
|
|
327
|
-
const text = await response.text();
|
|
328
|
-
try {
|
|
329
|
-
errorMsg = JSON.parse(text).error;
|
|
330
|
-
} catch {
|
|
331
|
-
errorMsg = text || "Unknown error";
|
|
332
|
-
}
|
|
333
|
-
} catch {}
|
|
334
|
-
throw new _generaltranslation_api.ApiError(apiError(response.status, response.statusText, errorMsg), response.status, errorMsg);
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
//#endregion
|
|
338
312
|
//#region src/translate/runtimeTranslate.ts
|
|
339
313
|
/**
|
|
340
314
|
* @internal
|
|
@@ -471,7 +445,7 @@ async function executeTranslationBatch(requests, globalMetadata, config) {
|
|
|
471
445
|
retryPolicy: "none",
|
|
472
446
|
timeoutMs: false
|
|
473
447
|
});
|
|
474
|
-
const
|
|
448
|
+
const runtimeResponse = unwrapApiResult(await (0, _generaltranslation_api.translate)({
|
|
475
449
|
body: {
|
|
476
450
|
requests: requestsObject,
|
|
477
451
|
targetLocale: globalMetadata.targetLocale,
|
|
@@ -482,12 +456,7 @@ async function executeTranslationBatch(requests, globalMetadata, config) {
|
|
|
482
456
|
}
|
|
483
457
|
},
|
|
484
458
|
client
|
|
485
|
-
});
|
|
486
|
-
if (result.data === void 0 && result.response && !hasDecodedError(result)) {
|
|
487
|
-
await validateResponse(result.response);
|
|
488
|
-
throw result.error;
|
|
489
|
-
}
|
|
490
|
-
const runtimeResponse = unwrapApiResult(result);
|
|
459
|
+
}));
|
|
491
460
|
const response = Object.fromEntries(Object.entries(runtimeResponse).map(([hash, translationResult]) => [hash, toTranslationResult(translationResult)]));
|
|
492
461
|
if (hashOrder) return hashOrder.map((hash) => response[hash] ?? {
|
|
493
462
|
success: false,
|
|
@@ -594,4 +563,4 @@ Object.defineProperty(exports, "validateAuth", {
|
|
|
594
563
|
}
|
|
595
564
|
});
|
|
596
565
|
|
|
597
|
-
//# sourceMappingURL=runtimeTranslate-
|
|
566
|
+
//# sourceMappingURL=runtimeTranslate-B8BLxD_U.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimeTranslate-B8BLxD_U.cjs","names":["createDiagnosticMessage","ModelProvider","ApiError","hashSource","createDiagnosticMessage"],"sources":["../src/settings/settings.ts","../src/settings/settingsUrls.ts","../src/logging/errors.ts","../src/logging/logger.ts","../src/adapter/modelProvider.ts","../src/translate/utils/fetchWithTimeout.ts","../src/translate/utils/unwrapApiResult.ts","../src/translate/runtimeTranslate.ts"],"sourcesContent":["export const libraryDefaultLocale = 'en' as const;\nexport const defaultTimeout = 60000;\n","export const defaultCacheUrl = 'https://cdn.gtx.dev' as const;\nexport const defaultBaseUrl = 'https://api.gtx.dev' as const;\nexport const defaultRuntimeApiUrl = 'https://api.gtx.dev' as const;\n","import { createDiagnosticMessage } from './diagnostics';\n\nconst GT_SOURCE = 'GT';\n\nexport const translationTimeoutError = (timeout: number) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Translation request timed out after ${timeout}ms`,\n fix: 'Try again, or increase the request timeout if the source content is large',\n });\n\nexport const translationRequestFailedError = (error: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: 'Translation request could not be completed',\n fix: 'Check your network connection and translation credentials, then try again',\n details: error,\n });\n\nexport const noTargetLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify targetLocale in the GT constructor`,\n });\n\nexport const noSourceLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify sourceLocale in the GT constructor`,\n });\n\nexport const noProjectIdProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified project ID`,\n fix: `Pass a project ID to \\`${functionName}\\` or specify projectId in the GT constructor`,\n });\n\nexport const noApiKeyProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified API key`,\n fix: `Pass an API key to \\`${functionName}\\` or specify apiKey in the GT constructor`,\n });\n\nexport const invalidLocaleError = (locale: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Locale \"${locale}\" is not valid`,\n fix: 'Use a valid BCP 47 locale code or add a custom mapping',\n });\n\nexport const invalidLocalesError = (locales: string[]) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `These locales are not valid: ${locales.join(', ')}`,\n fix: 'Use valid BCP 47 locale codes or add custom mappings',\n });\n","/**\n * Comprehensive logging system for the General Translation library.\n * Provides structured logging with multiple levels and configurable output.\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';\n\nexport type LogMetadataValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Date\n | Error\n | LogMetadataValue[]\n | { [key: string]: LogMetadataValue };\n\nexport type LogMetadata = Record<string, LogMetadataValue>;\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: Date;\n context?: string;\n metadata?: LogMetadata;\n}\n\nexport interface LoggerConfig {\n /** Minimum log level to output. */\n level: LogLevel;\n /** Whether to include timestamps in log output. */\n includeTimestamp: boolean;\n /** Whether to include context information. */\n includeContext: boolean;\n /** Custom prefix for all log messages. */\n prefix?: string;\n /** Whether to output to console (default: true) */\n enableConsole: boolean;\n /** Custom log handlers. */\n handlers?: LogHandler[];\n}\n\nexport interface LogHandler {\n handle(entry: LogEntry): void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n off: 4,\n};\n\nconst LOG_COLORS: Record<LogLevel, string> = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n off: '', // No color needed since 'off' level logs are never displayed\n};\n\nconst RESET_COLOR = '\\x1b[0m';\n\n/**\n * Get the configured log level from environment variable or default to 'warn'\n */\nfunction getConfiguredLogLevel(): LogLevel {\n if (typeof process !== 'undefined' && process.env?._GT_LOG_LEVEL) {\n const envLevel = process.env._GT_LOG_LEVEL.toLowerCase();\n if (envLevel in LOG_LEVELS) {\n return envLevel as LogLevel;\n }\n }\n return 'warn';\n}\n\n/**\n * Console log handler that outputs formatted messages to console\n */\nexport class ConsoleLogHandler implements LogHandler {\n private config: LoggerConfig;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n }\n\n handle(entry: LogEntry): void {\n const parts: string[] = [];\n\n // Add timestamp if enabled\n if (this.config.includeTimestamp) {\n parts.push(`[${entry.timestamp.toISOString()}]`);\n }\n\n // Add level with color\n const colorCode = LOG_COLORS[entry.level];\n const levelText = `[${entry.level.toUpperCase()}]`;\n parts.push(`${colorCode}${levelText}${RESET_COLOR}`);\n\n // Add prefix if configured\n if (this.config.prefix) {\n parts.push(`[${this.config.prefix}]`);\n }\n\n // Add context if available and enabled.\n if (this.config.includeContext && entry.context) {\n parts.push(`[${entry.context}]`);\n }\n\n // Add the main message\n parts.push(entry.message);\n\n // Format metadata if available.\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n parts.push(`\\n Metadata: ${JSON.stringify(entry.metadata, null, 2)}`);\n }\n\n const formattedMessage = parts.join(' ');\n\n // Output to appropriate console method based on level\n switch (entry.level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(formattedMessage);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(formattedMessage);\n break;\n case 'warn':\n console.warn(formattedMessage);\n break;\n case 'error':\n console.error(formattedMessage);\n break;\n }\n }\n}\n\n/**\n * Main Logger class providing structured logging capabilities.\n */\nexport class Logger {\n private config: LoggerConfig;\n private handlers: LogHandler[];\n\n constructor(config: Partial<LoggerConfig> = {}) {\n this.config = {\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n enableConsole: true,\n handlers: [],\n ...config,\n };\n\n this.handlers = [...(this.config.handlers || [])];\n\n // Add console handler if enabled\n if (this.config.enableConsole) {\n this.handlers.push(new ConsoleLogHandler(this.config));\n }\n }\n\n /**\n * Add a custom log handler\n */\n addHandler(handler: LogHandler): void {\n this.handlers.push(handler);\n }\n\n /**\n * Remove a log handler\n */\n removeHandler(handler: LogHandler): void {\n const index = this.handlers.indexOf(handler);\n if (index > -1) {\n this.handlers.splice(index, 1);\n }\n }\n\n /**\n * Update logger configuration\n */\n configure(config: Partial<LoggerConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Check if a log level should be output based on current configuration\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n /**\n * Internal logging method that creates log entries and passes them to handlers\n */\n private log(\n level: LogLevel,\n message: string,\n context?: string,\n metadata?: LogMetadata\n ): void {\n if (!this.shouldLog(level)) {\n return;\n }\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context,\n metadata,\n };\n\n // Pass to all handlers\n this.handlers.forEach((handler) => {\n try {\n handler.handle(entry);\n } catch (error) {\n // Prevent logging errors from breaking the application\n console.error('Error in log handler:', error);\n }\n });\n }\n\n /**\n * Log a debug message\n * Used for detailed diagnostic information, typically of interest only when diagnosing problems\n */\n debug(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('debug', message, context, metadata);\n }\n\n /**\n * Log an info message\n * Used for general information about application operation.\n */\n info(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('info', message, context, metadata);\n }\n\n /**\n * Log a warning message\n * Used for potentially problematic situations that don't prevent operation\n */\n warn(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('warn', message, context, metadata);\n }\n\n /**\n * Log an error message\n * Used for error events that might still allow the application to continue.\n */\n error(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('error', message, context, metadata);\n }\n\n /**\n * Create a child logger with a specific context\n */\n child(context: string): ContextLogger {\n return new ContextLogger(this, context);\n }\n\n /**\n * Get current logger configuration\n */\n getConfig(): LoggerConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Context logger that automatically includes context information.\n */\nexport class ContextLogger {\n private logger: Logger;\n private context: string;\n\n constructor(logger: Logger, context: string) {\n this.logger = logger;\n this.context = context;\n }\n\n debug(message: string, metadata?: LogMetadata): void {\n this.logger.debug(message, this.context, metadata);\n }\n\n info(message: string, metadata?: LogMetadata): void {\n this.logger.info(message, this.context, metadata);\n }\n\n warn(message: string, metadata?: LogMetadata): void {\n this.logger.warn(message, this.context, metadata);\n }\n\n error(message: string, metadata?: LogMetadata): void {\n this.logger.error(message, this.context, metadata);\n }\n\n child(childContext: string): ContextLogger {\n return new ContextLogger(this.logger, `${this.context}:${childContext}`);\n }\n}\n\n// Default logger instance. Pure annotations let bundlers drop the logger from\n// consumers that only import constants from the same chunk.\nexport const defaultLogger = /* @__PURE__ */ new Logger({\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n prefix: 'GT',\n});\n\n// Convenience functions using the default logger.\nexport const debug = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.debug(message, context, metadata);\n\nexport const info = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.info(message, context, metadata);\n\nexport const warn = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.warn(message, context, metadata);\n\nexport const error = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.error(message, context, metadata);\n\n// Create context-specific loggers for different parts of the system\nexport const fetchLogger = /* @__PURE__ */ defaultLogger.child('fetch');\nexport const gtInstanceLogger =\n /* @__PURE__ */ defaultLogger.child('GT instance');\n\n// Export types and classes\nexport { Logger as GTLogger };\n","import { ModelProvider } from '@generaltranslation/api';\n\nexport type { ModelProvider };\n\nexport const supportedModelProviders =\n /* @__PURE__ */ Object.values(ModelProvider);\n\nexport function isModelProvider(value: unknown): value is ModelProvider {\n return supportedModelProviders.includes(value as ModelProvider);\n}\n","import { translationTimeoutError } from '../../logging/errors';\nimport { defaultTimeout } from '../../settings/settings';\n\n/**\n * @internal\n *\n * Wraps a fetch implementation with the runtime translation timeout.\n *\n * @param url - The URL to fetch.\n * @param options - The options to pass to the fetch function.\n * @param timeoutMs - The timeout in milliseconds. Omitted selects `defaultTimeout`,\n * `0` is a literal zero, and `false` disables the runtime-owned timer.\n * @param fetchImplementation - The fetch implementation to call. Defaults to global fetch.\n * @returns The response from the fetch function.\n */\nexport async function fetchWithTimeout(\n url: string | URL | globalThis.Request,\n options: RequestInit,\n timeoutMs: number | false = defaultTimeout,\n fetchImplementation: typeof fetch = globalThis.fetch\n) {\n const controller = new AbortController();\n const signals = [controller.signal];\n if (options.signal) signals.push(options.signal);\n if (url instanceof Request) signals.push(url.signal);\n const signal = AbortSignal.any(signals);\n\n // Only a rejection with the SDK's own abort reason is a timeout. Native and\n // reason-preserving custom fetches keep distinct cancellations, even if the\n // SDK timer fires while they are cleaning up.\n let timedOut = false;\n const timeoutId =\n timeoutMs === false\n ? null\n : setTimeout(() => {\n timedOut = !signal.aborted;\n controller.abort();\n }, timeoutMs);\n\n try {\n const response = await fetchImplementation(url, { ...options, signal });\n return response;\n } catch (error) {\n if (timedOut && timeoutMs !== false && error === controller.signal.reason) {\n throw translationTimeoutError(timeoutMs);\n }\n throw error;\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n }\n}\n","import { ApiError } from '@generaltranslation/api';\n\nexport function isErrorResult(error: unknown): error is { error: string } {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'error' in error &&\n typeof error.error === 'string'\n );\n}\n\n/**\n * Unwraps a `@generaltranslation/api` SDK result, returning its data or\n * throwing an `ApiError` built from the failed response.\n */\nexport function unwrapApiResult<T>(result: {\n data: T | undefined;\n error: unknown;\n response?: Response;\n}): Exclude<T, undefined> {\n if (result.data !== undefined) {\n // TypeScript cannot narrow a generic T after excluding undefined; the\n // runtime guard above establishes the exact Exclude<T, undefined> result.\n return result.data as Exclude<T, undefined>;\n }\n if (result.response) {\n throw ApiError.fromResponse(result.error, result.response);\n }\n throw result.error;\n}\n","import {\n createApiClient,\n translate as translateEndpoint,\n type JsonObject,\n type JsonValue,\n type RuntimeTranslationResponse,\n type TranslateData,\n} from '@generaltranslation/api';\nimport {\n resolveCanonicalLocale,\n standardizeLocale,\n} from '@generaltranslation/format';\nimport type {\n Content,\n GTProp,\n JsxChildren,\n JsxElement,\n} from '@generaltranslation/format/types';\nimport type {\n TranslateConfig,\n TranslateManyResult,\n TranslationError,\n TranslationRequestConfig,\n TranslationResult,\n} from '../types';\nimport type {\n EntryMetadata,\n TranslateManyEntry,\n TranslateOptions,\n} from '../types-dir/api/entry';\nimport { libraryDefaultLocale } from '../settings/settings';\nimport { defaultRuntimeApiUrl } from '../settings/settingsUrls';\nimport {\n noApiKeyProvidedError,\n noProjectIdProvidedError,\n noTargetLocaleProvidedError,\n} from '../logging/errors';\nimport { gtInstanceLogger } from '../logging/logger';\nimport { createDiagnosticMessage } from '../logging/diagnostics';\nimport { hashSource } from '../id';\nimport {\n isModelProvider,\n supportedModelProviders,\n} from '../adapter/modelProvider';\nimport { fetchWithTimeout } from './utils/fetchWithTimeout';\nimport { unwrapApiResult } from './utils/unwrapApiResult';\n\ntype TranslateFunctionName = 'translate' | 'translateMany';\ntype TranslateDefaults = Partial<\n Pick<TranslateOptions, 'sourceLocale' | 'targetLocale'>\n>;\n\n/**\n * @internal\n * Credential/provider errors are reported before the project error, and both\n * before any locale validation. GT/GTRuntime share this ordering.\n */\nexport function validateAuth<\n T extends Pick<TranslateConfig, 'apiKey' | 'userTokenProvider' | 'projectId'>,\n>(\n functionName: string,\n config: T\n): asserts config is T & { projectId: string } {\n const errors: string[] = [];\n if (!config.apiKey && !config.userTokenProvider) {\n errors.push(noApiKeyProvidedError(functionName));\n }\n if (!config.projectId) {\n errors.push(noProjectIdProvidedError(functionName));\n }\n if (errors.length) {\n throw new Error(errors.join('\\n'));\n }\n}\n\n/**\n * @internal\n *\n * Shared preparation for every translation surface (classes and the tooling\n * facade): normalize the string shorthand, validate auth, require a target\n * locale, default the source locale and canonicalize both for the wire.\n *\n * @param defaults - Instance defaults supplied by GT/GTRuntime. Facade calls pass none.\n */\nfunction prepareTranslation(\n functionName: TranslateFunctionName,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults: TranslateDefaults = {}\n): {\n options: TranslateOptions & { sourceLocale: string };\n config: TranslationRequestConfig;\n} {\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n validateAuth(functionName, config);\n\n const targetLocale = options?.targetLocale || defaults.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError(functionName);\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n const { customMapping, ...requestConfig } = config;\n // Mapping resolves aliases; standardization also canonicalizes configured\n // spellings such as en-us before they cross the service boundary.\n const resolveServiceLocale = (locale: string) =>\n standardizeLocale(resolveCanonicalLocale(locale, customMapping));\n\n return {\n options: {\n ...options,\n targetLocale: resolveServiceLocale(targetLocale),\n sourceLocale: resolveServiceLocale(\n options?.sourceLocale || defaults.sourceLocale || libraryDefaultLocale\n ),\n },\n config: requestConfig,\n };\n}\n\n/**\n * @internal\n * Translates a single entry with explicit configuration and optional locale defaults.\n */\nexport async function translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslationResult | TranslationError> {\n const prepared = prepareTranslation('translate', options, config, defaults);\n const results = await executeTranslationBatch(\n [source],\n prepared.options,\n prepared.config\n );\n return results[0];\n}\n\n/**\n * @internal\n * Translates multiple entries in one request with explicit configuration.\n * Returns an array for array input and a record for record input.\n */\nexport async function translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult>;\nexport async function translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const prepared = prepareTranslation(\n 'translateMany',\n options,\n config,\n defaults\n );\n return await executeTranslationBatch(\n sources,\n prepared.options,\n prepared.config\n );\n}\n\ntype RuntimeTranslationResult = RuntimeTranslationResponse[string];\n\nfunction isJsonObject(value: JsonValue | undefined): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isGtProp(value: JsonValue | undefined): value is JsonObject & GTProp {\n if (!isJsonObject(value)) return false;\n if (value.t !== undefined && value.t !== 'p' && value.t !== 'b') return false;\n if (\n ['pl', 'ti', 'alt', 'arl', 'arb', 'ard'].some(\n (key) => value[key] !== undefined && typeof value[key] !== 'string'\n )\n ) {\n return false;\n }\n return (\n value.b === undefined ||\n (isJsonObject(value.b) && Object.values(value.b).every(isJsxChildren))\n );\n}\n\nfunction isJsxElement(\n value: JsonValue | undefined\n): value is JsonObject & JsxElement {\n if (!isJsonObject(value)) return false;\n return (\n (value.t === undefined || typeof value.t === 'string') &&\n (value.i === undefined || typeof value.i === 'number') &&\n (value.d === undefined || isGtProp(value.d)) &&\n (value.c === undefined || isJsxChildren(value.c))\n );\n}\n\nfunction isJsxChild(\n value: JsonValue | undefined\n): value is JsonValue & (string | JsxElement) {\n return typeof value === 'string' || isJsxElement(value);\n}\n\nfunction isJsxChildren(\n value: JsonValue | undefined\n): value is JsonValue & JsxChildren {\n return (\n value === null ||\n typeof value === 'boolean' ||\n isJsxChild(value) ||\n (Array.isArray(value) && value.every(isJsxChild))\n );\n}\n\n// JsonValue is wider than core's format-specific Content union, so narrow each\n// successful translation by dataFormat at the API boundary.\nfunction toTranslationResult(\n result: RuntimeTranslationResult\n): TranslationResult {\n if (!result.success) return result;\n if (result.dataFormat === 'JSX' && isJsxChildren(result.translation)) {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n if (result.dataFormat !== 'JSX' && typeof result.translation === 'string') {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n return {\n success: false,\n error: 'Invalid translation returned',\n code: 500,\n };\n}\n\n/**\n * @internal\n *\n * Translates multiple entries in a single API request for better performance.\n * This function batches multiple translation requests together and sends them\n * to the GT translation API in one call.\n *\n * @param requests - The entries to translate. Can be an array (entries are hashed and results returned in order) or a record keyed by hash (skips hash calculation, returns a record).\n * @param globalMetadata - The metadata for the translation.\n * @param config - The configuration for the translation, including transport settings such as `fetch`, `apiVersion` and `timeoutMs`.\n * @returns The results of the translation. An array if requests was an array, a record if requests was a record.\n */\nasync function executeTranslationBatch<\n T extends TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n>(\n requests: T,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<\n T extends TranslateManyEntry[]\n ? TranslateManyResult\n : Record<string, TranslationResult>\n>;\nasync function executeTranslationBatch(\n requests: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const isArray = Array.isArray(requests);\n\n // normalize and map from requests to requests record\n const hashOrder: string[] | undefined = isArray ? [] : undefined;\n const requestsObject: Record<\n string,\n { source: Content; metadata?: EntryMetadata }\n > = {};\n\n const entries: [string | undefined, TranslateManyEntry][] = isArray\n ? requests.map((r) => [undefined, r])\n : Object.entries(requests);\n\n for (const [key, request] of entries) {\n const normalized =\n typeof request === 'string' ? { source: request } : request;\n const { source, metadata } = normalized;\n const hash =\n key ??\n metadata?.hash ??\n hashSource({\n source,\n ...(metadata?.context && { context: metadata.context }),\n ...(metadata?.maxChars != null && { maxChars: metadata.maxChars }),\n ...(metadata?.fileFormat && { fileFormat: metadata.fileFormat }),\n dataFormat: metadata?.dataFormat ?? 'STRING',\n });\n hashOrder?.push(hash);\n requestsObject[hash] = {\n source,\n metadata: metadata,\n };\n }\n\n if (\n globalMetadata.modelProvider !== undefined &&\n !isModelProvider(globalMetadata.modelProvider)\n ) {\n throw new Error(\n createDiagnosticMessage({\n source: 'generaltranslation',\n severity: 'Error',\n whatHappened: 'The configured model provider is not supported',\n details: String(globalMetadata.modelProvider),\n fix: `Use one of: ${supportedModelProviders.join(', ')}`,\n })\n );\n }\n\n // Translation deliberately has no generic network/5xx/429 retries and owns\n // its timeout through fetchWithTimeout, so the SDK timer is disabled.\n const client = createApiClient({\n apiKey: config.apiKey,\n apiVersion: config.apiVersion,\n userTokenProvider: config.userTokenProvider,\n baseUrl: config.baseUrl || defaultRuntimeApiUrl,\n fetch: (input, init) =>\n fetchWithTimeout(input, init ?? {}, config.timeoutMs, config.fetch),\n projectId: config.projectId,\n retryPolicy: 'none',\n timeoutMs: false,\n });\n const body = {\n requests: requestsObject,\n targetLocale: globalMetadata.targetLocale,\n sourceLocale: globalMetadata.sourceLocale,\n metadata: {\n ...globalMetadata,\n modelProvider: globalMetadata.modelProvider,\n },\n } satisfies TranslateData['body'];\n const result = await translateEndpoint({ body, client });\n const runtimeResponse = unwrapApiResult(result);\n const response: Record<string, TranslationResult> = Object.fromEntries(\n Object.entries(runtimeResponse).map(([hash, translationResult]) => [\n hash,\n toTranslationResult(translationResult),\n ])\n );\n\n // If input was an array, map the record response back to an array in input order\n if (hashOrder) {\n return hashOrder.map(\n (hash) =>\n response[hash] ?? {\n success: false,\n error: 'No translation returned',\n code: 500,\n }\n );\n }\n\n // If input was a record, return the record response directly\n return response;\n}\n"],"mappings":";;;;;AAAA,MAAa,uBAAuB;AACpC,MAAa,iBAAiB;;;ACD9B,MAAa,kBAAkB;AAC/B,MAAa,iBAAiB;AAC9B,MAAa,uBAAuB;;;ACApC,MAAM,YAAY;AAElB,MAAa,2BAA2B,YACtCA,oBAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,uCAAuC,QAAQ;CAC7D,KAAK;CACN,CAAC;AAWJ,MAAa,+BAA+B,iBAC1CA,oBAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAEJ,MAAa,+BAA+B,iBAC1CA,oBAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAEJ,MAAa,4BAA4B,iBACvCA,oBAAAA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV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AC,CACH;AAGD,KAAI,UACF,QAAO,UAAU,KACd,SACC,SAAS,SAAS;EAChB,SAAS;EACT,OAAO;EACP,MAAM;EACP,CACJ;AAIH,QAAO"}
|
|
@@ -19,13 +19,6 @@ const translationTimeoutError = (timeout) => createDiagnosticMessage({
|
|
|
19
19
|
whatHappened: `Translation request timed out after ${timeout}ms`,
|
|
20
20
|
fix: "Try again, or increase the request timeout if the source content is large"
|
|
21
21
|
});
|
|
22
|
-
const apiError = (status, statusText, error) => createDiagnosticMessage({
|
|
23
|
-
source: GT_SOURCE,
|
|
24
|
-
severity: "Error",
|
|
25
|
-
whatHappened: `The translation API returned ${status} ${statusText}`,
|
|
26
|
-
fix: "Check the request configuration and try again",
|
|
27
|
-
details: error
|
|
28
|
-
});
|
|
29
22
|
const noTargetLocaleProvidedError = (functionName) => createDiagnosticMessage({
|
|
30
23
|
source: GT_SOURCE,
|
|
31
24
|
severity: "Error",
|
|
@@ -306,9 +299,6 @@ async function fetchWithTimeout(url, options, timeoutMs = defaultTimeout, fetchI
|
|
|
306
299
|
function isErrorResult(error) {
|
|
307
300
|
return typeof error === "object" && error !== null && "error" in error && typeof error.error === "string";
|
|
308
301
|
}
|
|
309
|
-
function hasDecodedError(result) {
|
|
310
|
-
return isErrorResult(result.error) || typeof result.error === "string";
|
|
311
|
-
}
|
|
312
302
|
/**
|
|
313
303
|
* Unwraps a `@generaltranslation/api` SDK result, returning its data or
|
|
314
304
|
* throwing an `ApiError` built from the failed response.
|
|
@@ -319,22 +309,6 @@ function unwrapApiResult(result) {
|
|
|
319
309
|
throw result.error;
|
|
320
310
|
}
|
|
321
311
|
//#endregion
|
|
322
|
-
//#region src/translate/utils/validateResponse.ts
|
|
323
|
-
async function validateResponse(response) {
|
|
324
|
-
if (!response.ok) {
|
|
325
|
-
let errorMsg = "Unknown error";
|
|
326
|
-
try {
|
|
327
|
-
const text = await response.text();
|
|
328
|
-
try {
|
|
329
|
-
errorMsg = JSON.parse(text).error;
|
|
330
|
-
} catch {
|
|
331
|
-
errorMsg = text || "Unknown error";
|
|
332
|
-
}
|
|
333
|
-
} catch {}
|
|
334
|
-
throw new ApiError(apiError(response.status, response.statusText, errorMsg), response.status, errorMsg);
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
//#endregion
|
|
338
312
|
//#region src/translate/runtimeTranslate.ts
|
|
339
313
|
/**
|
|
340
314
|
* @internal
|
|
@@ -471,7 +445,7 @@ async function executeTranslationBatch(requests, globalMetadata, config) {
|
|
|
471
445
|
retryPolicy: "none",
|
|
472
446
|
timeoutMs: false
|
|
473
447
|
});
|
|
474
|
-
const
|
|
448
|
+
const runtimeResponse = unwrapApiResult(await translate({
|
|
475
449
|
body: {
|
|
476
450
|
requests: requestsObject,
|
|
477
451
|
targetLocale: globalMetadata.targetLocale,
|
|
@@ -482,12 +456,7 @@ async function executeTranslationBatch(requests, globalMetadata, config) {
|
|
|
482
456
|
}
|
|
483
457
|
},
|
|
484
458
|
client
|
|
485
|
-
});
|
|
486
|
-
if (result.data === void 0 && result.response && !hasDecodedError(result)) {
|
|
487
|
-
await validateResponse(result.response);
|
|
488
|
-
throw result.error;
|
|
489
|
-
}
|
|
490
|
-
const runtimeResponse = unwrapApiResult(result);
|
|
459
|
+
}));
|
|
491
460
|
const response = Object.fromEntries(Object.entries(runtimeResponse).map(([hash, translationResult]) => [hash, toTranslationResult(translationResult)]));
|
|
492
461
|
if (hashOrder) return hashOrder.map((hash) => response[hash] ?? {
|
|
493
462
|
success: false,
|
|
@@ -499,4 +468,4 @@ async function executeTranslationBatch(requests, globalMetadata, config) {
|
|
|
499
468
|
//#endregion
|
|
500
469
|
export { unwrapApiResult as a, gtInstanceLogger as c, noSourceLocaleProvidedError as d, noTargetLocaleProvidedError as f, libraryDefaultLocale as g, defaultRuntimeApiUrl as h, isErrorResult as i, invalidLocaleError as l, defaultCacheUrl as m, translateMany as n, isModelProvider as o, defaultBaseUrl as p, validateAuth as r, supportedModelProviders as s, translate$1 as t, invalidLocalesError as u };
|
|
501
470
|
|
|
502
|
-
//# sourceMappingURL=runtimeTranslate-
|
|
471
|
+
//# sourceMappingURL=runtimeTranslate-CRWJMYly.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimeTranslate-CRWJMYly.mjs","names":["translate","translateEndpoint"],"sources":["../src/settings/settings.ts","../src/settings/settingsUrls.ts","../src/logging/errors.ts","../src/logging/logger.ts","../src/adapter/modelProvider.ts","../src/translate/utils/fetchWithTimeout.ts","../src/translate/utils/unwrapApiResult.ts","../src/translate/runtimeTranslate.ts"],"sourcesContent":["export const libraryDefaultLocale = 'en' as const;\nexport const defaultTimeout = 60000;\n","export const defaultCacheUrl = 'https://cdn.gtx.dev' as const;\nexport const defaultBaseUrl = 'https://api.gtx.dev' as const;\nexport const defaultRuntimeApiUrl = 'https://api.gtx.dev' as const;\n","import { createDiagnosticMessage } from './diagnostics';\n\nconst GT_SOURCE = 'GT';\n\nexport const translationTimeoutError = (timeout: number) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Translation request timed out after ${timeout}ms`,\n fix: 'Try again, or increase the request timeout if the source content is large',\n });\n\nexport const translationRequestFailedError = (error: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: 'Translation request could not be completed',\n fix: 'Check your network connection and translation credentials, then try again',\n details: error,\n });\n\nexport const noTargetLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify targetLocale in the GT constructor`,\n });\n\nexport const noSourceLocaleProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified locale`,\n fix: `Pass a locale to \\`${functionName}\\` or specify sourceLocale in the GT constructor`,\n });\n\nexport const noProjectIdProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified project ID`,\n fix: `Pass a project ID to \\`${functionName}\\` or specify projectId in the GT constructor`,\n });\n\nexport const noApiKeyProvidedError = (functionName: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Cannot call \\`${functionName}\\` without a specified API key`,\n fix: `Pass an API key to \\`${functionName}\\` or specify apiKey in the GT constructor`,\n });\n\nexport const invalidLocaleError = (locale: string) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `Locale \"${locale}\" is not valid`,\n fix: 'Use a valid BCP 47 locale code or add a custom mapping',\n });\n\nexport const invalidLocalesError = (locales: string[]) =>\n createDiagnosticMessage({\n source: GT_SOURCE,\n severity: 'Error',\n whatHappened: `These locales are not valid: ${locales.join(', ')}`,\n fix: 'Use valid BCP 47 locale codes or add custom mappings',\n });\n","/**\n * Comprehensive logging system for the General Translation library.\n * Provides structured logging with multiple levels and configurable output.\n */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';\n\nexport type LogMetadataValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | Date\n | Error\n | LogMetadataValue[]\n | { [key: string]: LogMetadataValue };\n\nexport type LogMetadata = Record<string, LogMetadataValue>;\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: Date;\n context?: string;\n metadata?: LogMetadata;\n}\n\nexport interface LoggerConfig {\n /** Minimum log level to output. */\n level: LogLevel;\n /** Whether to include timestamps in log output. */\n includeTimestamp: boolean;\n /** Whether to include context information. */\n includeContext: boolean;\n /** Custom prefix for all log messages. */\n prefix?: string;\n /** Whether to output to console (default: true) */\n enableConsole: boolean;\n /** Custom log handlers. */\n handlers?: LogHandler[];\n}\n\nexport interface LogHandler {\n handle(entry: LogEntry): void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n off: 4,\n};\n\nconst LOG_COLORS: Record<LogLevel, string> = {\n debug: '\\x1b[36m', // Cyan\n info: '\\x1b[32m', // Green\n warn: '\\x1b[33m', // Yellow\n error: '\\x1b[31m', // Red\n off: '', // No color needed since 'off' level logs are never displayed\n};\n\nconst RESET_COLOR = '\\x1b[0m';\n\n/**\n * Get the configured log level from environment variable or default to 'warn'\n */\nfunction getConfiguredLogLevel(): LogLevel {\n if (typeof process !== 'undefined' && process.env?._GT_LOG_LEVEL) {\n const envLevel = process.env._GT_LOG_LEVEL.toLowerCase();\n if (envLevel in LOG_LEVELS) {\n return envLevel as LogLevel;\n }\n }\n return 'warn';\n}\n\n/**\n * Console log handler that outputs formatted messages to console\n */\nexport class ConsoleLogHandler implements LogHandler {\n private config: LoggerConfig;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n }\n\n handle(entry: LogEntry): void {\n const parts: string[] = [];\n\n // Add timestamp if enabled\n if (this.config.includeTimestamp) {\n parts.push(`[${entry.timestamp.toISOString()}]`);\n }\n\n // Add level with color\n const colorCode = LOG_COLORS[entry.level];\n const levelText = `[${entry.level.toUpperCase()}]`;\n parts.push(`${colorCode}${levelText}${RESET_COLOR}`);\n\n // Add prefix if configured\n if (this.config.prefix) {\n parts.push(`[${this.config.prefix}]`);\n }\n\n // Add context if available and enabled.\n if (this.config.includeContext && entry.context) {\n parts.push(`[${entry.context}]`);\n }\n\n // Add the main message\n parts.push(entry.message);\n\n // Format metadata if available.\n if (entry.metadata && Object.keys(entry.metadata).length > 0) {\n parts.push(`\\n Metadata: ${JSON.stringify(entry.metadata, null, 2)}`);\n }\n\n const formattedMessage = parts.join(' ');\n\n // Output to appropriate console method based on level\n switch (entry.level) {\n case 'debug':\n // eslint-disable-next-line no-console\n console.debug(formattedMessage);\n break;\n case 'info':\n // eslint-disable-next-line no-console\n console.info(formattedMessage);\n break;\n case 'warn':\n console.warn(formattedMessage);\n break;\n case 'error':\n console.error(formattedMessage);\n break;\n }\n }\n}\n\n/**\n * Main Logger class providing structured logging capabilities.\n */\nexport class Logger {\n private config: LoggerConfig;\n private handlers: LogHandler[];\n\n constructor(config: Partial<LoggerConfig> = {}) {\n this.config = {\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n enableConsole: true,\n handlers: [],\n ...config,\n };\n\n this.handlers = [...(this.config.handlers || [])];\n\n // Add console handler if enabled\n if (this.config.enableConsole) {\n this.handlers.push(new ConsoleLogHandler(this.config));\n }\n }\n\n /**\n * Add a custom log handler\n */\n addHandler(handler: LogHandler): void {\n this.handlers.push(handler);\n }\n\n /**\n * Remove a log handler\n */\n removeHandler(handler: LogHandler): void {\n const index = this.handlers.indexOf(handler);\n if (index > -1) {\n this.handlers.splice(index, 1);\n }\n }\n\n /**\n * Update logger configuration\n */\n configure(config: Partial<LoggerConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Check if a log level should be output based on current configuration\n */\n private shouldLog(level: LogLevel): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n /**\n * Internal logging method that creates log entries and passes them to handlers\n */\n private log(\n level: LogLevel,\n message: string,\n context?: string,\n metadata?: LogMetadata\n ): void {\n if (!this.shouldLog(level)) {\n return;\n }\n\n const entry: LogEntry = {\n level,\n message,\n timestamp: new Date(),\n context,\n metadata,\n };\n\n // Pass to all handlers\n this.handlers.forEach((handler) => {\n try {\n handler.handle(entry);\n } catch (error) {\n // Prevent logging errors from breaking the application\n console.error('Error in log handler:', error);\n }\n });\n }\n\n /**\n * Log a debug message\n * Used for detailed diagnostic information, typically of interest only when diagnosing problems\n */\n debug(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('debug', message, context, metadata);\n }\n\n /**\n * Log an info message\n * Used for general information about application operation.\n */\n info(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('info', message, context, metadata);\n }\n\n /**\n * Log a warning message\n * Used for potentially problematic situations that don't prevent operation\n */\n warn(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('warn', message, context, metadata);\n }\n\n /**\n * Log an error message\n * Used for error events that might still allow the application to continue.\n */\n error(message: string, context?: string, metadata?: LogMetadata): void {\n this.log('error', message, context, metadata);\n }\n\n /**\n * Create a child logger with a specific context\n */\n child(context: string): ContextLogger {\n return new ContextLogger(this, context);\n }\n\n /**\n * Get current logger configuration\n */\n getConfig(): LoggerConfig {\n return { ...this.config };\n }\n}\n\n/**\n * Context logger that automatically includes context information.\n */\nexport class ContextLogger {\n private logger: Logger;\n private context: string;\n\n constructor(logger: Logger, context: string) {\n this.logger = logger;\n this.context = context;\n }\n\n debug(message: string, metadata?: LogMetadata): void {\n this.logger.debug(message, this.context, metadata);\n }\n\n info(message: string, metadata?: LogMetadata): void {\n this.logger.info(message, this.context, metadata);\n }\n\n warn(message: string, metadata?: LogMetadata): void {\n this.logger.warn(message, this.context, metadata);\n }\n\n error(message: string, metadata?: LogMetadata): void {\n this.logger.error(message, this.context, metadata);\n }\n\n child(childContext: string): ContextLogger {\n return new ContextLogger(this.logger, `${this.context}:${childContext}`);\n }\n}\n\n// Default logger instance. Pure annotations let bundlers drop the logger from\n// consumers that only import constants from the same chunk.\nexport const defaultLogger = /* @__PURE__ */ new Logger({\n level: getConfiguredLogLevel(),\n includeTimestamp: true,\n includeContext: true,\n prefix: 'GT',\n});\n\n// Convenience functions using the default logger.\nexport const debug = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.debug(message, context, metadata);\n\nexport const info = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.info(message, context, metadata);\n\nexport const warn = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.warn(message, context, metadata);\n\nexport const error = (\n message: string,\n context?: string,\n metadata?: LogMetadata\n) => defaultLogger.error(message, context, metadata);\n\n// Create context-specific loggers for different parts of the system\nexport const fetchLogger = /* @__PURE__ */ defaultLogger.child('fetch');\nexport const gtInstanceLogger =\n /* @__PURE__ */ defaultLogger.child('GT instance');\n\n// Export types and classes\nexport { Logger as GTLogger };\n","import { ModelProvider } from '@generaltranslation/api';\n\nexport type { ModelProvider };\n\nexport const supportedModelProviders =\n /* @__PURE__ */ Object.values(ModelProvider);\n\nexport function isModelProvider(value: unknown): value is ModelProvider {\n return supportedModelProviders.includes(value as ModelProvider);\n}\n","import { translationTimeoutError } from '../../logging/errors';\nimport { defaultTimeout } from '../../settings/settings';\n\n/**\n * @internal\n *\n * Wraps a fetch implementation with the runtime translation timeout.\n *\n * @param url - The URL to fetch.\n * @param options - The options to pass to the fetch function.\n * @param timeoutMs - The timeout in milliseconds. Omitted selects `defaultTimeout`,\n * `0` is a literal zero, and `false` disables the runtime-owned timer.\n * @param fetchImplementation - The fetch implementation to call. Defaults to global fetch.\n * @returns The response from the fetch function.\n */\nexport async function fetchWithTimeout(\n url: string | URL | globalThis.Request,\n options: RequestInit,\n timeoutMs: number | false = defaultTimeout,\n fetchImplementation: typeof fetch = globalThis.fetch\n) {\n const controller = new AbortController();\n const signals = [controller.signal];\n if (options.signal) signals.push(options.signal);\n if (url instanceof Request) signals.push(url.signal);\n const signal = AbortSignal.any(signals);\n\n // Only a rejection with the SDK's own abort reason is a timeout. Native and\n // reason-preserving custom fetches keep distinct cancellations, even if the\n // SDK timer fires while they are cleaning up.\n let timedOut = false;\n const timeoutId =\n timeoutMs === false\n ? null\n : setTimeout(() => {\n timedOut = !signal.aborted;\n controller.abort();\n }, timeoutMs);\n\n try {\n const response = await fetchImplementation(url, { ...options, signal });\n return response;\n } catch (error) {\n if (timedOut && timeoutMs !== false && error === controller.signal.reason) {\n throw translationTimeoutError(timeoutMs);\n }\n throw error;\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n }\n}\n","import { ApiError } from '@generaltranslation/api';\n\nexport function isErrorResult(error: unknown): error is { error: string } {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'error' in error &&\n typeof error.error === 'string'\n );\n}\n\n/**\n * Unwraps a `@generaltranslation/api` SDK result, returning its data or\n * throwing an `ApiError` built from the failed response.\n */\nexport function unwrapApiResult<T>(result: {\n data: T | undefined;\n error: unknown;\n response?: Response;\n}): Exclude<T, undefined> {\n if (result.data !== undefined) {\n // TypeScript cannot narrow a generic T after excluding undefined; the\n // runtime guard above establishes the exact Exclude<T, undefined> result.\n return result.data as Exclude<T, undefined>;\n }\n if (result.response) {\n throw ApiError.fromResponse(result.error, result.response);\n }\n throw result.error;\n}\n","import {\n createApiClient,\n translate as translateEndpoint,\n type JsonObject,\n type JsonValue,\n type RuntimeTranslationResponse,\n type TranslateData,\n} from '@generaltranslation/api';\nimport {\n resolveCanonicalLocale,\n standardizeLocale,\n} from '@generaltranslation/format';\nimport type {\n Content,\n GTProp,\n JsxChildren,\n JsxElement,\n} from '@generaltranslation/format/types';\nimport type {\n TranslateConfig,\n TranslateManyResult,\n TranslationError,\n TranslationRequestConfig,\n TranslationResult,\n} from '../types';\nimport type {\n EntryMetadata,\n TranslateManyEntry,\n TranslateOptions,\n} from '../types-dir/api/entry';\nimport { libraryDefaultLocale } from '../settings/settings';\nimport { defaultRuntimeApiUrl } from '../settings/settingsUrls';\nimport {\n noApiKeyProvidedError,\n noProjectIdProvidedError,\n noTargetLocaleProvidedError,\n} from '../logging/errors';\nimport { gtInstanceLogger } from '../logging/logger';\nimport { createDiagnosticMessage } from '../logging/diagnostics';\nimport { hashSource } from '../id';\nimport {\n isModelProvider,\n supportedModelProviders,\n} from '../adapter/modelProvider';\nimport { fetchWithTimeout } from './utils/fetchWithTimeout';\nimport { unwrapApiResult } from './utils/unwrapApiResult';\n\ntype TranslateFunctionName = 'translate' | 'translateMany';\ntype TranslateDefaults = Partial<\n Pick<TranslateOptions, 'sourceLocale' | 'targetLocale'>\n>;\n\n/**\n * @internal\n * Credential/provider errors are reported before the project error, and both\n * before any locale validation. GT/GTRuntime share this ordering.\n */\nexport function validateAuth<\n T extends Pick<TranslateConfig, 'apiKey' | 'userTokenProvider' | 'projectId'>,\n>(\n functionName: string,\n config: T\n): asserts config is T & { projectId: string } {\n const errors: string[] = [];\n if (!config.apiKey && !config.userTokenProvider) {\n errors.push(noApiKeyProvidedError(functionName));\n }\n if (!config.projectId) {\n errors.push(noProjectIdProvidedError(functionName));\n }\n if (errors.length) {\n throw new Error(errors.join('\\n'));\n }\n}\n\n/**\n * @internal\n *\n * Shared preparation for every translation surface (classes and the tooling\n * facade): normalize the string shorthand, validate auth, require a target\n * locale, default the source locale and canonicalize both for the wire.\n *\n * @param defaults - Instance defaults supplied by GT/GTRuntime. Facade calls pass none.\n */\nfunction prepareTranslation(\n functionName: TranslateFunctionName,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults: TranslateDefaults = {}\n): {\n options: TranslateOptions & { sourceLocale: string };\n config: TranslationRequestConfig;\n} {\n if (typeof options === 'string') {\n options = { targetLocale: options };\n }\n\n validateAuth(functionName, config);\n\n const targetLocale = options?.targetLocale || defaults.targetLocale;\n if (!targetLocale) {\n const error = noTargetLocaleProvidedError(functionName);\n gtInstanceLogger.error(error);\n throw new Error(error);\n }\n\n const { customMapping, ...requestConfig } = config;\n // Mapping resolves aliases; standardization also canonicalizes configured\n // spellings such as en-us before they cross the service boundary.\n const resolveServiceLocale = (locale: string) =>\n standardizeLocale(resolveCanonicalLocale(locale, customMapping));\n\n return {\n options: {\n ...options,\n targetLocale: resolveServiceLocale(targetLocale),\n sourceLocale: resolveServiceLocale(\n options?.sourceLocale || defaults.sourceLocale || libraryDefaultLocale\n ),\n },\n config: requestConfig,\n };\n}\n\n/**\n * @internal\n * Translates a single entry with explicit configuration and optional locale defaults.\n */\nexport async function translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslationResult | TranslationError> {\n const prepared = prepareTranslation('translate', options, config, defaults);\n const results = await executeTranslationBatch(\n [source],\n prepared.options,\n prepared.config\n );\n return results[0];\n}\n\n/**\n * @internal\n * Translates multiple entries in one request with explicit configuration.\n * Returns an array for array input and a record for record input.\n */\nexport async function translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult>;\nexport async function translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>>;\nexport async function translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n config: TranslateConfig,\n defaults?: TranslateDefaults\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const prepared = prepareTranslation(\n 'translateMany',\n options,\n config,\n defaults\n );\n return await executeTranslationBatch(\n sources,\n prepared.options,\n prepared.config\n );\n}\n\ntype RuntimeTranslationResult = RuntimeTranslationResponse[string];\n\nfunction isJsonObject(value: JsonValue | undefined): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isGtProp(value: JsonValue | undefined): value is JsonObject & GTProp {\n if (!isJsonObject(value)) return false;\n if (value.t !== undefined && value.t !== 'p' && value.t !== 'b') return false;\n if (\n ['pl', 'ti', 'alt', 'arl', 'arb', 'ard'].some(\n (key) => value[key] !== undefined && typeof value[key] !== 'string'\n )\n ) {\n return false;\n }\n return (\n value.b === undefined ||\n (isJsonObject(value.b) && Object.values(value.b).every(isJsxChildren))\n );\n}\n\nfunction isJsxElement(\n value: JsonValue | undefined\n): value is JsonObject & JsxElement {\n if (!isJsonObject(value)) return false;\n return (\n (value.t === undefined || typeof value.t === 'string') &&\n (value.i === undefined || typeof value.i === 'number') &&\n (value.d === undefined || isGtProp(value.d)) &&\n (value.c === undefined || isJsxChildren(value.c))\n );\n}\n\nfunction isJsxChild(\n value: JsonValue | undefined\n): value is JsonValue & (string | JsxElement) {\n return typeof value === 'string' || isJsxElement(value);\n}\n\nfunction isJsxChildren(\n value: JsonValue | undefined\n): value is JsonValue & JsxChildren {\n return (\n value === null ||\n typeof value === 'boolean' ||\n isJsxChild(value) ||\n (Array.isArray(value) && value.every(isJsxChild))\n );\n}\n\n// JsonValue is wider than core's format-specific Content union, so narrow each\n// successful translation by dataFormat at the API boundary.\nfunction toTranslationResult(\n result: RuntimeTranslationResult\n): TranslationResult {\n if (!result.success) return result;\n if (result.dataFormat === 'JSX' && isJsxChildren(result.translation)) {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n if (result.dataFormat !== 'JSX' && typeof result.translation === 'string') {\n return {\n success: true,\n translation: result.translation,\n dataFormat: result.dataFormat,\n locale: result.locale,\n };\n }\n return {\n success: false,\n error: 'Invalid translation returned',\n code: 500,\n };\n}\n\n/**\n * @internal\n *\n * Translates multiple entries in a single API request for better performance.\n * This function batches multiple translation requests together and sends them\n * to the GT translation API in one call.\n *\n * @param requests - The entries to translate. Can be an array (entries are hashed and results returned in order) or a record keyed by hash (skips hash calculation, returns a record).\n * @param globalMetadata - The metadata for the translation.\n * @param config - The configuration for the translation, including transport settings such as `fetch`, `apiVersion` and `timeoutMs`.\n * @returns The results of the translation. An array if requests was an array, a record if requests was a record.\n */\nasync function executeTranslationBatch<\n T extends TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n>(\n requests: T,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<\n T extends TranslateManyEntry[]\n ? TranslateManyResult\n : Record<string, TranslationResult>\n>;\nasync function executeTranslationBatch(\n requests: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n globalMetadata: {\n targetLocale: string;\n sourceLocale: string;\n } & TranslateOptions,\n config: TranslationRequestConfig\n): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n const isArray = Array.isArray(requests);\n\n // normalize and map from requests to requests record\n const hashOrder: string[] | undefined = isArray ? [] : undefined;\n const requestsObject: Record<\n string,\n { source: Content; metadata?: EntryMetadata }\n > = {};\n\n const entries: [string | undefined, TranslateManyEntry][] = isArray\n ? requests.map((r) => [undefined, r])\n : Object.entries(requests);\n\n for (const [key, request] of entries) {\n const normalized =\n typeof request === 'string' ? { source: request } : request;\n const { source, metadata } = normalized;\n const hash =\n key ??\n metadata?.hash ??\n hashSource({\n source,\n ...(metadata?.context && { context: metadata.context }),\n ...(metadata?.maxChars != null && { maxChars: metadata.maxChars }),\n ...(metadata?.fileFormat && { fileFormat: metadata.fileFormat }),\n dataFormat: metadata?.dataFormat ?? 'STRING',\n });\n hashOrder?.push(hash);\n requestsObject[hash] = {\n source,\n metadata: metadata,\n };\n }\n\n if (\n globalMetadata.modelProvider !== undefined &&\n !isModelProvider(globalMetadata.modelProvider)\n ) {\n throw new Error(\n createDiagnosticMessage({\n source: 'generaltranslation',\n severity: 'Error',\n whatHappened: 'The configured model provider is not supported',\n details: String(globalMetadata.modelProvider),\n fix: `Use one of: ${supportedModelProviders.join(', ')}`,\n })\n );\n }\n\n // Translation deliberately has no generic network/5xx/429 retries and owns\n // its timeout through fetchWithTimeout, so the SDK timer is disabled.\n const client = createApiClient({\n apiKey: config.apiKey,\n apiVersion: config.apiVersion,\n userTokenProvider: config.userTokenProvider,\n baseUrl: config.baseUrl || defaultRuntimeApiUrl,\n fetch: (input, init) =>\n fetchWithTimeout(input, init ?? {}, config.timeoutMs, config.fetch),\n projectId: config.projectId,\n retryPolicy: 'none',\n timeoutMs: false,\n });\n const body = {\n requests: requestsObject,\n targetLocale: globalMetadata.targetLocale,\n sourceLocale: globalMetadata.sourceLocale,\n metadata: {\n ...globalMetadata,\n modelProvider: globalMetadata.modelProvider,\n },\n } satisfies TranslateData['body'];\n const result = await translateEndpoint({ body, client });\n const runtimeResponse = unwrapApiResult(result);\n const response: Record<string, TranslationResult> = Object.fromEntries(\n Object.entries(runtimeResponse).map(([hash, translationResult]) => [\n hash,\n toTranslationResult(translationResult),\n ])\n );\n\n // If input was an array, map the record response back to an array in input order\n if (hashOrder) {\n return hashOrder.map(\n (hash) =>\n response[hash] ?? {\n success: false,\n error: 'No translation returned',\n code: 500,\n }\n );\n }\n\n // If input was a record, return the record response directly\n return response;\n}\n"],"mappings":";;;;;AAAA,MAAa,uBAAuB;AACpC,MAAa,iBAAiB;;;ACD9B,MAAa,kBAAkB;AAC/B,MAAa,iBAAiB;AAC9B,MAAa,uBAAuB;;;ACApC,MAAM,YAAY;AAElB,MAAa,2BAA2B,YACtC,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,uCAAuC,QAAQ;CAC7D,KAAK;CACN,CAAC;AAWJ,MAAa,+BAA+B,iBAC1C,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAEJ,MAAa,+BAA+B,iBAC1C,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,sBAAsB,aAAa;CACzC,CAAC;AAEJ,MAAa,4BAA4B,iBACvC,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,0BAA0B,aAAa;CAC7C,CAAC;AAEJ,MAAa,yBAAyB,iBACpC,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,iBAAiB,aAAa;CAC5C,KAAK,wBAAwB,aAAa;CAC3C,CAAC;AAEJ,MAAa,sBAAsB,WACjC,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,WAAW,OAAO;CAChC,KAAK;CACN,CAAC;AAEJ,MAAa,uBAAuB,YAClC,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,gCAAgC,QAAQ,KAAK,KAAK;CAChE,KAAK;CACN,CAAC;;;ACpBJ,MAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CAC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R,UAAU;EACV,cAAc;EACd,SAAS,OAAO,eAAe,cAAc;EAC7C,KAAK,eAAe,wBAAwB,KAAK,KAAK;EACvD,CAAC,CACH;CAKH,MAAM,SAAS,gBAAgB;EAC7B,QAAQ,OAAO;EACf,YAAY,OAAO;EACnB,mBAAmB,OAAO;EAC1B,SAAS,OAAO,WAAA;EAChB,QAAQ,OAAO,SACb,iBAAiB,OAAO,QAAQ,EAAE,EAAE,OAAO,WAAW,OAAO,MAAM;EACrE,WAAW,OAAO;EAClB,aAAa;EACb,WAAW;EACZ,CAAC;CAWF,MAAM,kBAAkB,gBAAgB,MADnBC,UAAkB;EAAE,MAAA;GARvC,UAAU;GACV,cAAc,eAAe;GAC7B,cAAc,eAAe;GAC7B,UAAU;IACR,GAAG;IACH,eAAe,eAAe;IAC/B;GAE0C;EAAE;EAAQ,CAAC,CACT;CAC/C,MAAM,WAA8C,OAAO,YACzD,OAAO,QAAQ,gBAAgB,CAAC,KAAK,CAAC,MAAM,uBAAuB,CACjE,MACA,oBAAoB,kBAAkB,CACvC,CAAC,CACH;AAGD,KAAI,UACF,QAAO,UAAU,KACd,SACC,SAAS,SAAS;EAChB,SAAS;EACT,OAAO;EACP,MAAM;EACP,CACJ;AAIH,QAAO"}
|
|
@@ -66,8 +66,7 @@ import { createDiagnosticMessage } from '../logging/diagnostics';
|
|
|
66
66
|
import { hashSource } from '../id';
|
|
67
67
|
import { isModelProvider, supportedModelProviders, } from '../adapter/modelProvider';
|
|
68
68
|
import { fetchWithTimeout } from './utils/fetchWithTimeout';
|
|
69
|
-
import {
|
|
70
|
-
import { validateResponse } from './utils/validateResponse';
|
|
69
|
+
import { unwrapApiResult } from './utils/unwrapApiResult';
|
|
71
70
|
/**
|
|
72
71
|
* @internal
|
|
73
72
|
* Credential/provider errors are reported before the project error, and both
|
|
@@ -262,14 +261,6 @@ function executeTranslationBatch(requests, globalMetadata, config) {
|
|
|
262
261
|
return [4 /*yield*/, translateEndpoint({ body: body, client: client })];
|
|
263
262
|
case 1:
|
|
264
263
|
result = _d.sent();
|
|
265
|
-
if (!(result.data === undefined &&
|
|
266
|
-
result.response &&
|
|
267
|
-
!hasDecodedError(result))) return [3 /*break*/, 3];
|
|
268
|
-
return [4 /*yield*/, validateResponse(result.response)];
|
|
269
|
-
case 2:
|
|
270
|
-
_d.sent();
|
|
271
|
-
throw result.error;
|
|
272
|
-
case 3:
|
|
273
264
|
runtimeResponse = unwrapApiResult(result);
|
|
274
265
|
response = Object.fromEntries(Object.entries(runtimeResponse).map(function (_a) {
|
|
275
266
|
var hash = _a[0], translationResult = _a[1];
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
export declare function isErrorResult(error: unknown): error is {
|
|
2
2
|
error: string;
|
|
3
3
|
};
|
|
4
|
-
export declare function hasDecodedError(result: {
|
|
5
|
-
error: unknown;
|
|
6
|
-
}): boolean;
|
|
7
4
|
/**
|
|
8
5
|
* Unwraps a `@generaltranslation/api` SDK result, returning its data or
|
|
9
6
|
* throwing an `ApiError` built from the failed response.
|
|
@@ -5,9 +5,6 @@ export function isErrorResult(error) {
|
|
|
5
5
|
'error' in error &&
|
|
6
6
|
typeof error.error === 'string');
|
|
7
7
|
}
|
|
8
|
-
export function hasDecodedError(result) {
|
|
9
|
-
return isErrorResult(result.error) || typeof result.error === 'string';
|
|
10
|
-
}
|
|
11
8
|
/**
|
|
12
9
|
* Unwraps a `@generaltranslation/api` SDK result, returning its data or
|
|
13
10
|
* throwing an `ApiError` built from the failed response.
|
|
@@ -476,9 +476,9 @@ type SubmitUserEditDiffsPayload = {
|
|
|
476
476
|
* Transformations are made from a prefix and a suffix.
|
|
477
477
|
*/
|
|
478
478
|
type Transformation = BaseTransformation | `${BaseTransformation}-${InjectionType}`;
|
|
479
|
-
type BaseTransformation = 'translate-client' | 'translate-server' | 'translate-runtime' | 'variable-variable' | 'variable-currency' | 'variable-datetime' | 'variable-number' | 'variable-
|
|
479
|
+
type BaseTransformation = 'translate-client' | 'translate-server' | 'translate-runtime' | 'variable-variable' | 'variable-currency' | 'variable-datetime' | 'variable-number' | 'variable-relativetime' | 'plural' | 'branch' | 'derive';
|
|
480
480
|
type TransformationPrefix = 'translate' | 'variable' | 'plural' | 'branch' | 'fragment' | 'derive';
|
|
481
|
-
type VariableTransformationSuffix = 'variable' | 'number' | 'datetime' | 'currency' | '
|
|
481
|
+
type VariableTransformationSuffix = 'variable' | 'number' | 'datetime' | 'currency' | 'relativetime';
|
|
482
482
|
type InjectionType = 'automatic' | 'manual';
|
|
483
483
|
//#endregion
|
|
484
484
|
//#region src/types.d.ts
|
|
@@ -529,4 +529,4 @@ type TranslateConfig = Omit<TranslationRequestConfig, 'projectId'> & {
|
|
|
529
529
|
};
|
|
530
530
|
//#endregion
|
|
531
531
|
export { DownloadFileOptions as $, InjectionType as A, GTParsingFlags as At, JobStatus as B, StringContent as C, FileQueryResult as Ct, TranslationRequestConfig as D, GTConfig as Dt, TranslateConfig as E, JsonValue as Et, SubmitUserEditDiffsPayload as F, TranslateManyEntry as Ft, FileDataQuery as G, MoveResult as H, AwaitJobsOptions$1 as I, TranslateOptions as It, BranchDataResult as J, FileDataResult as K, AwaitJobsResult as L, TransformationPrefix as M, ActionType as Mt, VariableTransformationSuffix as N, EntryMetadata as Nt, Variable as O, GTFilesConfig as Ot, SubmitUserEditDiff as P, RuntimeTranslateManyOptions as Pt, TranslationResultReference as Q, JobResult as R, RuntimeFileFormat$1 as S, FileQuery as St, StringMessage$1 as T, JsonPrimitive as Tt, ProcessMovesOptions as U, MoveMapping as V, ProcessMovesResponse as W, TranslationError as X, TranslateManyResult as Y, TranslationResult as Z, JsxChildren$1 as _, FileToUpload as _t, CustomRegionMapping$1 as a, SetupProjectFileReference as at, Metadata as b, Updates as bt, FormatVariables$1 as c, EnqueueFilesOptions as ct, HTML_CONTENT_PROPS as d, DownloadFileBatchResult as dt, PublishFileEntry as et, HtmlContentPropKeysRecord as f, DownloadedFile as ft, JsxChild as g, FileReferenceIds as gt, IcuMessage$1 as h, FileReference as ht, CustomMapping$1 as i, UploadFilesResponse as it, Transformation as j, HashMetadata as jt, VariableType as k, GTOutputFileConfig as kt, GTProp as l, DownloadFileBatchOptions as lt, I18nextMessage$1 as m, FileFormat as mt, CreateTagOptions as n, FileUpload as nt, CutoffFormatOptions$1 as o, SetupProjectOptions as ot, HtmlContentPropValuesRecord as p, BINARY_FILE_FORMATS as pt, BranchQuery as q, CreateTagResult as r, UploadFilesOptions as rt, DataFormat$1 as s, SetupProjectResult as st, Content as t, PublishFilesResult as tt, GetOrphanedFilesResult as u, DownloadFileBatchRequest as ut, JsxElement as v, isBinaryFileFormat as vt, StringFormat$1 as w, JsonObject as wt, OrphanedFile as x, CheckFileTranslationsOptions as xt, LocaleProperties$1 as y, EnqueueFilesResult as yt, CheckJobStatusResult as z };
|
|
532
|
-
//# sourceMappingURL=types-
|
|
532
|
+
//# sourceMappingURL=types-BxgnFr8M.d.cts.map
|
|
@@ -476,9 +476,9 @@ type SubmitUserEditDiffsPayload = {
|
|
|
476
476
|
* Transformations are made from a prefix and a suffix.
|
|
477
477
|
*/
|
|
478
478
|
type Transformation = BaseTransformation | `${BaseTransformation}-${InjectionType}`;
|
|
479
|
-
type BaseTransformation = 'translate-client' | 'translate-server' | 'translate-runtime' | 'variable-variable' | 'variable-currency' | 'variable-datetime' | 'variable-number' | 'variable-
|
|
479
|
+
type BaseTransformation = 'translate-client' | 'translate-server' | 'translate-runtime' | 'variable-variable' | 'variable-currency' | 'variable-datetime' | 'variable-number' | 'variable-relativetime' | 'plural' | 'branch' | 'derive';
|
|
480
480
|
type TransformationPrefix = 'translate' | 'variable' | 'plural' | 'branch' | 'fragment' | 'derive';
|
|
481
|
-
type VariableTransformationSuffix = 'variable' | 'number' | 'datetime' | 'currency' | '
|
|
481
|
+
type VariableTransformationSuffix = 'variable' | 'number' | 'datetime' | 'currency' | 'relativetime';
|
|
482
482
|
type InjectionType = 'automatic' | 'manual';
|
|
483
483
|
//#endregion
|
|
484
484
|
//#region src/types.d.ts
|
|
@@ -529,4 +529,4 @@ type TranslateConfig = Omit<TranslationRequestConfig, 'projectId'> & {
|
|
|
529
529
|
};
|
|
530
530
|
//#endregion
|
|
531
531
|
export { DownloadFileOptions as $, InjectionType as A, GTParsingFlags as At, JobStatus as B, StringContent as C, FileQueryResult as Ct, TranslationRequestConfig as D, GTConfig as Dt, TranslateConfig as E, JsonValue as Et, SubmitUserEditDiffsPayload as F, TranslateManyEntry as Ft, FileDataQuery as G, MoveResult as H, AwaitJobsOptions$1 as I, TranslateOptions as It, BranchDataResult as J, FileDataResult as K, AwaitJobsResult as L, TransformationPrefix as M, ActionType as Mt, VariableTransformationSuffix as N, EntryMetadata as Nt, Variable as O, GTFilesConfig as Ot, SubmitUserEditDiff as P, RuntimeTranslateManyOptions as Pt, TranslationResultReference as Q, JobResult as R, RuntimeFileFormat$1 as S, FileQuery as St, StringMessage$1 as T, JsonPrimitive as Tt, ProcessMovesOptions as U, MoveMapping as V, ProcessMovesResponse as W, TranslationError as X, TranslateManyResult as Y, TranslationResult as Z, JsxChildren$1 as _, FileToUpload as _t, CustomRegionMapping$1 as a, SetupProjectFileReference as at, Metadata as b, Updates as bt, FormatVariables$1 as c, EnqueueFilesOptions as ct, HTML_CONTENT_PROPS as d, DownloadFileBatchResult as dt, PublishFileEntry as et, HtmlContentPropKeysRecord as f, DownloadedFile as ft, JsxChild as g, FileReferenceIds as gt, IcuMessage$1 as h, FileReference as ht, CustomMapping$1 as i, UploadFilesResponse as it, Transformation as j, HashMetadata as jt, VariableType as k, GTOutputFileConfig as kt, GTProp as l, DownloadFileBatchOptions as lt, I18nextMessage$1 as m, FileFormat as mt, CreateTagOptions as n, FileUpload as nt, CutoffFormatOptions$1 as o, SetupProjectOptions as ot, HtmlContentPropValuesRecord as p, BINARY_FILE_FORMATS as pt, BranchQuery as q, CreateTagResult as r, UploadFilesOptions as rt, DataFormat$1 as s, SetupProjectResult as st, Content as t, PublishFilesResult as tt, GetOrphanedFilesResult as u, DownloadFileBatchRequest as ut, JsxElement as v, isBinaryFileFormat as vt, StringFormat$1 as w, JsonObject as wt, OrphanedFile as x, CheckFileTranslationsOptions as xt, LocaleProperties$1 as y, EnqueueFilesResult as yt, CheckJobStatusResult as z };
|
|
532
|
-
//# sourceMappingURL=types-
|
|
532
|
+
//# sourceMappingURL=types-Ix4SHG5H.d.mts.map
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Transformations are made from a prefix and a suffix.
|
|
3
3
|
*/
|
|
4
4
|
export type Transformation = BaseTransformation | `${BaseTransformation}-${InjectionType}`;
|
|
5
|
-
export type BaseTransformation = 'translate-client' | 'translate-server' | 'translate-runtime' | 'variable-variable' | 'variable-currency' | 'variable-datetime' | 'variable-number' | 'variable-
|
|
5
|
+
export type BaseTransformation = 'translate-client' | 'translate-server' | 'translate-runtime' | 'variable-variable' | 'variable-currency' | 'variable-datetime' | 'variable-number' | 'variable-relativetime' | 'plural' | 'branch' | 'derive';
|
|
6
6
|
export type TransformationPrefix = 'translate' | 'variable' | 'plural' | 'branch' | 'fragment' | 'derive';
|
|
7
|
-
export type VariableTransformationSuffix = 'variable' | 'number' | 'datetime' | 'currency' | '
|
|
7
|
+
export type VariableTransformationSuffix = 'variable' | 'number' | 'datetime' | 'currency' | 'relativetime';
|
|
8
8
|
export type InjectionType = 'automatic' | 'manual';
|
package/dist/types.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as DownloadFileOptions, A as InjectionType, At as GTParsingFlags, B as JobStatus, C as StringContent, D as TranslationRequestConfig, Dt as GTConfig, E as TranslateConfig, Et as JsonValue, F as SubmitUserEditDiffsPayload, Ft as TranslateManyEntry, G as FileDataQuery, H as MoveResult, I as AwaitJobsOptions, It as TranslateOptions, J as BranchDataResult, K as FileDataResult, L as AwaitJobsResult, M as TransformationPrefix, Mt as ActionType, N as VariableTransformationSuffix, Nt as EntryMetadata, O as Variable, Ot as GTFilesConfig, P as SubmitUserEditDiff, Q as TranslationResultReference, R as JobResult, S as RuntimeFileFormat, T as StringMessage, Tt as JsonPrimitive, U as ProcessMovesOptions, V as MoveMapping, W as ProcessMovesResponse, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult, _ as JsxChildren, _t as FileToUpload, a as CustomRegionMapping, at as SetupProjectFileReference, b as Metadata, bt as Updates, c as FormatVariables, ct as EnqueueFilesOptions, d as HTML_CONTENT_PROPS, dt as DownloadFileBatchResult, et as PublishFileEntry, f as HtmlContentPropKeysRecord, ft as DownloadedFile, g as JsxChild, h as IcuMessage, ht as FileReference, i as CustomMapping, j as Transformation, jt as HashMetadata, k as VariableType, kt as GTOutputFileConfig, l as GTProp, lt as DownloadFileBatchOptions, m as I18nextMessage, mt as FileFormat, n as CreateTagOptions, nt as FileUpload, o as CutoffFormatOptions, p as HtmlContentPropValuesRecord, pt as BINARY_FILE_FORMATS, q as BranchQuery, r as CreateTagResult, s as DataFormat, t as Content, tt as PublishFilesResult, u as GetOrphanedFilesResult, v as JsxElement, vt as isBinaryFileFormat, w as StringFormat, wt as JsonObject, x as OrphanedFile, xt as CheckFileTranslationsOptions, y as LocaleProperties, yt as EnqueueFilesResult, z as CheckJobStatusResult } from "./types-
|
|
1
|
+
import { $ as DownloadFileOptions, A as InjectionType, At as GTParsingFlags, B as JobStatus, C as StringContent, D as TranslationRequestConfig, Dt as GTConfig, E as TranslateConfig, Et as JsonValue, F as SubmitUserEditDiffsPayload, Ft as TranslateManyEntry, G as FileDataQuery, H as MoveResult, I as AwaitJobsOptions, It as TranslateOptions, J as BranchDataResult, K as FileDataResult, L as AwaitJobsResult, M as TransformationPrefix, Mt as ActionType, N as VariableTransformationSuffix, Nt as EntryMetadata, O as Variable, Ot as GTFilesConfig, P as SubmitUserEditDiff, Q as TranslationResultReference, R as JobResult, S as RuntimeFileFormat, T as StringMessage, Tt as JsonPrimitive, U as ProcessMovesOptions, V as MoveMapping, W as ProcessMovesResponse, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult, _ as JsxChildren, _t as FileToUpload, a as CustomRegionMapping, at as SetupProjectFileReference, b as Metadata, bt as Updates, c as FormatVariables, ct as EnqueueFilesOptions, d as HTML_CONTENT_PROPS, dt as DownloadFileBatchResult, et as PublishFileEntry, f as HtmlContentPropKeysRecord, ft as DownloadedFile, g as JsxChild, h as IcuMessage, ht as FileReference, i as CustomMapping, j as Transformation, jt as HashMetadata, k as VariableType, kt as GTOutputFileConfig, l as GTProp, lt as DownloadFileBatchOptions, m as I18nextMessage, mt as FileFormat, n as CreateTagOptions, nt as FileUpload, o as CutoffFormatOptions, p as HtmlContentPropValuesRecord, pt as BINARY_FILE_FORMATS, q as BranchQuery, r as CreateTagResult, s as DataFormat, t as Content, tt as PublishFilesResult, u as GetOrphanedFilesResult, v as JsxElement, vt as isBinaryFileFormat, w as StringFormat, wt as JsonObject, x as OrphanedFile, xt as CheckFileTranslationsOptions, y as LocaleProperties, yt as EnqueueFilesResult, z as CheckJobStatusResult } from "./types-BxgnFr8M.cjs";
|
|
2
2
|
export { AwaitJobsOptions, AwaitJobsResult, BINARY_FILE_FORMATS, BranchDataResult, BranchQuery, CheckFileTranslationsOptions, CheckJobStatusResult, Content, CreateTagOptions, CreateTagResult, CustomMapping, CustomRegionMapping, CutoffFormatOptions, DataFormat, DownloadFileBatchOptions, DownloadFileBatchResult, DownloadFileOptions, DownloadedFile, EnqueueFilesOptions, EnqueueFilesResult, ActionType as EntryActionType, EntryMetadata, FileDataQuery, FileDataResult, FileFormat, FileReference, FileToUpload, FileUpload, FormatVariables, GTConfig, GTFilesConfig, GTOutputFileConfig, GTParsingFlags, GTProp, GetOrphanedFilesResult, HTML_CONTENT_PROPS, HashMetadata, HtmlContentPropKeysRecord, HtmlContentPropValuesRecord, I18nextMessage, IcuMessage, InjectionType, JobResult, JobStatus, JsonObject, JsonPrimitive, JsonValue, JsxChild, JsxChildren, JsxElement, LocaleProperties, Metadata, MoveMapping, MoveResult, OrphanedFile, ProcessMovesOptions, ProcessMovesResponse, PublishFileEntry, PublishFilesResult, RuntimeFileFormat, SetupProjectFileReference, StringContent, StringFormat, StringMessage, SubmitUserEditDiff, SubmitUserEditDiffsPayload, Transformation, TransformationPrefix, TranslateConfig, TranslateManyEntry, TranslateManyResult, TranslateOptions, TranslationError, TranslationRequestConfig, TranslationResult, TranslationResultReference, Updates, Variable, VariableTransformationSuffix, VariableType, isBinaryFileFormat };
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as DownloadFileOptions, A as InjectionType, At as GTParsingFlags, B as JobStatus, C as StringContent, D as TranslationRequestConfig, Dt as GTConfig, E as TranslateConfig, Et as JsonValue, F as SubmitUserEditDiffsPayload, Ft as TranslateManyEntry, G as FileDataQuery, H as MoveResult, I as AwaitJobsOptions, It as TranslateOptions, J as BranchDataResult, K as FileDataResult, L as AwaitJobsResult, M as TransformationPrefix, Mt as ActionType, N as VariableTransformationSuffix, Nt as EntryMetadata, O as Variable, Ot as GTFilesConfig, P as SubmitUserEditDiff, Q as TranslationResultReference, R as JobResult, S as RuntimeFileFormat, T as StringMessage, Tt as JsonPrimitive, U as ProcessMovesOptions, V as MoveMapping, W as ProcessMovesResponse, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult, _ as JsxChildren, _t as FileToUpload, a as CustomRegionMapping, at as SetupProjectFileReference, b as Metadata, bt as Updates, c as FormatVariables, ct as EnqueueFilesOptions, d as HTML_CONTENT_PROPS, dt as DownloadFileBatchResult, et as PublishFileEntry, f as HtmlContentPropKeysRecord, ft as DownloadedFile, g as JsxChild, h as IcuMessage, ht as FileReference, i as CustomMapping, j as Transformation, jt as HashMetadata, k as VariableType, kt as GTOutputFileConfig, l as GTProp, lt as DownloadFileBatchOptions, m as I18nextMessage, mt as FileFormat, n as CreateTagOptions, nt as FileUpload, o as CutoffFormatOptions, p as HtmlContentPropValuesRecord, pt as BINARY_FILE_FORMATS, q as BranchQuery, r as CreateTagResult, s as DataFormat, t as Content, tt as PublishFilesResult, u as GetOrphanedFilesResult, v as JsxElement, vt as isBinaryFileFormat, w as StringFormat, wt as JsonObject, x as OrphanedFile, xt as CheckFileTranslationsOptions, y as LocaleProperties, yt as EnqueueFilesResult, z as CheckJobStatusResult } from "./types-
|
|
1
|
+
import { $ as DownloadFileOptions, A as InjectionType, At as GTParsingFlags, B as JobStatus, C as StringContent, D as TranslationRequestConfig, Dt as GTConfig, E as TranslateConfig, Et as JsonValue, F as SubmitUserEditDiffsPayload, Ft as TranslateManyEntry, G as FileDataQuery, H as MoveResult, I as AwaitJobsOptions, It as TranslateOptions, J as BranchDataResult, K as FileDataResult, L as AwaitJobsResult, M as TransformationPrefix, Mt as ActionType, N as VariableTransformationSuffix, Nt as EntryMetadata, O as Variable, Ot as GTFilesConfig, P as SubmitUserEditDiff, Q as TranslationResultReference, R as JobResult, S as RuntimeFileFormat, T as StringMessage, Tt as JsonPrimitive, U as ProcessMovesOptions, V as MoveMapping, W as ProcessMovesResponse, X as TranslationError, Y as TranslateManyResult, Z as TranslationResult, _ as JsxChildren, _t as FileToUpload, a as CustomRegionMapping, at as SetupProjectFileReference, b as Metadata, bt as Updates, c as FormatVariables, ct as EnqueueFilesOptions, d as HTML_CONTENT_PROPS, dt as DownloadFileBatchResult, et as PublishFileEntry, f as HtmlContentPropKeysRecord, ft as DownloadedFile, g as JsxChild, h as IcuMessage, ht as FileReference, i as CustomMapping, j as Transformation, jt as HashMetadata, k as VariableType, kt as GTOutputFileConfig, l as GTProp, lt as DownloadFileBatchOptions, m as I18nextMessage, mt as FileFormat, n as CreateTagOptions, nt as FileUpload, o as CutoffFormatOptions, p as HtmlContentPropValuesRecord, pt as BINARY_FILE_FORMATS, q as BranchQuery, r as CreateTagResult, s as DataFormat, t as Content, tt as PublishFilesResult, u as GetOrphanedFilesResult, v as JsxElement, vt as isBinaryFileFormat, w as StringFormat, wt as JsonObject, x as OrphanedFile, xt as CheckFileTranslationsOptions, y as LocaleProperties, yt as EnqueueFilesResult, z as CheckJobStatusResult } from "./types-Ix4SHG5H.mjs";
|
|
2
2
|
export { AwaitJobsOptions, AwaitJobsResult, BINARY_FILE_FORMATS, BranchDataResult, BranchQuery, CheckFileTranslationsOptions, CheckJobStatusResult, Content, CreateTagOptions, CreateTagResult, CustomMapping, CustomRegionMapping, CutoffFormatOptions, DataFormat, DownloadFileBatchOptions, DownloadFileBatchResult, DownloadFileOptions, DownloadedFile, EnqueueFilesOptions, EnqueueFilesResult, ActionType as EntryActionType, EntryMetadata, FileDataQuery, FileDataResult, FileFormat, FileReference, FileToUpload, FileUpload, FormatVariables, GTConfig, GTFilesConfig, GTOutputFileConfig, GTParsingFlags, GTProp, GetOrphanedFilesResult, HTML_CONTENT_PROPS, HashMetadata, HtmlContentPropKeysRecord, HtmlContentPropValuesRecord, I18nextMessage, IcuMessage, InjectionType, JobResult, JobStatus, JsonObject, JsonPrimitive, JsonValue, JsxChild, JsxChildren, JsxElement, LocaleProperties, Metadata, MoveMapping, MoveResult, OrphanedFile, ProcessMovesOptions, ProcessMovesResponse, PublishFileEntry, PublishFilesResult, RuntimeFileFormat, SetupProjectFileReference, StringContent, StringFormat, StringMessage, SubmitUserEditDiff, SubmitUserEditDiffsPayload, Transformation, TransformationPrefix, TranslateConfig, TranslateManyEntry, TranslateManyResult, TranslateOptions, TranslationError, TranslationRequestConfig, TranslationResult, TranslationResultReference, Updates, Variable, VariableTransformationSuffix, VariableType, isBinaryFileFormat };
|
package/dist/utils/minify.js
CHANGED
|
@@ -3,7 +3,7 @@ var VARIABLE_TRANSFORMATION_SUFFIXES_TO_MINIFIED_NAMES = {
|
|
|
3
3
|
number: 'n',
|
|
4
4
|
datetime: 'd',
|
|
5
5
|
currency: 'c',
|
|
6
|
-
|
|
6
|
+
relativetime: 'rt',
|
|
7
7
|
};
|
|
8
8
|
export function minifyVariableType(variableType) {
|
|
9
9
|
return VARIABLE_TRANSFORMATION_SUFFIXES_TO_MINIFIED_NAMES[variableType];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "generaltranslation",
|
|
3
|
-
"version": "9.5.
|
|
3
|
+
"version": "9.5.7",
|
|
4
4
|
"description": "A language toolkit for AI developers",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"@noble/hashes": "^2.2.0",
|
|
43
|
-
"@generaltranslation/api": "0.5.
|
|
43
|
+
"@generaltranslation/api": "0.5.4",
|
|
44
44
|
"@generaltranslation/icu": "0.1.2",
|
|
45
45
|
"@generaltranslation/format": "0.1.9"
|
|
46
46
|
},
|