@focus-reactive/payload-plugin-translator 0.10.4 → 0.11.1

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.
Files changed (64) hide show
  1. package/README.md +199 -11
  2. package/dist/client/widgets/bulk-translation-dashboard/ui/BulkTranslationDashboard.server.js +2 -2
  3. package/dist/client/widgets/translate-document/ui/TranslateDocument.server.js +2 -2
  4. package/dist/client/widgets/translate-field-control/ui/TranslateFieldControl.js +10 -7
  5. package/dist/core/translation-pipeline/stages/field-collector/FieldChunkCollector.js +0 -5
  6. package/dist/index.d.ts +8 -3
  7. package/dist/index.js +4 -3
  8. package/dist/server/features/translate-document/handler.d.ts +1 -0
  9. package/dist/server/features/translate-document/handler.js +55 -46
  10. package/dist/server/features/translate-document/targetLayer.d.ts +37 -0
  11. package/dist/server/features/translate-document/targetLayer.js +26 -0
  12. package/dist/server/features/translate-field/handler.js +4 -10
  13. package/dist/server/modules/auto-translate/AutoTranslateEnqueue.hook.js +2 -1
  14. package/dist/server/shared/guards/index.d.ts +0 -1
  15. package/dist/server/shared/guards/index.js +0 -1
  16. package/dist/server/shared/payload/sourceDocument.d.ts +2 -4
  17. package/dist/server/shared/payload/sourceDocument.js +10 -5
  18. package/dist/translation-providers/index.d.ts +1 -0
  19. package/dist/translation-providers/index.js +1 -7
  20. package/dist/translation-providers/openai/OpenAI.shapes.d.ts +52 -0
  21. package/dist/translation-providers/openai/OpenAI.shapes.js +13 -0
  22. package/dist/translation-providers/openai/OpenAITranslation.provider.d.ts +51 -112
  23. package/dist/translation-providers/openai/OpenAITranslation.provider.js +49 -137
  24. package/dist/translation-providers/openai/OpenAITranslationLegacy.provider.d.ts +11 -0
  25. package/dist/translation-providers/openai/OpenAITranslationLegacy.provider.js +15 -0
  26. package/dist/translation-providers/openai/index.d.ts +6 -1
  27. package/dist/translation-providers/openai/index.js +3 -3
  28. package/dist/translation-providers/openai/loadOpenAIClient.d.ts +24 -0
  29. package/dist/translation-providers/openai/loadOpenAIClient.js +79 -0
  30. package/dist/translation-providers/openai/openAIComplete.d.ts +39 -0
  31. package/dist/translation-providers/openai/openAIComplete.js +84 -0
  32. package/dist/translation-providers/shared/CompletionProvider.provider.d.ts +65 -0
  33. package/dist/translation-providers/shared/CompletionProvider.provider.js +93 -0
  34. package/dist/translation-providers/shared/buildResponseSchema.d.ts +13 -0
  35. package/dist/translation-providers/shared/buildResponseSchema.js +22 -0
  36. package/dist/translation-providers/shared/buildSystemPrompt.d.ts +28 -0
  37. package/dist/translation-providers/shared/buildSystemPrompt.js +25 -0
  38. package/dist/translation-providers/shared/errors/KeySetMismatchError.d.ts +15 -0
  39. package/dist/translation-providers/shared/errors/KeySetMismatchError.js +26 -0
  40. package/dist/translation-providers/shared/errors/NoContentError.d.ts +9 -0
  41. package/dist/translation-providers/shared/errors/NoContentError.js +10 -0
  42. package/dist/translation-providers/shared/errors/ProviderConfigurationError.d.ts +10 -0
  43. package/dist/translation-providers/shared/errors/ProviderConfigurationError.js +11 -0
  44. package/dist/translation-providers/shared/errors/TranslationProviderError.d.ts +18 -0
  45. package/dist/translation-providers/shared/errors/TranslationProviderError.js +21 -0
  46. package/dist/translation-providers/shared/errors/TransportError.d.ts +10 -0
  47. package/dist/translation-providers/shared/errors/TransportError.js +11 -0
  48. package/dist/translation-providers/shared/errors/UnparseableReplyError.d.ts +9 -0
  49. package/dist/translation-providers/shared/errors/UnparseableReplyError.js +10 -0
  50. package/dist/translation-providers/shared/errors/errorMessageLower.d.ts +1 -0
  51. package/dist/translation-providers/shared/errors/errorMessageLower.js +8 -0
  52. package/dist/translation-providers/shared/errors/index.d.ts +9 -0
  53. package/dist/translation-providers/shared/errors/index.js +10 -0
  54. package/dist/translation-providers/shared/errors/wrapTransportError.d.ts +7 -0
  55. package/dist/translation-providers/shared/errors/wrapTransportError.js +14 -0
  56. package/dist/translation-providers/shared/index.d.ts +8 -0
  57. package/dist/translation-providers/shared/index.js +5 -0
  58. package/dist/translation-providers/shared/parseAndValidateReply.d.ts +13 -0
  59. package/dist/translation-providers/shared/parseAndValidateReply.js +46 -0
  60. package/dist/translation-providers/shared/runDryRun.d.ts +20 -0
  61. package/dist/translation-providers/shared/runDryRun.js +17 -0
  62. package/package.json +1 -1
  63. package/dist/server/shared/guards/collection-guards.d.ts +0 -6
  64. package/dist/server/shared/guards/collection-guards.js +0 -16
@@ -0,0 +1,79 @@
1
+ import { errorMessageLower, ProviderConfigurationError } from "../shared";
2
+ /**
3
+ * A literal `import("openai")` is type-resolved like a static import and would put the SDK into the
4
+ * emitted .d.ts, forcing every consumer to install it. Through a constant it resolves at runtime only.
5
+ */ const OPENAI_MODULE = "openai";
6
+ const MODULE_NOT_FOUND_CODES = new Set([
7
+ "ERR_MODULE_NOT_FOUND",
8
+ "MODULE_NOT_FOUND"
9
+ ]);
10
+ /**
11
+ * Bundlers and test runners re-throw resolution failures in their own shapes, and several drop the
12
+ * `code` on the way. The wording is the more portable signal, so both are checked.
13
+ */ const MODULE_NOT_FOUND_MESSAGES = {
14
+ nodeCjs: "cannot find module",
15
+ nodeEsm: "cannot find package",
16
+ viteRollup: "failed to resolve",
17
+ viteDev: "failed to load url",
18
+ webpack: "module not found"
19
+ };
20
+ /**
21
+ * Each runtime's message names two things: what was not found and who imported it. The importer half
22
+ * is a path inside node_modules/openai, so it must be cut off before searching for "openai".
23
+ */ const IMPORTER_CLAUSES = {
24
+ nodeEsm: " imported from ",
25
+ nodeCjs: "require stack:",
26
+ vite: " from ",
27
+ webpack: " in "
28
+ };
29
+ /**
30
+ * `@vercel/nft` (Vercel builds, Next `output: "standalone"`) resolves `import()` statically and can
31
+ * follow a module-level constant but not a parameter — silently, so a parameterised specifier gets
32
+ * `openai` pruned from the deployment and the first production translation reports it missing.
33
+ */ async function importOpenAISdk() {
34
+ return await import(OPENAI_MODULE);
35
+ }
36
+ function whatCouldNotBeFound(text) {
37
+ return Object.values(IMPORTER_CLAUSES).reduce((remaining, clause)=>remaining.split(clause)[0], text);
38
+ }
39
+ /**
40
+ * Was `moduleSpecifier` itself missing, or one of its dependencies? Exported for its own test; not
41
+ * public API.
42
+ */ export function isModuleNotFound(cause, moduleSpecifier) {
43
+ const text = errorMessageLower(cause);
44
+ if (text === null) return false;
45
+ if (!whatCouldNotBeFound(text).includes(moduleSpecifier.toLowerCase())) return false;
46
+ const code = cause.code;
47
+ if (typeof code === "string" && MODULE_NOT_FOUND_CODES.has(code)) return true;
48
+ return Object.values(MODULE_NOT_FOUND_MESSAGES).some((phrase)=>text.includes(phrase));
49
+ }
50
+ /**
51
+ * Constructs an OpenAI SDK client, importing the `openai` package on every call — callers memoize.
52
+ * Reached only when a consumer passed `apiKey`; a consumer who injects a `client` never runs this
53
+ * module.
54
+ *
55
+ * @throws ProviderConfigurationError for a missing package, a broken install, or rejected options.
56
+ */ export async function loadOpenAIClient(options, importSdk = importOpenAISdk) {
57
+ let sdk;
58
+ try {
59
+ sdk = await importSdk();
60
+ } catch (cause) {
61
+ if (isModuleNotFound(cause, OPENAI_MODULE)) {
62
+ throw new ProviderConfigurationError("createOpenAIProvider({ apiKey }) needs the optional `openai` package. Install it, or pass a ready-made `client` instead.", {
63
+ cause
64
+ });
65
+ }
66
+ throw new ProviderConfigurationError("The `openai` package is installed but failed to load. See this error's `cause`.", {
67
+ cause
68
+ });
69
+ }
70
+ try {
71
+ return new sdk.default(options);
72
+ } catch (cause) {
73
+ throw new ProviderConfigurationError("The OpenAI client could not be constructed from the given options. See this error's `cause`.", {
74
+ cause
75
+ });
76
+ }
77
+ }
78
+
79
+ //# sourceMappingURL=loadOpenAIClient.js.map
@@ -0,0 +1,39 @@
1
+ import type { CompletionFn } from "../shared";
2
+ import type { OpenAIChatParams, OpenAIClientShape } from "./OpenAI.shapes";
3
+ /**
4
+ * Sampling parameters. Omitted from the request entirely unless set — several models reject them.
5
+ * Unset means the model's own defaults; pass `{ temperature: 0 }` for deterministic output.
6
+ *
7
+ * @since 0.11.0
8
+ */
9
+ export type OpenAISamplingParams = Pick<OpenAIChatParams, "temperature" | "top_p" | "frequency_penalty" | "presence_penalty">;
10
+ /**
11
+ * Which structured-output envelope to send.
12
+ *
13
+ * `json_schema` (the default): the reply must satisfy a schema, so a compliant model cannot drop a
14
+ * field. Older models and some gateways reject it with a 400, and the schema has a per-model
15
+ * property ceiling a large document can exceed.
16
+ *
17
+ * `json_object`: asks only for valid JSON. No ceiling, but a dropped key is then detected by
18
+ * key-set validation after the fact rather than prevented.
19
+ *
20
+ * The README weighs the two and explains how to size a document against the ceiling.
21
+ *
22
+ * @since 0.11.0
23
+ */
24
+ export type OpenAIStructuredOutput = "json_schema" | "json_object";
25
+ /**
26
+ * The vendor boundary: the only place OpenAI's response shape is read.
27
+ *
28
+ * Takes a client you constructed — it never loads the `openai` package — so pair it with
29
+ * `createTranslationProvider` to build a provider on an SDK version of your own choosing:
30
+ * `createTranslationProvider({ complete: openAIComplete({ client, model }) })`.
31
+ *
32
+ * @since 0.11.0
33
+ */
34
+ export declare function openAIComplete(args: {
35
+ client: OpenAIClientShape;
36
+ model: string;
37
+ sampling?: OpenAISamplingParams;
38
+ structuredOutput?: OpenAIStructuredOutput;
39
+ }): CompletionFn;
@@ -0,0 +1,84 @@
1
+ import { errorMessageLower, NoContentError, ProviderConfigurationError } from "../shared";
2
+ const SCHEMA_NAME = "translation";
3
+ /**
4
+ * Did the service reject the request over the schema envelope, and if so, why? The match stays
5
+ * narrow: a proxy that echoes the request body into an error string would otherwise turn every rate
6
+ * limit into a configuration problem.
7
+ */ function classifySchemaRejection(cause) {
8
+ const text = errorMessageLower(cause);
9
+ if (text === null) return null;
10
+ if (!text.includes("response_format") && !text.includes("json_schema")) return null;
11
+ // "…'response_format' of type 'json_schema' is not supported with this model."
12
+ if (text.includes("not supported") || text.includes("unsupported")) {
13
+ return "model-does-not-support";
14
+ }
15
+ // "Invalid schema for response_format 'translation': object has too many properties."
16
+ if (text.includes("invalid schema")) return "schema-rejected";
17
+ return null;
18
+ }
19
+ /**
20
+ * The vendor boundary: the only place OpenAI's response shape is read.
21
+ *
22
+ * Takes a client you constructed — it never loads the `openai` package — so pair it with
23
+ * `createTranslationProvider` to build a provider on an SDK version of your own choosing:
24
+ * `createTranslationProvider({ complete: openAIComplete({ client, model }) })`.
25
+ *
26
+ * @since 0.11.0
27
+ */ export function openAIComplete(args) {
28
+ const { client, model, sampling, structuredOutput = "json_schema" } = args;
29
+ return async ({ systemPrompt, userContent, responseSchema, signal })=>{
30
+ if (structuredOutput === "json_object" && !/json/iu.test(systemPrompt)) {
31
+ throw new ProviderConfigurationError('With structuredOutput: "json_object", OpenAI requires the word "json" somewhere in the prompt. Your systemPrompt override does not contain it.');
32
+ }
33
+ const params = {
34
+ model,
35
+ messages: [
36
+ {
37
+ role: "system",
38
+ content: systemPrompt
39
+ },
40
+ {
41
+ role: "user",
42
+ content: userContent
43
+ }
44
+ ],
45
+ response_format: structuredOutput === "json_schema" ? {
46
+ type: "json_schema",
47
+ json_schema: {
48
+ name: SCHEMA_NAME,
49
+ strict: true,
50
+ schema: responseSchema
51
+ }
52
+ } : {
53
+ type: "json_object"
54
+ },
55
+ ...sampling
56
+ };
57
+ let result;
58
+ try {
59
+ result = await client.chat.completions.create(params, {
60
+ signal
61
+ });
62
+ } catch (cause) {
63
+ const rejection = structuredOutput === "json_schema" ? classifySchemaRejection(cause) : null;
64
+ if (rejection === "model-does-not-support") {
65
+ throw new ProviderConfigurationError(`The model "${model}" does not support the json_schema response format. Pass structuredOutput: "json_object", or choose a model that supports structured outputs.`, {
66
+ cause
67
+ });
68
+ }
69
+ if (rejection === "schema-rejected") {
70
+ throw new ProviderConfigurationError(`OpenAI rejected the generated response schema. This usually means the document has more translatable fields than a strict schema allows. Pass structuredOutput: "json_object", or translate a smaller subtree.`, {
71
+ cause
72
+ });
73
+ }
74
+ throw cause;
75
+ }
76
+ const content = result.choices[0]?.message?.content;
77
+ if (!content) {
78
+ throw new NoContentError("OpenAI returned no content. The reply may have been filtered, or the model produced nothing.");
79
+ }
80
+ return content;
81
+ };
82
+ }
83
+
84
+ //# sourceMappingURL=openAIComplete.js.map
@@ -0,0 +1,65 @@
1
+ import type { TranslationProvider } from "../../core/domain/translation-providers";
2
+ import type { JsonSchemaObject } from "./buildResponseSchema";
3
+ import type { SystemPromptBuilder } from "./buildSystemPrompt";
4
+ import type { DryRunConfig } from "./runDryRun";
5
+ /**
6
+ * Everything a transport needs in order to make one translation request.
7
+ *
8
+ * @since 0.11.0
9
+ */
10
+ export type CompletionRequest = {
11
+ /** Already includes any `systemPrompt` override — send it verbatim, do not rebuild it. */
12
+ systemPrompt: string;
13
+ /** The user message: the input serialized as JSON. */
14
+ userContent: string;
15
+ /** A JSON Schema requiring exactly the input's keys. Feed it to the service's structured-output mechanism. */
16
+ responseSchema: JsonSchemaObject;
17
+ /** Reserved: the port carries no cancellation yet, so this is always `undefined` today. */
18
+ signal?: AbortSignal;
19
+ };
20
+ /**
21
+ * Sends one translation request and returns the service's reply as **raw text**.
22
+ *
23
+ * Returning text rather than a parsed object is deliberate: parsing and key-set validation stay on
24
+ * this side of the boundary, so a provider built on this factory cannot accidentally skip them.
25
+ *
26
+ * @since 0.11.0
27
+ */
28
+ export type CompletionFn = (request: CompletionRequest) => Promise<string>;
29
+ /**
30
+ * Configuration for {@link createTranslationProvider}.
31
+ *
32
+ * @since 0.11.0
33
+ */
34
+ export type TranslationProviderConfig = {
35
+ complete: CompletionFn;
36
+ systemPrompt?: SystemPromptBuilder;
37
+ /**
38
+ * Simulate translations without calling anything. `true` reverses the text; an object supplies a
39
+ * transformer and an optional delay.
40
+ *
41
+ * @deprecated Supply your own fake `complete` instead. Remove in next major.
42
+ * See docs/DEPRECATIONS.md#provider-dry-run
43
+ */
44
+ dryRun?: boolean | DryRunConfig;
45
+ };
46
+ /**
47
+ * Builds a complete {@link TranslationProvider} from a single request function.
48
+ *
49
+ * Use it when you need a service this package does not ship an adapter for, or when you need full
50
+ * control of the request body. For OpenAI, `openAIComplete({ client, model })` is a ready-made
51
+ * `complete` — construct the client yourself.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * const provider = createTranslationProvider({
56
+ * complete: async ({ systemPrompt, userContent, responseSchema }) => {
57
+ * const reply = await myService.chat({ systemPrompt, userContent, schema: responseSchema })
58
+ * return reply.text
59
+ * },
60
+ * })
61
+ * ```
62
+ *
63
+ * @since 0.11.0
64
+ */
65
+ export declare function createTranslationProvider(config: TranslationProviderConfig): TranslationProvider;
@@ -0,0 +1,93 @@
1
+ import { buildResponseSchema } from "./buildResponseSchema";
2
+ import { buildSystemPrompt } from "./buildSystemPrompt";
3
+ import { NoContentError, ProviderConfigurationError, wrapTransportError } from "./errors";
4
+ import { parseAndValidateReply } from "./parseAndValidateReply";
5
+ import { runDryRun } from "./runDryRun";
6
+ const MAX_LOGGED_REPLY_KEYS = 10;
7
+ /** Keys are model output: quoting them stops a newline inside a key from forging log entries. */ function describeReplyKeys(keys) {
8
+ const shown = keys.slice(0, MAX_LOGGED_REPLY_KEYS).map((key)=>JSON.stringify(key));
9
+ const rest = keys.length - shown.length;
10
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
11
+ }
12
+ function warnAboutPartialReply(missingInputKeys, unrequestedReplyKeys) {
13
+ const lead = missingInputKeys.length > 0 ? `The provider's reply did not cover every field. Untranslated indices: ${missingInputKeys.join(", ")}.` : "The provider's reply carried keys that were not requested.";
14
+ const extra = unrequestedReplyKeys.length > 0 ? ` Unexpected keys ignored: ${describeReplyKeys(unrequestedReplyKeys)}.` : "";
15
+ console.warn(`[payload-plugin-translator] ${lead}${extra}`);
16
+ }
17
+ async function asConfigurationFailure(what, run) {
18
+ try {
19
+ return await run();
20
+ } catch (cause) {
21
+ throw new ProviderConfigurationError(`The ${what} threw. See this error's \`cause\`.`, {
22
+ cause
23
+ });
24
+ }
25
+ }
26
+ /** Only the consumer's transform is wrapped — our own loop must not report its bugs as configuration failures. */ function guardTransformer(dryRun) {
27
+ if (typeof dryRun !== "object" || !dryRun.transform) return dryRun;
28
+ const { transform } = dryRun;
29
+ return {
30
+ ...dryRun,
31
+ transform: (text)=>asConfigurationFailure("dry-run transformer", ()=>transform(text))
32
+ };
33
+ }
34
+ /**
35
+ * Builds a complete {@link TranslationProvider} from a single request function.
36
+ *
37
+ * Use it when you need a service this package does not ship an adapter for, or when you need full
38
+ * control of the request body. For OpenAI, `openAIComplete({ client, model })` is a ready-made
39
+ * `complete` — construct the client yourself.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const provider = createTranslationProvider({
44
+ * complete: async ({ systemPrompt, userContent, responseSchema }) => {
45
+ * const reply = await myService.chat({ systemPrompt, userContent, schema: responseSchema })
46
+ * return reply.text
47
+ * },
48
+ * })
49
+ * ```
50
+ *
51
+ * @since 0.11.0
52
+ */ export function createTranslationProvider(config) {
53
+ const { complete, systemPrompt, dryRun } = config;
54
+ if (dryRun) {
55
+ const guarded = guardTransformer(dryRun);
56
+ return {
57
+ translate: (input)=>runDryRun(input, guarded)
58
+ };
59
+ }
60
+ return {
61
+ async translate (input, sourceLng, targetLng) {
62
+ // A strict response schema with no properties is rejected by the service, so an empty
63
+ // document must not reach the transport at all.
64
+ if (Object.keys(input).length === 0) return {};
65
+ const systemPromptText = await asConfigurationFailure("systemPrompt builder", ()=>buildSystemPrompt({
66
+ sourceLng,
67
+ targetLng,
68
+ override: systemPrompt
69
+ }));
70
+ const request = await asConfigurationFailure("serialization of the input", ()=>({
71
+ systemPrompt: systemPromptText,
72
+ userContent: JSON.stringify(input),
73
+ responseSchema: buildResponseSchema(input)
74
+ }));
75
+ let raw;
76
+ try {
77
+ raw = await complete(request);
78
+ } catch (cause) {
79
+ throw wrapTransportError(cause);
80
+ }
81
+ if (!raw) {
82
+ throw new NoContentError("The provider returned an empty reply.");
83
+ }
84
+ const { translations, missingInputKeys, unrequestedReplyKeys } = parseAndValidateReply(input, raw);
85
+ if (missingInputKeys.length > 0 || unrequestedReplyKeys.length > 0) {
86
+ warnAboutPartialReply(missingInputKeys, unrequestedReplyKeys);
87
+ }
88
+ return translations;
89
+ }
90
+ };
91
+ }
92
+
93
+ //# sourceMappingURL=CompletionProvider.provider.js.map
@@ -0,0 +1,13 @@
1
+ import type { TranslationInput } from "../../core/domain/translation-providers";
2
+ /**
3
+ * A JSON Schema document, as a plain object — deliberately untyped beyond that, so it can be dropped
4
+ * into any vendor's response-format envelope.
5
+ *
6
+ * @since 0.11.0
7
+ */
8
+ export type JsonSchemaObject = Record<string, unknown>;
9
+ /**
10
+ * Builds the response schema for a translation request: exactly the input's keys, all required, no
11
+ * extras.
12
+ */
13
+ export declare function buildResponseSchema(input: TranslationInput): JsonSchemaObject;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Builds the response schema for a translation request: exactly the input's keys, all required, no
3
+ * extras.
4
+ */ export function buildResponseSchema(input) {
5
+ const keys = Object.keys(input);
6
+ const properties = {};
7
+ for (const key of keys){
8
+ properties[key] = {
9
+ type: "string"
10
+ };
11
+ }
12
+ // Strict structured-output modes reject a schema unless every property is listed in `required`
13
+ // and extras are forbidden.
14
+ return {
15
+ type: "object",
16
+ properties,
17
+ required: keys,
18
+ additionalProperties: false
19
+ };
20
+ }
21
+
22
+ //# sourceMappingURL=buildResponseSchema.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Context handed to a {@link SystemPromptBuilder}.
3
+ *
4
+ * @since 0.11.0
5
+ */
6
+ export type SystemPromptContext = {
7
+ /** Source language code (e.g. 'en', 'de'). Empty when the provider should auto-detect. */
8
+ sourceLang: string;
9
+ targetLang: string;
10
+ defaultPrompt: string;
11
+ };
12
+ /**
13
+ * Builds a custom system prompt for translation.
14
+ *
15
+ * @since 0.11.0
16
+ */
17
+ export type SystemPromptBuilder = (context: SystemPromptContext) => string;
18
+ /**
19
+ * Produces the system prompt sent with a translation request.
20
+ *
21
+ * The default wording is handed to `systemPrompt` builders as `defaultPrompt`, so consumers extend
22
+ * this exact string — changing it changes every custom prompt built on it.
23
+ */
24
+ export declare function buildSystemPrompt(args: {
25
+ sourceLng: string;
26
+ targetLng: string;
27
+ override?: SystemPromptBuilder;
28
+ }): string;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Context handed to a {@link SystemPromptBuilder}.
3
+ *
4
+ * @since 0.11.0
5
+ */ /**
6
+ * Produces the system prompt sent with a translation request.
7
+ *
8
+ * The default wording is handed to `systemPrompt` builders as `defaultPrompt`, so consumers extend
9
+ * this exact string — changing it changes every custom prompt built on it.
10
+ */ export function buildSystemPrompt(args) {
11
+ const { sourceLng, targetLng, override } = args;
12
+ const defaultPrompt = `Translate the values from the JSON that the user will send you${sourceLng ? ` from ${sourceLng}` : ""} into ${targetLng}. Keep all JSON keys exactly as they are, only translate the values.
13
+ The response should be a valid JSON object with the same structure and keys as the input, but with translated values.
14
+ Maintain any special formatting, placeholders, or variables within the values if they exist.`;
15
+ if (override) {
16
+ return override({
17
+ sourceLang: sourceLng,
18
+ targetLang: targetLng,
19
+ defaultPrompt
20
+ });
21
+ }
22
+ return defaultPrompt;
23
+ }
24
+
25
+ //# sourceMappingURL=buildSystemPrompt.js.map
@@ -0,0 +1,15 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * Nothing in the reply could be applied — either its keys did not overlap the input's, or they did
4
+ * and none of the values was a string. A partial gap is not an error; see `parseAndValidateReply`.
5
+ *
6
+ * @since 0.11.0
7
+ */
8
+ export declare class KeySetMismatchError extends TranslationProviderError {
9
+ readonly code: "key-set-mismatch";
10
+ /** Input keys left without a usable translation. */
11
+ readonly missingInputKeys: number[];
12
+ /** Keys the reply carried but nobody asked for — model output, so untrusted text. */
13
+ readonly unrequestedReplyKeys: string[];
14
+ constructor(message: string, missingInputKeys: number[], unrequestedReplyKeys: string[], options?: ErrorOptions);
15
+ }
@@ -0,0 +1,26 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * Nothing in the reply could be applied — either its keys did not overlap the input's, or they did
4
+ * and none of the values was a string. A partial gap is not an error; see `parseAndValidateReply`.
5
+ *
6
+ * @since 0.11.0
7
+ */ export class KeySetMismatchError extends TranslationProviderError {
8
+ code = "key-set-mismatch";
9
+ /** Input keys left without a usable translation. */ missingInputKeys;
10
+ /** Keys the reply carried but nobody asked for — model output, so untrusted text. */ unrequestedReplyKeys;
11
+ constructor(message, missingInputKeys, unrequestedReplyKeys, options){
12
+ super(message, options);
13
+ this.missingInputKeys = missingInputKeys;
14
+ this.unrequestedReplyKeys = unrequestedReplyKeys;
15
+ // Model-invented strings: enumerable, they would land in `JSON.stringify(error)` and every
16
+ // structured logger.
17
+ Object.defineProperty(this, "missingInputKeys", {
18
+ enumerable: false
19
+ });
20
+ Object.defineProperty(this, "unrequestedReplyKeys", {
21
+ enumerable: false
22
+ });
23
+ }
24
+ }
25
+
26
+ //# sourceMappingURL=KeySetMismatchError.js.map
@@ -0,0 +1,9 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The provider produced no usable text — an empty reply, or a response the vendor filtered.
4
+ *
5
+ * @since 0.11.0
6
+ */
7
+ export declare class NoContentError extends TranslationProviderError {
8
+ readonly code: "no-content";
9
+ }
@@ -0,0 +1,10 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The provider produced no usable text — an empty reply, or a response the vendor filtered.
4
+ *
5
+ * @since 0.11.0
6
+ */ export class NoContentError extends TranslationProviderError {
7
+ code = "no-content";
8
+ }
9
+
10
+ //# sourceMappingURL=NoContentError.js.map
@@ -0,0 +1,10 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The provider is configured in a way that cannot work — most often an optional SDK that is not
4
+ * installed.
5
+ *
6
+ * @since 0.11.0
7
+ */
8
+ export declare class ProviderConfigurationError extends TranslationProviderError {
9
+ readonly code: "config";
10
+ }
@@ -0,0 +1,11 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The provider is configured in a way that cannot work — most often an optional SDK that is not
4
+ * installed.
5
+ *
6
+ * @since 0.11.0
7
+ */ export class ProviderConfigurationError extends TranslationProviderError {
8
+ code = "config";
9
+ }
10
+
11
+ //# sourceMappingURL=ProviderConfigurationError.js.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Failure causes a translation provider can report.
3
+ *
4
+ * @since 0.11.0
5
+ */
6
+ export type TranslationFailureCode = "no-content" | "unparseable-reply" | "key-set-mismatch" | "transport" | "config";
7
+ /**
8
+ * Base class for every failure a built-in translation provider reports.
9
+ *
10
+ * The original failure travels on `cause` and is never interpolated into `message`: a vendor SDK
11
+ * error can carry an API key, and `message` reaches an HTTP response body.
12
+ *
13
+ * @since 0.11.0
14
+ */
15
+ export declare abstract class TranslationProviderError extends Error {
16
+ abstract readonly code: TranslationFailureCode;
17
+ constructor(message: string, options?: ErrorOptions);
18
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Failure causes a translation provider can report.
3
+ *
4
+ * @since 0.11.0
5
+ */ /**
6
+ * Base class for every failure a built-in translation provider reports.
7
+ *
8
+ * The original failure travels on `cause` and is never interpolated into `message`: a vendor SDK
9
+ * error can carry an API key, and `message` reaches an HTTP response body.
10
+ *
11
+ * @since 0.11.0
12
+ */ export class TranslationProviderError extends Error {
13
+ constructor(message, options){
14
+ // Never `this.cause = cause`: an assigned property is enumerable, so JSON.stringify and pino
15
+ // serialize the vendor error whole — headers and API key with it. `super` installs it non-enumerably.
16
+ super(message, options);
17
+ this.name = new.target.name;
18
+ }
19
+ }
20
+
21
+ //# sourceMappingURL=TranslationProviderError.js.map
@@ -0,0 +1,10 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The call to the provider failed — network, auth, rate limit, timeout. The vendor's own error is on
4
+ * `cause`.
5
+ *
6
+ * @since 0.11.0
7
+ */
8
+ export declare class TransportError extends TranslationProviderError {
9
+ readonly code: "transport";
10
+ }
@@ -0,0 +1,11 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The call to the provider failed — network, auth, rate limit, timeout. The vendor's own error is on
4
+ * `cause`.
5
+ *
6
+ * @since 0.11.0
7
+ */ export class TransportError extends TranslationProviderError {
8
+ code = "transport";
9
+ }
10
+
11
+ //# sourceMappingURL=TransportError.js.map
@@ -0,0 +1,9 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The reply was not JSON, or parsed to something that is not an object — arrays included.
4
+ *
5
+ * @since 0.11.0
6
+ */
7
+ export declare class UnparseableReplyError extends TranslationProviderError {
8
+ readonly code: "unparseable-reply";
9
+ }
@@ -0,0 +1,10 @@
1
+ import { TranslationProviderError } from "./TranslationProviderError";
2
+ /**
3
+ * The reply was not JSON, or parsed to something that is not an object — arrays included.
4
+ *
5
+ * @since 0.11.0
6
+ */ export class UnparseableReplyError extends TranslationProviderError {
7
+ code = "unparseable-reply";
8
+ }
9
+
10
+ //# sourceMappingURL=UnparseableReplyError.js.map
@@ -0,0 +1 @@
1
+ export declare function errorMessageLower(cause: unknown): string | null;
@@ -0,0 +1,8 @@
1
+ import { isObject } from "../../../core/kernel/utils/isObject";
2
+ export function errorMessageLower(cause) {
3
+ if (!isObject(cause)) return null;
4
+ const message = cause.message;
5
+ return typeof message === "string" ? message.toLowerCase() : null;
6
+ }
7
+
8
+ //# sourceMappingURL=errorMessageLower.js.map
@@ -0,0 +1,9 @@
1
+ export { TranslationProviderError } from "./TranslationProviderError";
2
+ export type { TranslationFailureCode } from "./TranslationProviderError";
3
+ export { NoContentError } from "./NoContentError";
4
+ export { UnparseableReplyError } from "./UnparseableReplyError";
5
+ export { KeySetMismatchError } from "./KeySetMismatchError";
6
+ export { TransportError } from "./TransportError";
7
+ export { ProviderConfigurationError } from "./ProviderConfigurationError";
8
+ export { wrapTransportError } from "./wrapTransportError";
9
+ export { errorMessageLower } from "./errorMessageLower";