@puzzle-ui/i18n 0.0.0-stage → 0.16.0

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 (152) hide show
  1. package/README.md +94 -2
  2. package/ai/instructions.md +141 -0
  3. package/ai/manifest.json +10 -0
  4. package/dist/LICENSE +21 -0
  5. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  6. package/dist/adapters/next.cjs +11 -0
  7. package/dist/adapters/next.cjs.map +1 -0
  8. package/dist/adapters/next.d.cts +7 -0
  9. package/dist/adapters/next.d.ts +7 -0
  10. package/dist/adapters/next.js +10 -0
  11. package/dist/adapters/next.js.map +1 -0
  12. package/dist/adapters/react-router.cjs +13 -0
  13. package/dist/adapters/react-router.cjs.map +1 -0
  14. package/dist/adapters/react-router.d.cts +10 -0
  15. package/dist/adapters/react-router.d.ts +10 -0
  16. package/dist/adapters/react-router.js +12 -0
  17. package/dist/adapters/react-router.js.map +1 -0
  18. package/dist/adapters/request.cjs +67 -0
  19. package/dist/adapters/request.cjs.map +1 -0
  20. package/dist/adapters/request.d.cts +16 -0
  21. package/dist/adapters/request.d.ts +16 -0
  22. package/dist/adapters/request.js +65 -0
  23. package/dist/adapters/request.js.map +1 -0
  24. package/dist/adapters/tanstack.cjs +13 -0
  25. package/dist/adapters/tanstack.cjs.map +1 -0
  26. package/dist/adapters/tanstack.d.cts +10 -0
  27. package/dist/adapters/tanstack.d.ts +10 -0
  28. package/dist/adapters/tanstack.js +12 -0
  29. package/dist/adapters/tanstack.js.map +1 -0
  30. package/dist/ai/index.cjs +205 -0
  31. package/dist/ai/index.cjs.map +1 -0
  32. package/dist/ai/index.d.cts +75 -0
  33. package/dist/ai/index.d.ts +75 -0
  34. package/dist/ai/index.js +195 -0
  35. package/dist/ai/index.js.map +1 -0
  36. package/dist/ai/review.cjs +319 -0
  37. package/dist/ai/review.cjs.map +1 -0
  38. package/dist/ai/review.d.cts +91 -0
  39. package/dist/ai/review.d.ts +91 -0
  40. package/dist/ai/review.js +315 -0
  41. package/dist/ai/review.js.map +1 -0
  42. package/dist/cli/bin.cjs +10 -0
  43. package/dist/cli/bin.cjs.map +1 -0
  44. package/dist/cli/bin.d.cts +1 -0
  45. package/dist/cli/bin.d.ts +1 -0
  46. package/dist/cli/bin.js +12 -0
  47. package/dist/cli/bin.js.map +1 -0
  48. package/dist/cli/index.cjs +310 -0
  49. package/dist/cli/index.cjs.map +1 -0
  50. package/dist/cli/index.d.cts +7 -0
  51. package/dist/cli/index.d.ts +7 -0
  52. package/dist/cli/index.js +309 -0
  53. package/dist/cli/index.js.map +1 -0
  54. package/dist/compiler/index.cjs +218 -0
  55. package/dist/compiler/index.cjs.map +1 -0
  56. package/dist/compiler/index.d.cts +18 -0
  57. package/dist/compiler/index.d.ts +18 -0
  58. package/dist/compiler/index.js +210 -0
  59. package/dist/compiler/index.js.map +1 -0
  60. package/dist/compiler/typescript.cjs +251 -0
  61. package/dist/compiler/typescript.cjs.map +1 -0
  62. package/dist/compiler/typescript.d.cts +27 -0
  63. package/dist/compiler/typescript.d.ts +27 -0
  64. package/dist/compiler/typescript.js +247 -0
  65. package/dist/compiler/typescript.js.map +1 -0
  66. package/dist/compiler/vite.cjs +94 -0
  67. package/dist/compiler/vite.cjs.map +1 -0
  68. package/dist/compiler/vite.d.cts +13 -0
  69. package/dist/compiler/vite.d.ts +13 -0
  70. package/dist/compiler/vite.js +92 -0
  71. package/dist/compiler/vite.js.map +1 -0
  72. package/dist/content/index.cjs +156 -0
  73. package/dist/content/index.cjs.map +1 -0
  74. package/dist/content/index.d.cts +75 -0
  75. package/dist/content/index.d.ts +75 -0
  76. package/dist/content/index.js +151 -0
  77. package/dist/content/index.js.map +1 -0
  78. package/dist/content/sanity.cjs +74 -0
  79. package/dist/content/sanity.cjs.map +1 -0
  80. package/dist/content/sanity.d.cts +19 -0
  81. package/dist/content/sanity.d.ts +19 -0
  82. package/dist/content/sanity.js +73 -0
  83. package/dist/content/sanity.js.map +1 -0
  84. package/dist/devtools/index.cjs +77 -0
  85. package/dist/devtools/index.cjs.map +1 -0
  86. package/dist/devtools/index.d.cts +29 -0
  87. package/dist/devtools/index.d.ts +29 -0
  88. package/dist/devtools/index.js +75 -0
  89. package/dist/devtools/index.js.map +1 -0
  90. package/dist/format.cjs +17 -0
  91. package/dist/format.cjs.map +1 -0
  92. package/dist/format.d.cts +9 -0
  93. package/dist/format.d.ts +9 -0
  94. package/dist/format.js +13 -0
  95. package/dist/format.js.map +1 -0
  96. package/dist/index.cjs +20 -0
  97. package/dist/index.d.cts +5 -0
  98. package/dist/index.d.ts +5 -0
  99. package/dist/index.js +5 -0
  100. package/dist/locale.cjs +158 -0
  101. package/dist/locale.cjs.map +1 -0
  102. package/dist/locale.d.cts +42 -0
  103. package/dist/locale.d.ts +42 -0
  104. package/dist/locale.js +155 -0
  105. package/dist/locale.js.map +1 -0
  106. package/dist/react/index.cjs +239 -0
  107. package/dist/react/index.cjs.map +1 -0
  108. package/dist/react/index.d.cts +105 -0
  109. package/dist/react/index.d.ts +105 -0
  110. package/dist/react/index.js +238 -0
  111. package/dist/react/index.js.map +1 -0
  112. package/dist/routing/index.cjs +381 -0
  113. package/dist/routing/index.cjs.map +1 -0
  114. package/dist/routing/index.d.cts +44 -0
  115. package/dist/routing/index.d.ts +44 -0
  116. package/dist/routing/index.js +380 -0
  117. package/dist/routing/index.js.map +1 -0
  118. package/dist/runtime.cjs +261 -0
  119. package/dist/runtime.cjs.map +1 -0
  120. package/dist/runtime.d.cts +74 -0
  121. package/dist/runtime.d.ts +74 -0
  122. package/dist/runtime.js +257 -0
  123. package/dist/runtime.js.map +1 -0
  124. package/dist/seo/index.cjs +212 -0
  125. package/dist/seo/index.cjs.map +1 -0
  126. package/dist/seo/index.d.cts +52 -0
  127. package/dist/seo/index.d.ts +52 -0
  128. package/dist/seo/index.js +209 -0
  129. package/dist/seo/index.js.map +1 -0
  130. package/dist/seo/origin.cjs +27 -0
  131. package/dist/seo/origin.cjs.map +1 -0
  132. package/dist/seo/origin.js +26 -0
  133. package/dist/seo/origin.js.map +1 -0
  134. package/dist/seo/sitemap.cjs +74 -0
  135. package/dist/seo/sitemap.cjs.map +1 -0
  136. package/dist/seo/sitemap.d.cts +16 -0
  137. package/dist/seo/sitemap.d.ts +16 -0
  138. package/dist/seo/sitemap.js +72 -0
  139. package/dist/seo/sitemap.js.map +1 -0
  140. package/dist/sources/index.cjs +227 -0
  141. package/dist/sources/index.cjs.map +1 -0
  142. package/dist/sources/index.d.cts +41 -0
  143. package/dist/sources/index.d.ts +41 -0
  144. package/dist/sources/index.js +222 -0
  145. package/dist/sources/index.js.map +1 -0
  146. package/dist/sources/node.cjs +50 -0
  147. package/dist/sources/node.cjs.map +1 -0
  148. package/dist/sources/node.d.cts +5 -0
  149. package/dist/sources/node.d.ts +5 -0
  150. package/dist/sources/node.js +49 -0
  151. package/dist/sources/node.js.map +1 -0
  152. package/package.json +256 -4
@@ -0,0 +1,10 @@
1
+ import { RequestLocaleOptions } from "./request.js";
2
+ import { LocaleResolution } from "../locale.js";
3
+ export interface TanStackLocaleLoaderArgs {
4
+ request: Request;
5
+ params?: Readonly<Record<string, string | undefined>>;
6
+ }
7
+ export interface TanStackLocaleLoaderOptions extends RequestLocaleOptions {
8
+ localeParam?: string;
9
+ }
10
+ export declare const createTanStackLocaleLoader: (options: TanStackLocaleLoaderOptions) => ((args: TanStackLocaleLoaderArgs) => LocaleResolution);
@@ -0,0 +1,12 @@
1
+ import { resolveRequestLocale } from "./request.js";
2
+ // src/adapters/tanstack.ts
3
+ const createTanStackLocaleLoader = (options) => {
4
+ const localeParam = options.localeParam ?? "locale";
5
+ return ({ request, params }) => resolveRequestLocale(request, {
6
+ ...options,
7
+ urlLocale: params?.[localeParam] ?? options.urlLocale
8
+ });
9
+ };
10
+ export { createTanStackLocaleLoader };
11
+
12
+ //# sourceMappingURL=tanstack.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tanstack.js","names":[],"sources":["../../src/adapters/tanstack.ts"],"sourcesContent":["import { resolveRequestLocale } from \"./request\";\n\nimport type { RequestLocaleOptions } from \"./request\";\nimport type { LocaleResolution } from \"../locale\";\n\nexport interface TanStackLocaleLoaderArgs {\n request: Request;\n params?: Readonly<Record<string, string | undefined>>;\n}\n\nexport interface TanStackLocaleLoaderOptions extends RequestLocaleOptions {\n localeParam?: string;\n}\n\nexport const createTanStackLocaleLoader = (\n options: TanStackLocaleLoaderOptions,\n): ((args: TanStackLocaleLoaderArgs) => LocaleResolution) => {\n const localeParam = options.localeParam ?? \"locale\";\n\n return ({ request, params }) =>\n resolveRequestLocale(request, {\n ...options,\n urlLocale: params?.[localeParam] ?? options.urlLocale,\n });\n};\n"],"mappings":";;AAcA,MAAa,8BACX,YAC2D;CAC3D,MAAM,cAAc,QAAQ,eAAe;CAE3C,QAAQ,EAAE,SAAS,aACjB,qBAAqB,SAAS;EAC5B,GAAG;EACH,WAAW,SAAS,gBAAgB,QAAQ;CAC9C,CAAC;AACL"}
@@ -0,0 +1,205 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
3
+ const require_ai_review = require("./review.cjs");
4
+ let intl_messageformat = require("intl-messageformat");
5
+ intl_messageformat = require_runtime.__toESM(intl_messageformat, 1);
6
+ // src/ai/index.ts
7
+ var TranslationSuggestionError = class extends Error {
8
+ code;
9
+ constructor(code, message, options) {
10
+ super(message, options);
11
+ this.code = code;
12
+ this.name = "TranslationSuggestionError";
13
+ }
14
+ };
15
+ const canonicalize = (locale) => {
16
+ try {
17
+ const [canonical] = Intl.getCanonicalLocales(locale);
18
+ if (!canonical) throw new Error();
19
+ return canonical;
20
+ } catch {
21
+ throw new TranslationSuggestionError("invalid-source", `Invalid BCP 47 locale "${locale}".`);
22
+ }
23
+ };
24
+ const getPlaceholders = (message) => [...message.matchAll(/\{\s*([A-Za-z_][\w.-]*)/g)].map((match) => match[1]).filter((name) => name !== void 0).sort();
25
+ const isAbortError = (error) => error instanceof Error && error.name === "AbortError";
26
+ const assertServerOnly = () => {
27
+ if (typeof window !== "undefined") throw new TranslationSuggestionError("server-only", "Translation providers must only be called from a server environment.");
28
+ };
29
+ const createQualityReport = async (request, suggestion, options) => {
30
+ const checks = [];
31
+ const addCheck = (id, weight, evaluate) => {
32
+ const normalizedWeight = weight ?? 1;
33
+ if (!Number.isFinite(normalizedWeight) || normalizedWeight <= 0) throw new TranslationSuggestionError("invalid-quality-config", "Translation quality check weights must be positive finite numbers.");
34
+ if (!id.trim() || checks.some((check) => check.id === id)) throw new TranslationSuggestionError("invalid-quality-config", "Translation quality check IDs must be unique and non-empty.");
35
+ checks.push({
36
+ id,
37
+ weight: normalizedWeight,
38
+ evaluate
39
+ });
40
+ };
41
+ for (const [index, rule] of (options.terminology ?? []).entries()) {
42
+ if (!rule.source.trim() || !rule.target.trim()) throw new TranslationSuggestionError("invalid-quality-config", "Translation terminology rules require source and target terms.");
43
+ const sourceTerm = rule.source.toLocaleLowerCase(request.sourceLocale);
44
+ const targetTerm = rule.target.toLocaleLowerCase(request.targetLocale);
45
+ if (request.sourceMessage.toLocaleLowerCase(request.sourceLocale).includes(sourceTerm)) addCheck(`terminology-${index + 1}`, rule.weight, () => suggestion.toLocaleLowerCase(request.targetLocale).includes(targetTerm) ? 100 : {
46
+ score: 0,
47
+ message: "The required target term is missing from the suggestion."
48
+ });
49
+ }
50
+ for (const check of options.checks ?? []) addCheck(check.id, check.weight, check.evaluate);
51
+ const input = Object.freeze({
52
+ request,
53
+ suggestion
54
+ });
55
+ const results = await Promise.all(checks.map(async (check) => {
56
+ let output;
57
+ try {
58
+ output = await check.evaluate(input);
59
+ } catch (error) {
60
+ throw new TranslationSuggestionError("quality-check-failed", `Translation quality check "${check.id}" failed.`, { cause: error });
61
+ }
62
+ const details = typeof output === "object" && output !== null ? output : void 0;
63
+ const score = typeof output === "number" ? output : details?.score;
64
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > 100) throw new TranslationSuggestionError("quality-check-failed", `Translation quality check "${check.id}" returned an invalid score.`);
65
+ return Object.freeze({
66
+ id: check.id,
67
+ score,
68
+ weight: check.weight,
69
+ passed: score === 100,
70
+ ...details?.message ? { message: details.message } : {}
71
+ });
72
+ }));
73
+ const totalWeight = checks.reduce((total, check) => total + check.weight, 0);
74
+ const score = totalWeight === 0 ? 100 : Math.round(results.reduce((total, result) => total + result.score * result.weight, 0) / totalWeight);
75
+ return Object.freeze({
76
+ score,
77
+ checks: Object.freeze(results)
78
+ });
79
+ };
80
+ const suggestTranslation = async (provider, request, signal, options = {}) => {
81
+ assertServerOnly();
82
+ if (!request.key.trim() || !request.sourceMessage.trim()) throw new TranslationSuggestionError("invalid-source", "A translation key and non-empty source message are required.");
83
+ const sourceLocale = canonicalize(request.sourceLocale);
84
+ const targetLocale = canonicalize(request.targetLocale);
85
+ const normalizedRequest = Object.freeze({
86
+ ...request,
87
+ sourceLocale,
88
+ targetLocale,
89
+ terminology: request.terminology ? Object.freeze([...request.terminology]) : void 0
90
+ });
91
+ const qualityOptions = options.quality;
92
+ if (qualityOptions) {
93
+ const checkIds = /* @__PURE__ */ new Set();
94
+ for (const [index, rule] of (qualityOptions.terminology ?? []).entries()) {
95
+ if (typeof rule.source !== "string" || typeof rule.target !== "string" || !rule.source.trim() || !rule.target.trim() || rule.weight !== void 0 && (!Number.isFinite(rule.weight) || rule.weight <= 0)) throw new TranslationSuggestionError("invalid-quality-config", "Translation terminology rules require non-empty terms and positive finite weights.");
96
+ if (normalizedRequest.sourceMessage.toLocaleLowerCase(sourceLocale).includes(rule.source.toLocaleLowerCase(sourceLocale))) checkIds.add(`terminology-${index + 1}`);
97
+ }
98
+ for (const check of qualityOptions.checks ?? []) {
99
+ const id = check.id;
100
+ if (typeof id !== "string" || !id.trim() || checkIds.has(id) || typeof check.evaluate !== "function") throw new TranslationSuggestionError("invalid-quality-config", "Translation quality checks require unique non-empty IDs and an evaluator.");
101
+ checkIds.add(id);
102
+ if (check.weight !== void 0 && (!Number.isFinite(check.weight) || check.weight <= 0)) throw new TranslationSuggestionError("invalid-quality-config", "Translation quality check weights must be positive finite numbers.");
103
+ }
104
+ }
105
+ try {
106
+ new intl_messageformat.default(normalizedRequest.sourceMessage, sourceLocale);
107
+ } catch (error) {
108
+ throw new TranslationSuggestionError("invalid-source", `The source message for "${request.key}" has invalid ICU syntax.`, { cause: error });
109
+ }
110
+ if (signal?.aborted) throw new TranslationSuggestionError("aborted", `Translation suggestion for "${request.key}" was aborted.`, { cause: signal.reason });
111
+ let suggestion;
112
+ try {
113
+ suggestion = await provider.suggest(normalizedRequest, signal);
114
+ } catch (error) {
115
+ if (error instanceof TranslationSuggestionError) throw error;
116
+ if (signal?.aborted || isAbortError(error)) throw new TranslationSuggestionError("aborted", `Translation suggestion for "${request.key}" was aborted.`, { cause: error });
117
+ throw new TranslationSuggestionError("provider-failed", `The translation provider failed for "${request.key}".`, { cause: error });
118
+ }
119
+ if (typeof suggestion !== "string" || !suggestion.trim()) throw new TranslationSuggestionError("invalid-output", `The translation provider returned an empty or non-text suggestion for "${request.key}".`);
120
+ try {
121
+ new intl_messageformat.default(suggestion, targetLocale);
122
+ } catch (error) {
123
+ throw new TranslationSuggestionError("invalid-output", `The translation provider returned invalid message syntax for "${request.key}".`, { cause: error });
124
+ }
125
+ const sourcePlaceholders = getPlaceholders(normalizedRequest.sourceMessage);
126
+ const translatedPlaceholders = getPlaceholders(suggestion);
127
+ if (sourcePlaceholders.length !== translatedPlaceholders.length || sourcePlaceholders.some((placeholder, index) => placeholder !== translatedPlaceholders[index])) throw new TranslationSuggestionError("placeholder-mismatch", `The translation provider changed placeholders for "${request.key}".`);
128
+ const quality = qualityOptions ? await createQualityReport(normalizedRequest, suggestion, qualityOptions) : void 0;
129
+ return Object.freeze({
130
+ key: normalizedRequest.key,
131
+ locale: targetLocale,
132
+ value: suggestion,
133
+ approved: false,
134
+ ...quality ? { quality } : {}
135
+ });
136
+ };
137
+ /** Calls authorize for every server-side suggestion and fails closed. */
138
+ const createAuthorizedSuggestionProvider = (provider, authorize) => ({ async suggest(request, signal) {
139
+ assertServerOnly();
140
+ if (signal?.aborted) throw new TranslationSuggestionError("aborted", "Translation suggestion authorization was aborted.", { cause: signal.reason });
141
+ const authorizedRequest = Object.freeze({
142
+ ...request,
143
+ terminology: request.terminology ? Object.freeze([...request.terminology]) : void 0
144
+ });
145
+ let authorized;
146
+ try {
147
+ authorized = await authorize(authorizedRequest, signal);
148
+ } catch (error) {
149
+ if (signal?.aborted || isAbortError(error)) throw new TranslationSuggestionError("aborted", "Translation suggestion authorization was aborted.", { cause: error });
150
+ throw new TranslationSuggestionError("authorization-failed", "Translation suggestion authorization failed.");
151
+ }
152
+ if (signal?.aborted) throw new TranslationSuggestionError("aborted", "Translation suggestion authorization was aborted.", { cause: signal.reason });
153
+ if (authorized !== true) throw new TranslationSuggestionError("unauthorized", "The caller is not authorized to request this translation suggestion.");
154
+ return provider.suggest(authorizedRequest, signal);
155
+ } });
156
+ const abortableDelay = (delay, signal) => new Promise((resolve, reject) => {
157
+ if (signal?.aborted) {
158
+ reject(new TranslationSuggestionError("aborted", "Translation provider request was aborted.", { cause: signal.reason }));
159
+ return;
160
+ }
161
+ let timer;
162
+ const onAbort = () => {
163
+ clearTimeout(timer);
164
+ signal?.removeEventListener("abort", onAbort);
165
+ reject(new TranslationSuggestionError("aborted", "Translation provider request was aborted.", { cause: signal?.reason }));
166
+ };
167
+ timer = setTimeout(() => {
168
+ signal?.removeEventListener("abort", onAbort);
169
+ resolve();
170
+ }, delay);
171
+ signal?.addEventListener("abort", onAbort, { once: true });
172
+ });
173
+ const createRateLimitedSuggestionProvider = (provider, options = {}) => {
174
+ const maxConcurrent = options.maxConcurrent ?? 2;
175
+ const minIntervalMs = options.minIntervalMs ?? 0;
176
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) throw new Error("maxConcurrent must be a positive integer.");
177
+ if (!Number.isFinite(minIntervalMs) || minIntervalMs < 0) throw new Error("minIntervalMs must be a non-negative finite number.");
178
+ let activeRequests = 0;
179
+ let nextStartAt = 0;
180
+ return { async suggest(request, signal) {
181
+ assertServerOnly();
182
+ if (activeRequests >= maxConcurrent) throw new TranslationSuggestionError("rate-limited", "The translation provider concurrency limit was reached.");
183
+ activeRequests += 1;
184
+ const startAt = Math.max(Date.now(), nextStartAt);
185
+ nextStartAt = startAt + minIntervalMs;
186
+ try {
187
+ const delay = startAt - Date.now();
188
+ if (delay > 0) await abortableDelay(delay, signal);
189
+ else if (signal?.aborted) throw new TranslationSuggestionError("aborted", "Translation provider request was aborted.", { cause: signal.reason });
190
+ return await provider.suggest(request, signal);
191
+ } finally {
192
+ activeRequests -= 1;
193
+ }
194
+ } };
195
+ };
196
+ exports.TranslationReviewConflictError = require_ai_review.TranslationReviewConflictError;
197
+ exports.TranslationSuggestionError = TranslationSuggestionError;
198
+ exports.createAuthorizedSuggestionProvider = createAuthorizedSuggestionProvider;
199
+ exports.createInMemoryTranslationReviewStore = require_ai_review.createInMemoryTranslationReviewStore;
200
+ exports.createRateLimitedSuggestionProvider = createRateLimitedSuggestionProvider;
201
+ exports.createTransactionalTranslationReviewStore = require_ai_review.createTransactionalTranslationReviewStore;
202
+ exports.createTranslationReviewWorkflow = require_ai_review.createTranslationReviewWorkflow;
203
+ exports.suggestTranslation = suggestTranslation;
204
+
205
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["IntlMessageFormat"],"sources":["../../src/ai/index.ts"],"sourcesContent":["import IntlMessageFormat from \"intl-messageformat\";\n\nexport interface TranslationSuggestionRequest {\n sourceLocale: string;\n targetLocale: string;\n key: string;\n sourceMessage: string;\n context?: string;\n terminology?: readonly string[];\n}\n\nexport interface TranslationTerminologyRule {\n /** Source substring that must be present before the target term is required. */\n source: string;\n /** Required, case-insensitive target substring in the suggestion. */\n target: string;\n weight?: number;\n}\n\nexport interface TranslationQualityCheckInput {\n request: Readonly<TranslationSuggestionRequest>;\n suggestion: string;\n}\n\nexport interface TranslationQualityCheckOutput {\n /** Quality score from 0 to 100. */\n score: number;\n message?: string;\n}\n\nexport interface TranslationQualityCheck {\n id: string;\n weight?: number;\n evaluate(\n input: Readonly<TranslationQualityCheckInput>,\n ):\n | number\n | TranslationQualityCheckOutput\n | Promise<number | TranslationQualityCheckOutput>;\n}\n\nexport interface TranslationQualityOptions {\n terminology?: readonly TranslationTerminologyRule[];\n /** Custom checks receive the request, including its optional context. */\n checks?: readonly TranslationQualityCheck[];\n}\n\nexport interface TranslationQualityCheckResult {\n id: string;\n score: number;\n weight: number;\n passed: boolean;\n message?: string;\n}\n\nexport interface TranslationQualityReport {\n /** Weighted mean of all applicable checks, rounded to the nearest integer. */\n score: number;\n checks: readonly TranslationQualityCheckResult[];\n}\n\nexport interface SuggestTranslationOptions {\n quality?: TranslationQualityOptions;\n}\n\nexport interface TranslationSuggestionProvider {\n suggest(\n request: Readonly<TranslationSuggestionRequest>,\n signal?: AbortSignal,\n ): Promise<string>;\n}\n\nexport type TranslationSuggestionAuthorizer = (\n request: Readonly<TranslationSuggestionRequest>,\n signal?: AbortSignal,\n) => boolean | Promise<boolean>;\n\nexport interface TranslationSuggestion {\n key: string;\n locale: string;\n value: string;\n approved: false;\n quality?: TranslationQualityReport;\n}\n\nexport type TranslationSuggestionErrorCode =\n | \"invalid-source\"\n | \"invalid-output\"\n | \"placeholder-mismatch\"\n | \"provider-failed\"\n | \"rate-limited\"\n | \"server-only\"\n | \"unauthorized\"\n | \"authorization-failed\"\n | \"invalid-quality-config\"\n | \"quality-check-failed\"\n | \"aborted\";\n\nexport class TranslationSuggestionError extends Error {\n constructor(\n public readonly code: TranslationSuggestionErrorCode,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"TranslationSuggestionError\";\n }\n}\n\nconst canonicalize = (locale: string): string => {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n\n if (!canonical) {\n throw new Error();\n }\n\n return canonical;\n } catch {\n throw new TranslationSuggestionError(\n \"invalid-source\",\n `Invalid BCP 47 locale \"${locale}\".`,\n );\n }\n};\n\nconst getPlaceholders = (message: string): string[] =>\n [...message.matchAll(/\\{\\s*([A-Za-z_][\\w.-]*)/g)]\n .map((match) => match[1])\n .filter((name): name is string => name !== undefined)\n .sort();\n\nconst isAbortError = (error: unknown): boolean =>\n error instanceof Error && error.name === \"AbortError\";\n\nconst assertServerOnly = (): void => {\n if (typeof window !== \"undefined\") {\n throw new TranslationSuggestionError(\n \"server-only\",\n \"Translation providers must only be called from a server environment.\",\n );\n }\n};\n\nconst createQualityReport = async (\n request: Readonly<TranslationSuggestionRequest>,\n suggestion: string,\n options: TranslationQualityOptions,\n): Promise<TranslationQualityReport> => {\n const checks: Array<{\n id: string;\n weight: number;\n evaluate: (\n input: Readonly<TranslationQualityCheckInput>,\n ) => number | TranslationQualityCheckOutput | Promise<number | TranslationQualityCheckOutput>;\n }> = [];\n const addCheck = (\n id: string,\n weight: number | undefined,\n evaluate: (input: Readonly<TranslationQualityCheckInput>) =>\n | number\n | TranslationQualityCheckOutput\n | Promise<number | TranslationQualityCheckOutput>,\n ): void => {\n const normalizedWeight = weight ?? 1;\n\n if (!Number.isFinite(normalizedWeight) || normalizedWeight <= 0) {\n throw new TranslationSuggestionError(\n \"invalid-quality-config\",\n \"Translation quality check weights must be positive finite numbers.\",\n );\n }\n\n if (!id.trim() || checks.some((check) => check.id === id)) {\n throw new TranslationSuggestionError(\n \"invalid-quality-config\",\n \"Translation quality check IDs must be unique and non-empty.\",\n );\n }\n\n checks.push({ id, weight: normalizedWeight, evaluate });\n };\n\n for (const [index, rule] of (options.terminology ?? []).entries()) {\n if (!rule.source.trim() || !rule.target.trim()) {\n throw new TranslationSuggestionError(\n \"invalid-quality-config\",\n \"Translation terminology rules require source and target terms.\",\n );\n }\n\n const sourceTerm = rule.source.toLocaleLowerCase(request.sourceLocale);\n const targetTerm = rule.target.toLocaleLowerCase(request.targetLocale);\n\n if (request.sourceMessage.toLocaleLowerCase(request.sourceLocale).includes(sourceTerm)) {\n addCheck(\n `terminology-${index + 1}`,\n rule.weight,\n () =>\n suggestion.toLocaleLowerCase(request.targetLocale).includes(targetTerm)\n ? 100\n : {\n score: 0,\n message: \"The required target term is missing from the suggestion.\",\n },\n );\n }\n }\n\n for (const check of options.checks ?? []) {\n addCheck(check.id, check.weight, check.evaluate);\n }\n\n const input = Object.freeze({ request, suggestion });\n const results = await Promise.all(\n checks.map(async (check): Promise<TranslationQualityCheckResult> => {\n let output: number | TranslationQualityCheckOutput;\n\n try {\n output = await check.evaluate(input);\n } catch (error) {\n throw new TranslationSuggestionError(\n \"quality-check-failed\",\n `Translation quality check \"${check.id}\" failed.`,\n { cause: error },\n );\n }\n\n const details =\n typeof output === \"object\" && output !== null ? output : undefined;\n const score = typeof output === \"number\" ? output : details?.score;\n\n if (typeof score !== \"number\" || !Number.isFinite(score) || score < 0 || score > 100) {\n throw new TranslationSuggestionError(\n \"quality-check-failed\",\n `Translation quality check \"${check.id}\" returned an invalid score.`,\n );\n }\n\n return Object.freeze({\n id: check.id,\n score,\n weight: check.weight,\n passed: score === 100,\n ...(details?.message ? { message: details.message } : {}),\n });\n }),\n );\n const totalWeight = checks.reduce((total, check) => total + check.weight, 0);\n const score =\n totalWeight === 0\n ? 100\n : Math.round(\n results.reduce(\n (total, result) => total + result.score * result.weight,\n 0,\n ) / totalWeight,\n );\n\n return Object.freeze({ score, checks: Object.freeze(results) });\n};\n\nexport const suggestTranslation = async (\n provider: TranslationSuggestionProvider,\n request: TranslationSuggestionRequest,\n signal?: AbortSignal,\n options: SuggestTranslationOptions = {},\n): Promise<TranslationSuggestion> => {\n assertServerOnly();\n\n if (!request.key.trim() || !request.sourceMessage.trim()) {\n throw new TranslationSuggestionError(\n \"invalid-source\",\n \"A translation key and non-empty source message are required.\",\n );\n }\n\n const sourceLocale = canonicalize(request.sourceLocale);\n const targetLocale = canonicalize(request.targetLocale);\n const normalizedRequest = Object.freeze({\n ...request,\n sourceLocale,\n targetLocale,\n terminology: request.terminology\n ? Object.freeze([...request.terminology])\n : undefined,\n });\n const qualityOptions = options.quality;\n\n if (qualityOptions) {\n const checkIds = new Set<string>();\n for (const [index, rule] of (qualityOptions.terminology ?? []).entries()) {\n if (\n typeof rule.source !== \"string\" ||\n typeof rule.target !== \"string\" ||\n !rule.source.trim() ||\n !rule.target.trim() ||\n (rule.weight !== undefined &&\n (!Number.isFinite(rule.weight) || rule.weight <= 0))\n ) {\n throw new TranslationSuggestionError(\n \"invalid-quality-config\",\n \"Translation terminology rules require non-empty terms and positive finite weights.\",\n );\n }\n\n if (\n normalizedRequest.sourceMessage\n .toLocaleLowerCase(sourceLocale)\n .includes(rule.source.toLocaleLowerCase(sourceLocale))\n ) {\n checkIds.add(`terminology-${index + 1}`);\n }\n }\n\n for (const check of qualityOptions.checks ?? []) {\n const id = check.id;\n\n if (\n typeof id !== \"string\" ||\n !id.trim() ||\n checkIds.has(id) ||\n typeof check.evaluate !== \"function\"\n ) {\n throw new TranslationSuggestionError(\n \"invalid-quality-config\",\n \"Translation quality checks require unique non-empty IDs and an evaluator.\",\n );\n }\n\n checkIds.add(id);\n\n if (\n check.weight !== undefined &&\n (!Number.isFinite(check.weight) || check.weight <= 0)\n ) {\n throw new TranslationSuggestionError(\n \"invalid-quality-config\",\n \"Translation quality check weights must be positive finite numbers.\",\n );\n }\n }\n }\n\n try {\n new IntlMessageFormat(normalizedRequest.sourceMessage, sourceLocale);\n } catch (error) {\n throw new TranslationSuggestionError(\n \"invalid-source\",\n `The source message for \"${request.key}\" has invalid ICU syntax.`,\n { cause: error },\n );\n }\n\n if (signal?.aborted) {\n throw new TranslationSuggestionError(\n \"aborted\",\n `Translation suggestion for \"${request.key}\" was aborted.`,\n { cause: signal.reason },\n );\n }\n\n let suggestion: string;\n\n try {\n suggestion = await provider.suggest(normalizedRequest, signal);\n } catch (error) {\n if (error instanceof TranslationSuggestionError) {\n throw error;\n }\n\n if (signal?.aborted || isAbortError(error)) {\n throw new TranslationSuggestionError(\n \"aborted\",\n `Translation suggestion for \"${request.key}\" was aborted.`,\n { cause: error },\n );\n }\n\n throw new TranslationSuggestionError(\n \"provider-failed\",\n `The translation provider failed for \"${request.key}\".`,\n { cause: error },\n );\n }\n\n if (typeof suggestion !== \"string\" || !suggestion.trim()) {\n throw new TranslationSuggestionError(\n \"invalid-output\",\n `The translation provider returned an empty or non-text suggestion for \"${request.key}\".`,\n );\n }\n\n try {\n new IntlMessageFormat(suggestion, targetLocale);\n } catch (error) {\n throw new TranslationSuggestionError(\n \"invalid-output\",\n `The translation provider returned invalid message syntax for \"${request.key}\".`,\n { cause: error },\n );\n }\n\n const sourcePlaceholders = getPlaceholders(normalizedRequest.sourceMessage);\n const translatedPlaceholders = getPlaceholders(suggestion);\n\n if (\n sourcePlaceholders.length !== translatedPlaceholders.length ||\n sourcePlaceholders.some(\n (placeholder, index) => placeholder !== translatedPlaceholders[index],\n )\n ) {\n throw new TranslationSuggestionError(\n \"placeholder-mismatch\",\n `The translation provider changed placeholders for \"${request.key}\".`,\n );\n }\n\n const quality = qualityOptions\n ? await createQualityReport(normalizedRequest, suggestion, qualityOptions)\n : undefined;\n\n return Object.freeze({\n key: normalizedRequest.key,\n locale: targetLocale,\n value: suggestion,\n approved: false,\n ...(quality ? { quality } : {}),\n });\n};\n\n/** Calls authorize for every server-side suggestion and fails closed. */\nexport const createAuthorizedSuggestionProvider = (\n provider: TranslationSuggestionProvider,\n authorize: TranslationSuggestionAuthorizer,\n): TranslationSuggestionProvider => ({\n async suggest(request, signal) {\n assertServerOnly();\n\n if (signal?.aborted) {\n throw new TranslationSuggestionError(\n \"aborted\",\n \"Translation suggestion authorization was aborted.\",\n { cause: signal.reason },\n );\n }\n\n const authorizedRequest = Object.freeze({\n ...request,\n terminology: request.terminology\n ? Object.freeze([...request.terminology])\n : undefined,\n });\n let authorized: boolean;\n\n try {\n authorized = await authorize(authorizedRequest, signal);\n } catch (error) {\n if (signal?.aborted || isAbortError(error)) {\n throw new TranslationSuggestionError(\n \"aborted\",\n \"Translation suggestion authorization was aborted.\",\n { cause: error },\n );\n }\n\n throw new TranslationSuggestionError(\n \"authorization-failed\",\n \"Translation suggestion authorization failed.\",\n );\n }\n\n if (signal?.aborted) {\n throw new TranslationSuggestionError(\n \"aborted\",\n \"Translation suggestion authorization was aborted.\",\n { cause: signal.reason },\n );\n }\n\n if (authorized !== true) {\n throw new TranslationSuggestionError(\n \"unauthorized\",\n \"The caller is not authorized to request this translation suggestion.\",\n );\n }\n\n return provider.suggest(authorizedRequest, signal);\n },\n});\n\nexport interface RateLimitedProviderOptions {\n maxConcurrent?: number;\n minIntervalMs?: number;\n}\n\nconst abortableDelay = (delay: number, signal?: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(\n new TranslationSuggestionError(\n \"aborted\",\n \"Translation provider request was aborted.\",\n { cause: signal.reason },\n ),\n );\n return;\n }\n\n let timer: ReturnType<typeof setTimeout>;\n const onAbort = () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n reject(\n new TranslationSuggestionError(\n \"aborted\",\n \"Translation provider request was aborted.\",\n { cause: signal?.reason },\n ),\n );\n };\n\n timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, delay);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n\nexport const createRateLimitedSuggestionProvider = (\n provider: TranslationSuggestionProvider,\n options: RateLimitedProviderOptions = {},\n): TranslationSuggestionProvider => {\n const maxConcurrent = options.maxConcurrent ?? 2;\n const minIntervalMs = options.minIntervalMs ?? 0;\n\n if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) {\n throw new Error(\"maxConcurrent must be a positive integer.\");\n }\n\n if (!Number.isFinite(minIntervalMs) || minIntervalMs < 0) {\n throw new Error(\"minIntervalMs must be a non-negative finite number.\");\n }\n\n let activeRequests = 0;\n let nextStartAt = 0;\n\n return {\n async suggest(request, signal) {\n assertServerOnly();\n\n if (activeRequests >= maxConcurrent) {\n throw new TranslationSuggestionError(\n \"rate-limited\",\n \"The translation provider concurrency limit was reached.\",\n );\n }\n\n activeRequests += 1;\n const startAt = Math.max(Date.now(), nextStartAt);\n nextStartAt = startAt + minIntervalMs;\n\n try {\n const delay = startAt - Date.now();\n\n if (delay > 0) {\n await abortableDelay(delay, signal);\n } else if (signal?.aborted) {\n throw new TranslationSuggestionError(\n \"aborted\",\n \"Translation provider request was aborted.\",\n { cause: signal.reason },\n );\n }\n\n return await provider.suggest(request, signal);\n } finally {\n activeRequests -= 1;\n }\n },\n };\n};\n\nexport {\n createInMemoryTranslationReviewStore,\n createTransactionalTranslationReviewStore,\n createTranslationReviewWorkflow,\n TranslationReviewConflictError,\n} from \"./review\";\nexport type {\n TransactionalTranslationReviewPersistence,\n TransactionalTranslationReviewTransaction,\n TranslationReviewAuditRecord,\n TranslationReviewRecord,\n TranslationReviewStatus,\n TranslationReviewStore,\n TranslationReviewWorkflow,\n CreateTransactionalTranslationReviewStoreOptions,\n VersionedTranslation,\n} from \"./review\";\n"],"mappings":";;;;;;AAkGA,IAAa,6BAAb,cAAgD,MAAM;CAElC;CADlB,YACE,MACA,SACA,SACA;EACA,MAAM,SAAS,OAAO;EAJN,KAAA,OAAA;EAKhB,KAAK,OAAO;CACd;AACF;AAEA,MAAM,gBAAgB,WAA2B;CAC/C,IAAI;EACF,MAAM,CAAC,aAAa,KAAK,oBAAoB,MAAM;EAEnD,IAAI,CAAC,WACH,MAAM,IAAI,MAAM;EAGlB,OAAO;CACT,QAAQ;EACN,MAAM,IAAI,2BACR,kBACA,0BAA0B,OAAO,GACnC;CACF;AACF;AAEA,MAAM,mBAAmB,YACvB,CAAC,GAAG,QAAQ,SAAS,0BAA0B,CAAC,CAAC,CAC9C,KAAK,UAAU,MAAM,EAAE,CAAC,CACxB,QAAQ,SAAyB,SAAS,KAAA,CAAS,CAAC,CACpD,KAAK;AAEV,MAAM,gBAAgB,UACpB,iBAAiB,S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,EACL,MAAM,QAAQ,SAAS,QAAQ;EAC7B,iBAAiB;EAEjB,IAAI,kBAAkB,eACpB,MAAM,IAAI,2BACR,gBACA,yDACF;EAGF,kBAAkB;EAClB,MAAM,UAAU,KAAK,IAAI,KAAK,IAAI,GAAG,WAAW;EAChD,cAAc,UAAU;EAExB,IAAI;GACF,MAAM,QAAQ,UAAU,KAAK,IAAI;GAEjC,IAAI,QAAQ,GACV,MAAM,eAAe,OAAO,MAAM;QAC7B,IAAI,QAAQ,SACjB,MAAM,IAAI,2BACR,WACA,6CACA,EAAE,OAAO,OAAO,OAAO,CACzB;GAGF,OAAO,MAAM,SAAS,QAAQ,SAAS,MAAM;EAC/C,UAAU;GACR,kBAAkB;EACpB;CACF,EACF;AACF"}
@@ -0,0 +1,75 @@
1
+ import { CreateTransactionalTranslationReviewStoreOptions, TransactionalTranslationReviewPersistence, TransactionalTranslationReviewTransaction, TranslationReviewAuditRecord, TranslationReviewConflictError, TranslationReviewRecord, TranslationReviewStatus, TranslationReviewStore, TranslationReviewWorkflow, VersionedTranslation, createInMemoryTranslationReviewStore, createTransactionalTranslationReviewStore, createTranslationReviewWorkflow } from "./review.cjs";
2
+ export interface TranslationSuggestionRequest {
3
+ sourceLocale: string;
4
+ targetLocale: string;
5
+ key: string;
6
+ sourceMessage: string;
7
+ context?: string;
8
+ terminology?: readonly string[];
9
+ }
10
+ export interface TranslationTerminologyRule {
11
+ /** Source substring that must be present before the target term is required. */
12
+ source: string;
13
+ /** Required, case-insensitive target substring in the suggestion. */
14
+ target: string;
15
+ weight?: number;
16
+ }
17
+ export interface TranslationQualityCheckInput {
18
+ request: Readonly<TranslationSuggestionRequest>;
19
+ suggestion: string;
20
+ }
21
+ export interface TranslationQualityCheckOutput {
22
+ /** Quality score from 0 to 100. */
23
+ score: number;
24
+ message?: string;
25
+ }
26
+ export interface TranslationQualityCheck {
27
+ id: string;
28
+ weight?: number;
29
+ evaluate(input: Readonly<TranslationQualityCheckInput>): number | TranslationQualityCheckOutput | Promise<number | TranslationQualityCheckOutput>;
30
+ }
31
+ export interface TranslationQualityOptions {
32
+ terminology?: readonly TranslationTerminologyRule[];
33
+ /** Custom checks receive the request, including its optional context. */
34
+ checks?: readonly TranslationQualityCheck[];
35
+ }
36
+ export interface TranslationQualityCheckResult {
37
+ id: string;
38
+ score: number;
39
+ weight: number;
40
+ passed: boolean;
41
+ message?: string;
42
+ }
43
+ export interface TranslationQualityReport {
44
+ /** Weighted mean of all applicable checks, rounded to the nearest integer. */
45
+ score: number;
46
+ checks: readonly TranslationQualityCheckResult[];
47
+ }
48
+ export interface SuggestTranslationOptions {
49
+ quality?: TranslationQualityOptions;
50
+ }
51
+ export interface TranslationSuggestionProvider {
52
+ suggest(request: Readonly<TranslationSuggestionRequest>, signal?: AbortSignal): Promise<string>;
53
+ }
54
+ export type TranslationSuggestionAuthorizer = (request: Readonly<TranslationSuggestionRequest>, signal?: AbortSignal) => boolean | Promise<boolean>;
55
+ export interface TranslationSuggestion {
56
+ key: string;
57
+ locale: string;
58
+ value: string;
59
+ approved: false;
60
+ quality?: TranslationQualityReport;
61
+ }
62
+ export type TranslationSuggestionErrorCode = "invalid-source" | "invalid-output" | "placeholder-mismatch" | "provider-failed" | "rate-limited" | "server-only" | "unauthorized" | "authorization-failed" | "invalid-quality-config" | "quality-check-failed" | "aborted";
63
+ export declare class TranslationSuggestionError extends Error {
64
+ readonly code: TranslationSuggestionErrorCode;
65
+ constructor(code: TranslationSuggestionErrorCode, message: string, options?: ErrorOptions);
66
+ }
67
+ export declare const suggestTranslation: (provider: TranslationSuggestionProvider, request: TranslationSuggestionRequest, signal?: AbortSignal, options?: SuggestTranslationOptions) => Promise<TranslationSuggestion>;
68
+ /** Calls authorize for every server-side suggestion and fails closed. */
69
+ export declare const createAuthorizedSuggestionProvider: (provider: TranslationSuggestionProvider, authorize: TranslationSuggestionAuthorizer) => TranslationSuggestionProvider;
70
+ export interface RateLimitedProviderOptions {
71
+ maxConcurrent?: number;
72
+ minIntervalMs?: number;
73
+ }
74
+ export declare const createRateLimitedSuggestionProvider: (provider: TranslationSuggestionProvider, options?: RateLimitedProviderOptions) => TranslationSuggestionProvider;
75
+ export { type CreateTransactionalTranslationReviewStoreOptions, type TransactionalTranslationReviewPersistence, type TransactionalTranslationReviewTransaction, type TranslationReviewAuditRecord, TranslationReviewConflictError, type TranslationReviewRecord, type TranslationReviewStatus, type TranslationReviewStore, type TranslationReviewWorkflow, type VersionedTranslation, createInMemoryTranslationReviewStore, createTransactionalTranslationReviewStore, createTranslationReviewWorkflow };
@@ -0,0 +1,75 @@
1
+ import { CreateTransactionalTranslationReviewStoreOptions, TransactionalTranslationReviewPersistence, TransactionalTranslationReviewTransaction, TranslationReviewAuditRecord, TranslationReviewConflictError, TranslationReviewRecord, TranslationReviewStatus, TranslationReviewStore, TranslationReviewWorkflow, VersionedTranslation, createInMemoryTranslationReviewStore, createTransactionalTranslationReviewStore, createTranslationReviewWorkflow } from "./review.js";
2
+ export interface TranslationSuggestionRequest {
3
+ sourceLocale: string;
4
+ targetLocale: string;
5
+ key: string;
6
+ sourceMessage: string;
7
+ context?: string;
8
+ terminology?: readonly string[];
9
+ }
10
+ export interface TranslationTerminologyRule {
11
+ /** Source substring that must be present before the target term is required. */
12
+ source: string;
13
+ /** Required, case-insensitive target substring in the suggestion. */
14
+ target: string;
15
+ weight?: number;
16
+ }
17
+ export interface TranslationQualityCheckInput {
18
+ request: Readonly<TranslationSuggestionRequest>;
19
+ suggestion: string;
20
+ }
21
+ export interface TranslationQualityCheckOutput {
22
+ /** Quality score from 0 to 100. */
23
+ score: number;
24
+ message?: string;
25
+ }
26
+ export interface TranslationQualityCheck {
27
+ id: string;
28
+ weight?: number;
29
+ evaluate(input: Readonly<TranslationQualityCheckInput>): number | TranslationQualityCheckOutput | Promise<number | TranslationQualityCheckOutput>;
30
+ }
31
+ export interface TranslationQualityOptions {
32
+ terminology?: readonly TranslationTerminologyRule[];
33
+ /** Custom checks receive the request, including its optional context. */
34
+ checks?: readonly TranslationQualityCheck[];
35
+ }
36
+ export interface TranslationQualityCheckResult {
37
+ id: string;
38
+ score: number;
39
+ weight: number;
40
+ passed: boolean;
41
+ message?: string;
42
+ }
43
+ export interface TranslationQualityReport {
44
+ /** Weighted mean of all applicable checks, rounded to the nearest integer. */
45
+ score: number;
46
+ checks: readonly TranslationQualityCheckResult[];
47
+ }
48
+ export interface SuggestTranslationOptions {
49
+ quality?: TranslationQualityOptions;
50
+ }
51
+ export interface TranslationSuggestionProvider {
52
+ suggest(request: Readonly<TranslationSuggestionRequest>, signal?: AbortSignal): Promise<string>;
53
+ }
54
+ export type TranslationSuggestionAuthorizer = (request: Readonly<TranslationSuggestionRequest>, signal?: AbortSignal) => boolean | Promise<boolean>;
55
+ export interface TranslationSuggestion {
56
+ key: string;
57
+ locale: string;
58
+ value: string;
59
+ approved: false;
60
+ quality?: TranslationQualityReport;
61
+ }
62
+ export type TranslationSuggestionErrorCode = "invalid-source" | "invalid-output" | "placeholder-mismatch" | "provider-failed" | "rate-limited" | "server-only" | "unauthorized" | "authorization-failed" | "invalid-quality-config" | "quality-check-failed" | "aborted";
63
+ export declare class TranslationSuggestionError extends Error {
64
+ readonly code: TranslationSuggestionErrorCode;
65
+ constructor(code: TranslationSuggestionErrorCode, message: string, options?: ErrorOptions);
66
+ }
67
+ export declare const suggestTranslation: (provider: TranslationSuggestionProvider, request: TranslationSuggestionRequest, signal?: AbortSignal, options?: SuggestTranslationOptions) => Promise<TranslationSuggestion>;
68
+ /** Calls authorize for every server-side suggestion and fails closed. */
69
+ export declare const createAuthorizedSuggestionProvider: (provider: TranslationSuggestionProvider, authorize: TranslationSuggestionAuthorizer) => TranslationSuggestionProvider;
70
+ export interface RateLimitedProviderOptions {
71
+ maxConcurrent?: number;
72
+ minIntervalMs?: number;
73
+ }
74
+ export declare const createRateLimitedSuggestionProvider: (provider: TranslationSuggestionProvider, options?: RateLimitedProviderOptions) => TranslationSuggestionProvider;
75
+ export { type CreateTransactionalTranslationReviewStoreOptions, type TransactionalTranslationReviewPersistence, type TransactionalTranslationReviewTransaction, type TranslationReviewAuditRecord, TranslationReviewConflictError, type TranslationReviewRecord, type TranslationReviewStatus, type TranslationReviewStore, type TranslationReviewWorkflow, type VersionedTranslation, createInMemoryTranslationReviewStore, createTransactionalTranslationReviewStore, createTranslationReviewWorkflow };
@@ -0,0 +1,195 @@
1
+ import { TranslationReviewConflictError, createInMemoryTranslationReviewStore, createTransactionalTranslationReviewStore, createTranslationReviewWorkflow } from "./review.js";
2
+ import IntlMessageFormat from "intl-messageformat";
3
+ // src/ai/index.ts
4
+ var TranslationSuggestionError = class extends Error {
5
+ code;
6
+ constructor(code, message, options) {
7
+ super(message, options);
8
+ this.code = code;
9
+ this.name = "TranslationSuggestionError";
10
+ }
11
+ };
12
+ const canonicalize = (locale) => {
13
+ try {
14
+ const [canonical] = Intl.getCanonicalLocales(locale);
15
+ if (!canonical) throw new Error();
16
+ return canonical;
17
+ } catch {
18
+ throw new TranslationSuggestionError("invalid-source", `Invalid BCP 47 locale "${locale}".`);
19
+ }
20
+ };
21
+ const getPlaceholders = (message) => [...message.matchAll(/\{\s*([A-Za-z_][\w.-]*)/g)].map((match) => match[1]).filter((name) => name !== void 0).sort();
22
+ const isAbortError = (error) => error instanceof Error && error.name === "AbortError";
23
+ const assertServerOnly = () => {
24
+ if (typeof window !== "undefined") throw new TranslationSuggestionError("server-only", "Translation providers must only be called from a server environment.");
25
+ };
26
+ const createQualityReport = async (request, suggestion, options) => {
27
+ const checks = [];
28
+ const addCheck = (id, weight, evaluate) => {
29
+ const normalizedWeight = weight ?? 1;
30
+ if (!Number.isFinite(normalizedWeight) || normalizedWeight <= 0) throw new TranslationSuggestionError("invalid-quality-config", "Translation quality check weights must be positive finite numbers.");
31
+ if (!id.trim() || checks.some((check) => check.id === id)) throw new TranslationSuggestionError("invalid-quality-config", "Translation quality check IDs must be unique and non-empty.");
32
+ checks.push({
33
+ id,
34
+ weight: normalizedWeight,
35
+ evaluate
36
+ });
37
+ };
38
+ for (const [index, rule] of (options.terminology ?? []).entries()) {
39
+ if (!rule.source.trim() || !rule.target.trim()) throw new TranslationSuggestionError("invalid-quality-config", "Translation terminology rules require source and target terms.");
40
+ const sourceTerm = rule.source.toLocaleLowerCase(request.sourceLocale);
41
+ const targetTerm = rule.target.toLocaleLowerCase(request.targetLocale);
42
+ if (request.sourceMessage.toLocaleLowerCase(request.sourceLocale).includes(sourceTerm)) addCheck(`terminology-${index + 1}`, rule.weight, () => suggestion.toLocaleLowerCase(request.targetLocale).includes(targetTerm) ? 100 : {
43
+ score: 0,
44
+ message: "The required target term is missing from the suggestion."
45
+ });
46
+ }
47
+ for (const check of options.checks ?? []) addCheck(check.id, check.weight, check.evaluate);
48
+ const input = Object.freeze({
49
+ request,
50
+ suggestion
51
+ });
52
+ const results = await Promise.all(checks.map(async (check) => {
53
+ let output;
54
+ try {
55
+ output = await check.evaluate(input);
56
+ } catch (error) {
57
+ throw new TranslationSuggestionError("quality-check-failed", `Translation quality check "${check.id}" failed.`, { cause: error });
58
+ }
59
+ const details = typeof output === "object" && output !== null ? output : void 0;
60
+ const score = typeof output === "number" ? output : details?.score;
61
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > 100) throw new TranslationSuggestionError("quality-check-failed", `Translation quality check "${check.id}" returned an invalid score.`);
62
+ return Object.freeze({
63
+ id: check.id,
64
+ score,
65
+ weight: check.weight,
66
+ passed: score === 100,
67
+ ...details?.message ? { message: details.message } : {}
68
+ });
69
+ }));
70
+ const totalWeight = checks.reduce((total, check) => total + check.weight, 0);
71
+ const score = totalWeight === 0 ? 100 : Math.round(results.reduce((total, result) => total + result.score * result.weight, 0) / totalWeight);
72
+ return Object.freeze({
73
+ score,
74
+ checks: Object.freeze(results)
75
+ });
76
+ };
77
+ const suggestTranslation = async (provider, request, signal, options = {}) => {
78
+ assertServerOnly();
79
+ if (!request.key.trim() || !request.sourceMessage.trim()) throw new TranslationSuggestionError("invalid-source", "A translation key and non-empty source message are required.");
80
+ const sourceLocale = canonicalize(request.sourceLocale);
81
+ const targetLocale = canonicalize(request.targetLocale);
82
+ const normalizedRequest = Object.freeze({
83
+ ...request,
84
+ sourceLocale,
85
+ targetLocale,
86
+ terminology: request.terminology ? Object.freeze([...request.terminology]) : void 0
87
+ });
88
+ const qualityOptions = options.quality;
89
+ if (qualityOptions) {
90
+ const checkIds = /* @__PURE__ */ new Set();
91
+ for (const [index, rule] of (qualityOptions.terminology ?? []).entries()) {
92
+ if (typeof rule.source !== "string" || typeof rule.target !== "string" || !rule.source.trim() || !rule.target.trim() || rule.weight !== void 0 && (!Number.isFinite(rule.weight) || rule.weight <= 0)) throw new TranslationSuggestionError("invalid-quality-config", "Translation terminology rules require non-empty terms and positive finite weights.");
93
+ if (normalizedRequest.sourceMessage.toLocaleLowerCase(sourceLocale).includes(rule.source.toLocaleLowerCase(sourceLocale))) checkIds.add(`terminology-${index + 1}`);
94
+ }
95
+ for (const check of qualityOptions.checks ?? []) {
96
+ const id = check.id;
97
+ if (typeof id !== "string" || !id.trim() || checkIds.has(id) || typeof check.evaluate !== "function") throw new TranslationSuggestionError("invalid-quality-config", "Translation quality checks require unique non-empty IDs and an evaluator.");
98
+ checkIds.add(id);
99
+ if (check.weight !== void 0 && (!Number.isFinite(check.weight) || check.weight <= 0)) throw new TranslationSuggestionError("invalid-quality-config", "Translation quality check weights must be positive finite numbers.");
100
+ }
101
+ }
102
+ try {
103
+ new IntlMessageFormat(normalizedRequest.sourceMessage, sourceLocale);
104
+ } catch (error) {
105
+ throw new TranslationSuggestionError("invalid-source", `The source message for "${request.key}" has invalid ICU syntax.`, { cause: error });
106
+ }
107
+ if (signal?.aborted) throw new TranslationSuggestionError("aborted", `Translation suggestion for "${request.key}" was aborted.`, { cause: signal.reason });
108
+ let suggestion;
109
+ try {
110
+ suggestion = await provider.suggest(normalizedRequest, signal);
111
+ } catch (error) {
112
+ if (error instanceof TranslationSuggestionError) throw error;
113
+ if (signal?.aborted || isAbortError(error)) throw new TranslationSuggestionError("aborted", `Translation suggestion for "${request.key}" was aborted.`, { cause: error });
114
+ throw new TranslationSuggestionError("provider-failed", `The translation provider failed for "${request.key}".`, { cause: error });
115
+ }
116
+ if (typeof suggestion !== "string" || !suggestion.trim()) throw new TranslationSuggestionError("invalid-output", `The translation provider returned an empty or non-text suggestion for "${request.key}".`);
117
+ try {
118
+ new IntlMessageFormat(suggestion, targetLocale);
119
+ } catch (error) {
120
+ throw new TranslationSuggestionError("invalid-output", `The translation provider returned invalid message syntax for "${request.key}".`, { cause: error });
121
+ }
122
+ const sourcePlaceholders = getPlaceholders(normalizedRequest.sourceMessage);
123
+ const translatedPlaceholders = getPlaceholders(suggestion);
124
+ if (sourcePlaceholders.length !== translatedPlaceholders.length || sourcePlaceholders.some((placeholder, index) => placeholder !== translatedPlaceholders[index])) throw new TranslationSuggestionError("placeholder-mismatch", `The translation provider changed placeholders for "${request.key}".`);
125
+ const quality = qualityOptions ? await createQualityReport(normalizedRequest, suggestion, qualityOptions) : void 0;
126
+ return Object.freeze({
127
+ key: normalizedRequest.key,
128
+ locale: targetLocale,
129
+ value: suggestion,
130
+ approved: false,
131
+ ...quality ? { quality } : {}
132
+ });
133
+ };
134
+ /** Calls authorize for every server-side suggestion and fails closed. */
135
+ const createAuthorizedSuggestionProvider = (provider, authorize) => ({ async suggest(request, signal) {
136
+ assertServerOnly();
137
+ if (signal?.aborted) throw new TranslationSuggestionError("aborted", "Translation suggestion authorization was aborted.", { cause: signal.reason });
138
+ const authorizedRequest = Object.freeze({
139
+ ...request,
140
+ terminology: request.terminology ? Object.freeze([...request.terminology]) : void 0
141
+ });
142
+ let authorized;
143
+ try {
144
+ authorized = await authorize(authorizedRequest, signal);
145
+ } catch (error) {
146
+ if (signal?.aborted || isAbortError(error)) throw new TranslationSuggestionError("aborted", "Translation suggestion authorization was aborted.", { cause: error });
147
+ throw new TranslationSuggestionError("authorization-failed", "Translation suggestion authorization failed.");
148
+ }
149
+ if (signal?.aborted) throw new TranslationSuggestionError("aborted", "Translation suggestion authorization was aborted.", { cause: signal.reason });
150
+ if (authorized !== true) throw new TranslationSuggestionError("unauthorized", "The caller is not authorized to request this translation suggestion.");
151
+ return provider.suggest(authorizedRequest, signal);
152
+ } });
153
+ const abortableDelay = (delay, signal) => new Promise((resolve, reject) => {
154
+ if (signal?.aborted) {
155
+ reject(new TranslationSuggestionError("aborted", "Translation provider request was aborted.", { cause: signal.reason }));
156
+ return;
157
+ }
158
+ let timer;
159
+ const onAbort = () => {
160
+ clearTimeout(timer);
161
+ signal?.removeEventListener("abort", onAbort);
162
+ reject(new TranslationSuggestionError("aborted", "Translation provider request was aborted.", { cause: signal?.reason }));
163
+ };
164
+ timer = setTimeout(() => {
165
+ signal?.removeEventListener("abort", onAbort);
166
+ resolve();
167
+ }, delay);
168
+ signal?.addEventListener("abort", onAbort, { once: true });
169
+ });
170
+ const createRateLimitedSuggestionProvider = (provider, options = {}) => {
171
+ const maxConcurrent = options.maxConcurrent ?? 2;
172
+ const minIntervalMs = options.minIntervalMs ?? 0;
173
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) throw new Error("maxConcurrent must be a positive integer.");
174
+ if (!Number.isFinite(minIntervalMs) || minIntervalMs < 0) throw new Error("minIntervalMs must be a non-negative finite number.");
175
+ let activeRequests = 0;
176
+ let nextStartAt = 0;
177
+ return { async suggest(request, signal) {
178
+ assertServerOnly();
179
+ if (activeRequests >= maxConcurrent) throw new TranslationSuggestionError("rate-limited", "The translation provider concurrency limit was reached.");
180
+ activeRequests += 1;
181
+ const startAt = Math.max(Date.now(), nextStartAt);
182
+ nextStartAt = startAt + minIntervalMs;
183
+ try {
184
+ const delay = startAt - Date.now();
185
+ if (delay > 0) await abortableDelay(delay, signal);
186
+ else if (signal?.aborted) throw new TranslationSuggestionError("aborted", "Translation provider request was aborted.", { cause: signal.reason });
187
+ return await provider.suggest(request, signal);
188
+ } finally {
189
+ activeRequests -= 1;
190
+ }
191
+ } };
192
+ };
193
+ export { TranslationReviewConflictError, TranslationSuggestionError, createAuthorizedSuggestionProvider, createInMemoryTranslationReviewStore, createRateLimitedSuggestionProvider, createTransactionalTranslationReviewStore, createTranslationReviewWorkflow, suggestTranslation };
194
+
195
+ //# sourceMappingURL=index.js.map