@uniformdev/tms-sdk 19.135.1-alpha.11

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/dist/index.js ADDED
@@ -0,0 +1,1043 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ collectTranslationPayload: () => collectTranslationPayload,
24
+ getCompositionForTranslation: () => getCompositionForTranslation,
25
+ getEntryForTranslation: () => getEntryForTranslation,
26
+ mergeCompositionTranslationToUniform: () => mergeCompositionTranslationToUniform,
27
+ mergeEntryTranslationToUniform: () => mergeEntryTranslationToUniform,
28
+ mergeTranslationToUniform: () => mergeTranslationToUniform,
29
+ translateComposition: () => translateComposition,
30
+ translateEntry: () => translateEntry
31
+ });
32
+ module.exports = __toCommonJS(src_exports);
33
+
34
+ // src/collectTranslationPayload.ts
35
+ var import_canvas2 = require("@uniformdev/canvas");
36
+ var import_richtext4 = require("@uniformdev/richtext");
37
+
38
+ // src/constants.ts
39
+ var TRANSLATION_PAYLOAD_SOURCE_KEY = "source";
40
+ var TRANSLATION_PAYLOAD_TARGET_KEY = "target";
41
+ var TRANSLATION_PAYLOAD_ORIGINAL_TARGET_KEY = "originalTarget";
42
+ var SUPPORTED_PARAM_TYPES = {
43
+ text: "text",
44
+ richText: "richText"
45
+ };
46
+
47
+ // src/richText/renderAsTranslatableXml.ts
48
+ var import_richtext = require("@uniformdev/richtext");
49
+ var REF_ATTRIBUTE_NAME = "ref";
50
+ function renderAsTranslatableXml(root) {
51
+ if (!root) {
52
+ return null;
53
+ }
54
+ const result = {
55
+ attributes: [],
56
+ xmlParts: []
57
+ };
58
+ renderXmlNode(result, root);
59
+ const metadata = result.attributes.reduce(
60
+ (result2, current, index) => {
61
+ result2[String(index)] = {
62
+ attrs: current
63
+ };
64
+ return result2;
65
+ },
66
+ {}
67
+ );
68
+ return {
69
+ metadata,
70
+ xml: result.xmlParts.join("")
71
+ };
72
+ }
73
+ var IGNORE_ATTRS = ["type", "children", "text"];
74
+ function renderXmlNode(context, node) {
75
+ if (!node) {
76
+ return;
77
+ }
78
+ const base64Props = getPropsAsBase64(node, IGNORE_ATTRS);
79
+ let refKey = context.attributes.findIndex((x) => x === base64Props);
80
+ if (refKey == -1) {
81
+ context.attributes.push(base64Props);
82
+ refKey = context.attributes.length - 1;
83
+ }
84
+ context.xmlParts.push(`<${node.type} ${REF_ATTRIBUTE_NAME}="${refKey}"`);
85
+ const metaAttrsString = getNodeMetaAttributesString(node);
86
+ if (metaAttrsString) {
87
+ context.xmlParts.push(" " + metaAttrsString);
88
+ }
89
+ context.xmlParts.push(">");
90
+ if ((0, import_richtext.isRichTextNodeType)(node, "text")) {
91
+ context.xmlParts.push(node.text);
92
+ } else if (Array.isArray(node.children) && node.children.length) {
93
+ node.children.forEach((child) => {
94
+ renderXmlNode(context, child);
95
+ });
96
+ }
97
+ context.xmlParts.push(`</${node.type}>`);
98
+ }
99
+ var getPropsAsBase64 = (node, ignoreProps) => {
100
+ const props = {};
101
+ Object.keys(node).forEach((key) => {
102
+ if (!ignoreProps.includes(key)) {
103
+ props[key] = node[key];
104
+ }
105
+ });
106
+ return btoa(JSON.stringify(props));
107
+ };
108
+ var getNodeMetaAttributesString = (node) => {
109
+ const metadata = {};
110
+ if ((0, import_richtext.isRichTextNodeType)(node, "text")) {
111
+ const formatTags = (0, import_richtext.getRichTextTagsFromTextFormat)(node.format);
112
+ if (formatTags.length) {
113
+ metadata["format"] = formatTags.join(" ");
114
+ }
115
+ } else if ((0, import_richtext.isRichTextNodeType)(node, "heading")) {
116
+ if (node.tag) {
117
+ metadata["tag"] = node.tag;
118
+ }
119
+ } else if ((0, import_richtext.isRichTextNodeType)(node, "paragraph")) {
120
+ if (node.format) {
121
+ metadata["format"] = node.format;
122
+ }
123
+ } else if ((0, import_richtext.isRichTextNodeType)(node, "list")) {
124
+ if (node.tag) {
125
+ metadata["tag"] = node.tag;
126
+ }
127
+ } else if ((0, import_richtext.isRichTextNodeType)(node, "listitem")) {
128
+ metadata["value"] = String(node.value);
129
+ }
130
+ if (!Object.keys(metadata).length) {
131
+ return "";
132
+ }
133
+ const result = [];
134
+ Object.entries(metadata).forEach(([key, value]) => {
135
+ result.push(`${key}="${value}"`);
136
+ });
137
+ return result.join(" ");
138
+ };
139
+
140
+ // src/translationHelpers.ts
141
+ var import_canvas = require("@uniformdev/canvas");
142
+ var import_richtext3 = require("@uniformdev/richtext");
143
+ var import_lite = require("dequal/lite");
144
+
145
+ // src/richText/parseTranslatableXml.ts
146
+ var import_richtext2 = require("@uniformdev/richtext");
147
+ var import_fast_xml_parser = require("fast-xml-parser");
148
+ var ATTR_NAME_PREFIX = "@_";
149
+ var ATTRIBUTES_SUBNODE_NAME = ":@";
150
+ var IGNORE_PROPS_PREFIX = [ATTR_NAME_PREFIX, ATTRIBUTES_SUBNODE_NAME, "#"];
151
+ var parseTranslatableXml = ({ xml, metadata }) => {
152
+ const parser = new import_fast_xml_parser.XMLParser({
153
+ ignoreDeclaration: true,
154
+ ignorePiTags: true,
155
+ ignoreAttributes: false,
156
+ preserveOrder: true,
157
+ trimValues: false,
158
+ attributeNamePrefix: ATTR_NAME_PREFIX
159
+ });
160
+ const rawObj = parser.parse(prepareXml(xml));
161
+ const result = processParseObject(rawObj, {
162
+ metadata,
163
+ nodeTypes: []
164
+ });
165
+ return result;
166
+ };
167
+ var prepareXml = (xml) => {
168
+ const result = xml.replaceAll("&lt;/text>", "</text>");
169
+ return result;
170
+ };
171
+ var processParseObject = (rawObj, context) => {
172
+ const result = visitAndTransformNode(rawObj, context);
173
+ const root = Array.isArray(result) ? result.at(0) : result;
174
+ if (root && root.type === "root") {
175
+ const value = { root };
176
+ if ((0, import_richtext2.isRichTextValue)(value)) {
177
+ return value;
178
+ }
179
+ }
180
+ return null;
181
+ };
182
+ var visitAndTransformNode = (node, context) => {
183
+ if (Array.isArray(node)) {
184
+ return node.map((x) => visitAndTransformNode(x, context)).filter((node2) => !!node2);
185
+ } else if (typeof node === "object" && node !== null) {
186
+ const type = Object.keys(node).find(
187
+ (key) => !IGNORE_PROPS_PREFIX.some((prefix) => key.startsWith(prefix))
188
+ );
189
+ if (!type) {
190
+ return null;
191
+ }
192
+ const transformed = {};
193
+ transformed["type"] = type;
194
+ const propsFromRef = restorePropsFromRef(node, context);
195
+ Object.entries(propsFromRef).forEach(([key, value]) => {
196
+ transformed[key] = value;
197
+ });
198
+ if (type === "text") {
199
+ const nestedNode = node[type];
200
+ const nestedNodeAsArray = Array.isArray(nestedNode) ? nestedNode : [nestedNode];
201
+ const firstChild = nestedNodeAsArray.at(0);
202
+ const text = firstChild == null ? void 0 : firstChild["#text"];
203
+ transformed["text"] = typeof text === "string" && text ? text : "";
204
+ } else {
205
+ const children = [];
206
+ const nestedNode = node[type];
207
+ if (typeof nestedNode === "object" && nestedNode) {
208
+ const nestedNodeAsArray = Array.isArray(nestedNode) ? nestedNode : [nestedNode];
209
+ nestedNodeAsArray.forEach((currNode) => {
210
+ const transformed2 = visitAndTransformNode(currNode, context);
211
+ if (transformed2) {
212
+ children.push(transformed2);
213
+ }
214
+ });
215
+ }
216
+ if (children.length) {
217
+ transformed["children"] = children;
218
+ } else if (type === "paragraph" && Array.isArray(nestedNode) && !nestedNode.length) {
219
+ transformed["children"] = [];
220
+ }
221
+ }
222
+ return transformed;
223
+ } else {
224
+ return node;
225
+ }
226
+ };
227
+ var restorePropsFromRef = (node, context) => {
228
+ const result = {};
229
+ let uniformRef = node[ATTR_NAME_PREFIX + REF_ATTRIBUTE_NAME];
230
+ if (!uniformRef) {
231
+ const attrsSubNode = node[ATTRIBUTES_SUBNODE_NAME];
232
+ uniformRef = attrsSubNode == null ? void 0 : attrsSubNode[ATTR_NAME_PREFIX + REF_ATTRIBUTE_NAME];
233
+ }
234
+ if (typeof uniformRef === "string" && uniformRef && context.metadata[uniformRef]) {
235
+ const metadata = context.metadata[uniformRef];
236
+ if (metadata.attrs) {
237
+ const decodedProps = JSON.parse(atob(metadata.attrs));
238
+ Object.keys(decodedProps).forEach((key) => {
239
+ result[key] = decodedProps[key];
240
+ });
241
+ }
242
+ }
243
+ return result;
244
+ };
245
+
246
+ // src/richText/types.ts
247
+ var isTranslatableRichTextValue = (value) => {
248
+ if (typeof value !== "object" || !value) {
249
+ return false;
250
+ }
251
+ if (!("xml" in value) || typeof value.xml !== "string") {
252
+ return false;
253
+ }
254
+ if (!("metadata" in value) || typeof value.metadata !== "object" || !value.metadata) {
255
+ return false;
256
+ }
257
+ return true;
258
+ };
259
+
260
+ // src/translationHelpers.ts
261
+ var MERGE_TRANSLATION_ERRORS = {
262
+ unknown: "Unknown error",
263
+ "invalid-args": "Invalid arguments",
264
+ "project-id-mismatch": "Project ID mismatch",
265
+ "entity-id-mismatch": "Enity ID mismatch",
266
+ "entity-locales-mismatch": "Entity does not include required locales"
267
+ };
268
+ var createErrorResult = (errorKind) => {
269
+ return { updated: false, errorKind, errorText: MERGE_TRANSLATION_ERRORS[errorKind] };
270
+ };
271
+ var processComponentTranslation = ({
272
+ uniformSourceLocale,
273
+ uniformTargetLocale,
274
+ originalNode,
275
+ translatedComponent
276
+ }) => {
277
+ var _a, _b;
278
+ let updated = false;
279
+ if (!originalNode.type || !originalNode._id) {
280
+ return { updated };
281
+ }
282
+ const componentParameters = "parameters" in originalNode ? originalNode.parameters : void 0;
283
+ const entryFields = "fields" in originalNode ? originalNode.fields : void 0;
284
+ const originalParametersOrFields = componentParameters != null ? componentParameters : entryFields;
285
+ Object.entries((_a = translatedComponent.parameters) != null ? _a : {}).forEach(([paramKey, parameter]) => {
286
+ const originalParameter = originalParametersOrFields == null ? void 0 : originalParametersOrFields[paramKey];
287
+ if (!originalParameter) {
288
+ return;
289
+ }
290
+ const result = processParameterTranslation({
291
+ uniformSourceLocale,
292
+ uniformTargetLocale,
293
+ originalParameter,
294
+ parameter
295
+ });
296
+ if (result.updated) {
297
+ updated = true;
298
+ }
299
+ });
300
+ Object.entries((_b = translatedComponent._overrides) != null ? _b : {}).forEach(([overrideKey, override]) => {
301
+ var _a2;
302
+ const originalOverride = (_a2 = originalNode._overrides) == null ? void 0 : _a2[overrideKey];
303
+ if (!originalOverride) {
304
+ return;
305
+ }
306
+ const result = processOverrideTranslation({
307
+ uniformSourceLocale,
308
+ uniformTargetLocale,
309
+ originalOverride,
310
+ override
311
+ });
312
+ if (result.updated) {
313
+ updated = true;
314
+ }
315
+ });
316
+ return { updated };
317
+ };
318
+ var processParameterTranslation = ({
319
+ uniformSourceLocale,
320
+ uniformTargetLocale,
321
+ originalParameter,
322
+ parameter
323
+ }) => {
324
+ var _a, _b, _c, _d;
325
+ if (originalParameter.type !== parameter.type) {
326
+ return { updated: false };
327
+ }
328
+ if (!originalParameter.locales && originalParameter.value === void 0) {
329
+ return { updated: false };
330
+ }
331
+ const sourceValue = (_a = parameter.locales) == null ? void 0 : _a[TRANSLATION_PAYLOAD_SOURCE_KEY];
332
+ const targetValue = (_b = parameter.locales) == null ? void 0 : _b[TRANSLATION_PAYLOAD_TARGET_KEY];
333
+ const originalTargetValue = (_c = parameter.locales) == null ? void 0 : _c[TRANSLATION_PAYLOAD_ORIGINAL_TARGET_KEY];
334
+ const originalParameterSource = originalParameter.locales ? originalParameter.locales[uniformSourceLocale] : originalParameter.value;
335
+ const isSourceValueUntouched = isSameParameterValue({
336
+ parameterType: originalParameter.type,
337
+ left: originalParameterSource,
338
+ right: sourceValue
339
+ });
340
+ const isTargetValueUntouched = isSameParameterValue({
341
+ parameterType: originalParameter.type,
342
+ left: (_d = originalParameter.locales) == null ? void 0 : _d[uniformTargetLocale],
343
+ right: originalTargetValue
344
+ });
345
+ if (targetValue !== void 0 && isSourceValueUntouched && isTargetValueUntouched) {
346
+ if (parameter.type == SUPPORTED_PARAM_TYPES.richText && isTranslatableRichTextValue(targetValue)) {
347
+ try {
348
+ const richTextValue = parseTranslatableXml(targetValue);
349
+ updateOriginalParameterValue(richTextValue);
350
+ return { updated: true };
351
+ } catch (e) {
352
+ return { updated: false };
353
+ }
354
+ } else if (parameter.type == SUPPORTED_PARAM_TYPES.text) {
355
+ updateOriginalParameterValue(targetValue);
356
+ return { updated: true };
357
+ }
358
+ }
359
+ function updateOriginalParameterValue(value) {
360
+ if (originalParameter.locales) {
361
+ originalParameter.locales[uniformTargetLocale] = value;
362
+ } else if (originalParameter.value !== void 0) {
363
+ originalParameter.locales = {
364
+ [uniformSourceLocale]: originalParameter.value,
365
+ [uniformTargetLocale]: value
366
+ };
367
+ originalParameter.value = void 0;
368
+ }
369
+ }
370
+ return { updated: false };
371
+ };
372
+ var processOverrideTranslation = ({
373
+ uniformSourceLocale,
374
+ uniformTargetLocale,
375
+ originalOverride,
376
+ override
377
+ }) => {
378
+ var _a, _b;
379
+ let updated = false;
380
+ Object.entries((_a = override.parameters) != null ? _a : {}).forEach(([paramKey, parameter]) => {
381
+ var _a2;
382
+ const originalParameter = (_a2 = originalOverride.parameters) == null ? void 0 : _a2[paramKey];
383
+ if (!originalParameter) {
384
+ return;
385
+ }
386
+ const result = processParameterTranslation({
387
+ uniformSourceLocale,
388
+ uniformTargetLocale,
389
+ originalParameter,
390
+ parameter
391
+ });
392
+ if (result.updated) {
393
+ updated = true;
394
+ }
395
+ });
396
+ Object.entries((_b = override.slots) != null ? _b : {}).forEach(([slotKey, slotComponents]) => {
397
+ var _a2;
398
+ const originalSlotComponents = (_a2 = originalOverride.slots) == null ? void 0 : _a2[slotKey];
399
+ if (!(originalSlotComponents == null ? void 0 : originalSlotComponents.length)) {
400
+ return;
401
+ }
402
+ slotComponents.forEach((slotComponent) => {
403
+ if (!slotComponent.type || !slotComponent._id) {
404
+ return;
405
+ }
406
+ const originalSlotComponent = originalSlotComponents.find(
407
+ (x) => x._id === slotComponent._id && x.type === slotComponent.type
408
+ );
409
+ if (!originalSlotComponent) {
410
+ return;
411
+ }
412
+ (0, import_canvas.walkNodeTree)(slotComponent, ({ node: component, type, actions }) => {
413
+ if (type !== "component" || !component._id || !component.type) {
414
+ actions.stopProcessingDescendants();
415
+ return;
416
+ }
417
+ const originalComponent = findComponentInNodeTree(originalSlotComponent, component._id);
418
+ if (!originalComponent || originalComponent.type !== component.type) {
419
+ actions.stopProcessingDescendants();
420
+ return;
421
+ }
422
+ const { updated: isComponentUpdated } = processComponentTranslation({
423
+ uniformSourceLocale,
424
+ uniformTargetLocale,
425
+ originalNode: originalComponent,
426
+ translatedComponent: component
427
+ });
428
+ if (isComponentUpdated) {
429
+ updated = true;
430
+ }
431
+ });
432
+ });
433
+ });
434
+ return { updated };
435
+ };
436
+ var isSameParameterValue = ({
437
+ parameterType,
438
+ left,
439
+ right
440
+ }) => {
441
+ switch (parameterType) {
442
+ case SUPPORTED_PARAM_TYPES.text:
443
+ return left === right || !left && !right;
444
+ break;
445
+ case SUPPORTED_PARAM_TYPES.richText:
446
+ try {
447
+ if ((0, import_richtext3.isRichTextValueConsideredEmpty)(left) && (0, import_richtext3.isRichTextValueConsideredEmpty)(right)) {
448
+ return true;
449
+ }
450
+ } catch (e) {
451
+ return false;
452
+ }
453
+ return (0, import_lite.dequal)(left, right);
454
+ break;
455
+ default:
456
+ return left === right;
457
+ }
458
+ };
459
+ var findComponentInNodeTree = (root, id) => {
460
+ let result;
461
+ (0, import_canvas.walkNodeTree)(root, ({ node, actions }) => {
462
+ if (node._id === id) {
463
+ result = node;
464
+ actions.stopProcessingDescendants();
465
+ }
466
+ });
467
+ return result;
468
+ };
469
+
470
+ // src/collectTranslationPayload.ts
471
+ var MERGE_TRANSLATION_ERRORS2 = {
472
+ unknown: "Unknown error",
473
+ "invalid-args": "Invalid arguments",
474
+ "entity-source-locale-missing": "Entity does not include specified Uniform source locale"
475
+ };
476
+ var createErrorResult2 = (errorKind) => {
477
+ return { errorKind, errorText: MERGE_TRANSLATION_ERRORS2[errorKind] };
478
+ };
479
+ var collectTranslationPayload = ({
480
+ uniformProjectId,
481
+ uniformSourceLocale,
482
+ uniformTargetLocale,
483
+ uniformReleaseId,
484
+ targetLang,
485
+ entity,
486
+ entityType
487
+ }) => {
488
+ if (!uniformSourceLocale || !uniformTargetLocale || !targetLang || !entity) {
489
+ return createErrorResult2("invalid-args");
490
+ }
491
+ if (!entity._locales || !entity._locales.includes(uniformSourceLocale)) {
492
+ return createErrorResult2("entity-source-locale-missing");
493
+ }
494
+ const payload = {
495
+ schemaVersion: 1,
496
+ metadata: {
497
+ uniformProjectId,
498
+ uniformSourceLocale,
499
+ uniformTargetLocale,
500
+ uniformReleaseId,
501
+ targetLang,
502
+ entityType,
503
+ entity: {
504
+ id: entity._id,
505
+ slug: entity._slug || ""
506
+ }
507
+ },
508
+ components: {}
509
+ };
510
+ (0, import_canvas2.walkNodeTree)(entity, ({ node, actions }) => {
511
+ if (!node.type || !node._id) {
512
+ actions.stopProcessingDescendants();
513
+ return;
514
+ }
515
+ const { _id, type, parameters, _overrides } = collectFromNode({
516
+ uniformSourceLocale,
517
+ uniformTargetLocale,
518
+ node,
519
+ deep: false
520
+ });
521
+ if (parameters || _overrides) {
522
+ payload.components[node._id] = {
523
+ _id,
524
+ type,
525
+ parameters,
526
+ _overrides
527
+ };
528
+ }
529
+ });
530
+ return { payload };
531
+ };
532
+ var collectFromNode = ({
533
+ uniformSourceLocale,
534
+ uniformTargetLocale,
535
+ node,
536
+ deep
537
+ }) => {
538
+ var _a, _b, _c;
539
+ const collectedParameters = {};
540
+ const collectedSlots = {};
541
+ const collectedOverrides = {};
542
+ const componentParameters = "parameters" in node ? node.parameters : void 0;
543
+ const entryFields = "fields" in node ? node.fields : void 0;
544
+ Object.entries((_a = componentParameters != null ? componentParameters : entryFields) != null ? _a : {}).forEach(([paramKey, param]) => {
545
+ var _a2, _b2;
546
+ const sourceLocaleValue = (_a2 = param.locales) == null ? void 0 : _a2[uniformSourceLocale];
547
+ const targetLocaleValue = (_b2 = param.locales) == null ? void 0 : _b2[uniformTargetLocale];
548
+ if (!canTranslateParameterValue(param, sourceLocaleValue)) {
549
+ return;
550
+ }
551
+ if (!isTargetLocaleUntouched(param.type, sourceLocaleValue, targetLocaleValue)) {
552
+ return;
553
+ }
554
+ collectedParameters[paramKey] = {
555
+ type: param.type,
556
+ locales: {
557
+ [TRANSLATION_PAYLOAD_SOURCE_KEY]: sourceLocaleValue,
558
+ [TRANSLATION_PAYLOAD_TARGET_KEY]: preprocessTargetValue(param, sourceLocaleValue),
559
+ [TRANSLATION_PAYLOAD_ORIGINAL_TARGET_KEY]: targetLocaleValue
560
+ }
561
+ };
562
+ });
563
+ if (deep) {
564
+ Object.entries((_b = "slots" in node ? node.slots : null) != null ? _b : {}).forEach(([slotKey, slotComponents]) => {
565
+ slotComponents.map((slotComponent) => {
566
+ var _a2;
567
+ if (!slotComponent.type || !slotComponent._id) {
568
+ return;
569
+ }
570
+ const collectedNode = collectFromNode({
571
+ uniformSourceLocale,
572
+ uniformTargetLocale,
573
+ node: slotComponent,
574
+ deep: true
575
+ });
576
+ const hasContent = collectedNode.parameters || collectedNode._overrides || collectedNode.slots;
577
+ if (hasContent) {
578
+ (_a2 = collectedSlots[slotKey]) != null ? _a2 : collectedSlots[slotKey] = [];
579
+ collectedSlots[slotKey].push(collectedNode);
580
+ }
581
+ });
582
+ });
583
+ }
584
+ Object.entries((_c = node._overrides) != null ? _c : {}).forEach(([overrideKey, override]) => {
585
+ var _a2, _b2;
586
+ Object.entries((_a2 = override.parameters) != null ? _a2 : {}).forEach(([paramKey, param]) => {
587
+ var _a3, _b3, _c2, _d, _e;
588
+ const sourceLocaleValue = (_a3 = param.locales) == null ? void 0 : _a3[uniformSourceLocale];
589
+ const targetLocaleValue = (_b3 = param.locales) == null ? void 0 : _b3[uniformTargetLocale];
590
+ if (!canTranslateParameterValue(param, sourceLocaleValue)) {
591
+ return;
592
+ }
593
+ if (!isTargetLocaleUntouched(param.type, sourceLocaleValue, targetLocaleValue)) {
594
+ return;
595
+ }
596
+ (_c2 = collectedOverrides[overrideKey]) != null ? _c2 : collectedOverrides[overrideKey] = {};
597
+ (_e = (_d = collectedOverrides[overrideKey]).parameters) != null ? _e : _d.parameters = {};
598
+ collectedOverrides[overrideKey].parameters[paramKey] = {
599
+ type: param.type,
600
+ locales: {
601
+ [TRANSLATION_PAYLOAD_SOURCE_KEY]: sourceLocaleValue,
602
+ [TRANSLATION_PAYLOAD_TARGET_KEY]: preprocessTargetValue(param, sourceLocaleValue),
603
+ [TRANSLATION_PAYLOAD_ORIGINAL_TARGET_KEY]: targetLocaleValue
604
+ }
605
+ };
606
+ });
607
+ Object.entries((_b2 = override.slots) != null ? _b2 : {}).forEach(([slotKey, slotComponents]) => {
608
+ slotComponents.map((slotComponent) => {
609
+ var _a3, _b3, _c2, _d, _e;
610
+ if (!slotComponent.type || !slotComponent._id) {
611
+ return;
612
+ }
613
+ const collectedNode = collectFromNode({
614
+ uniformSourceLocale,
615
+ uniformTargetLocale,
616
+ node: slotComponent,
617
+ // keep tree structure for `Slot Sections`
618
+ // to store whole `override` content in scope of current component
619
+ deep: true
620
+ });
621
+ const hasContent = collectedNode.parameters || collectedNode._overrides || collectedNode.slots;
622
+ if (hasContent) {
623
+ (_a3 = collectedOverrides[overrideKey]) != null ? _a3 : collectedOverrides[overrideKey] = {};
624
+ (_c2 = (_b3 = collectedOverrides[overrideKey]).slots) != null ? _c2 : _b3.slots = {};
625
+ (_e = (_d = collectedOverrides[overrideKey].slots)[slotKey]) != null ? _e : _d[slotKey] = [];
626
+ collectedOverrides[overrideKey].slots[slotKey].push(collectedNode);
627
+ }
628
+ });
629
+ });
630
+ });
631
+ const hasParameters = Object.keys(collectedParameters).length > 0;
632
+ const hasSlots = Object.keys(collectedSlots).length > 0;
633
+ const hasOverrides = Object.keys(collectedOverrides).length > 0;
634
+ return {
635
+ _id: node._id,
636
+ type: node.type,
637
+ parameters: hasParameters ? collectedParameters : void 0,
638
+ slots: hasSlots ? collectedSlots : void 0,
639
+ _overrides: hasOverrides ? collectedOverrides : void 0
640
+ };
641
+ };
642
+ var canTranslateParameterValue = (parameter, value) => {
643
+ if (parameter.type === SUPPORTED_PARAM_TYPES.text) {
644
+ if (typeof value !== "string" || !value) {
645
+ return false;
646
+ }
647
+ if (value.trim().length === 0) {
648
+ return false;
649
+ }
650
+ const bindResult = (0, import_canvas2.bindVariables)({
651
+ variables: {},
652
+ value,
653
+ handleBinding: () => ""
654
+ });
655
+ const valueWithoutVariables = bindResult.result;
656
+ if (!valueWithoutVariables || valueWithoutVariables.trim().length === 0) {
657
+ return false;
658
+ }
659
+ return true;
660
+ } else if (parameter.type === SUPPORTED_PARAM_TYPES.richText) {
661
+ return (0, import_richtext4.isRichTextValue)(value) && !(0, import_richtext4.isRichTextValueConsideredEmpty)(value);
662
+ }
663
+ return false;
664
+ };
665
+ var isTargetLocaleUntouched = (parameterType, sourceLocaleValue, targetLocaleValue) => {
666
+ if (targetLocaleValue === void 0 || targetLocaleValue === null) {
667
+ return true;
668
+ }
669
+ if (parameterType === SUPPORTED_PARAM_TYPES.text && !targetLocaleValue) {
670
+ return true;
671
+ }
672
+ if (parameterType === SUPPORTED_PARAM_TYPES.richText && (0, import_richtext4.isRichTextValueConsideredEmpty)(targetLocaleValue)) {
673
+ return true;
674
+ }
675
+ return isSameParameterValue({
676
+ parameterType,
677
+ left: sourceLocaleValue,
678
+ right: targetLocaleValue
679
+ });
680
+ };
681
+ var preprocessTargetValue = (parameter, value) => {
682
+ if (parameter.type === SUPPORTED_PARAM_TYPES.richText) {
683
+ try {
684
+ return (0, import_richtext4.isRichTextValue)(value) ? renderAsTranslatableXml(value.root) : value;
685
+ } catch (e) {
686
+ return value;
687
+ }
688
+ }
689
+ return value;
690
+ };
691
+
692
+ // src/getCompositionForTranslation.ts
693
+ var import_canvas3 = require("@uniformdev/canvas");
694
+ var getCompositionForTranslation = async ({
695
+ canvasClient,
696
+ compositionId,
697
+ releaseId,
698
+ state = import_canvas3.CANVAS_DRAFT_STATE
699
+ }) => {
700
+ if (!compositionId) {
701
+ return void 0;
702
+ }
703
+ const composition = await canvasClient.getCompositionById({
704
+ compositionId,
705
+ releaseId: releaseId ? releaseId : void 0,
706
+ withComponentIDs: true,
707
+ skipDataResolution: true,
708
+ skipOverridesResolution: true,
709
+ skipPatternResolution: true,
710
+ state
711
+ });
712
+ return composition ? composition : void 0;
713
+ };
714
+
715
+ // src/getEntryForTranslation.ts
716
+ var import_canvas4 = require("@uniformdev/canvas");
717
+ var getEntryForTranslation = async ({
718
+ contentClient,
719
+ entryId,
720
+ releaseId,
721
+ pattern,
722
+ state = import_canvas4.CANVAS_DRAFT_STATE
723
+ }) => {
724
+ if (!entryId) {
725
+ return void 0;
726
+ }
727
+ const entriesResponse = await contentClient.getEntries({
728
+ entryIDs: [entryId],
729
+ releaseId: releaseId ? releaseId : void 0,
730
+ limit: 1,
731
+ withComponentIDs: true,
732
+ skipDataResolution: true,
733
+ skipOverridesResolution: true,
734
+ skipPatternResolution: true,
735
+ pattern,
736
+ state
737
+ });
738
+ const entry = entriesResponse.entries.at(0);
739
+ return entry ? entry : void 0;
740
+ };
741
+
742
+ // src/mergeCompositionTranslationToUniform.ts
743
+ var import_canvas6 = require("@uniformdev/canvas");
744
+
745
+ // src/translateComposition.ts
746
+ var import_canvas5 = require("@uniformdev/canvas");
747
+ var import_immer = require("immer");
748
+ var translateComposition = ({
749
+ composition,
750
+ translationPayload
751
+ }) => {
752
+ var _a;
753
+ if (!composition || !composition.composition || !translationPayload) {
754
+ return createErrorResult("invalid-args");
755
+ }
756
+ if (composition.projectId !== translationPayload.metadata.uniformProjectId) {
757
+ return createErrorResult("project-id-mismatch");
758
+ }
759
+ if (composition.composition._id !== translationPayload.metadata.entity.id) {
760
+ return createErrorResult("entity-id-mismatch");
761
+ }
762
+ const uniformSourceLocale = translationPayload.metadata.uniformSourceLocale;
763
+ const uniformTargetLocale = translationPayload.metadata.uniformTargetLocale;
764
+ const compositionLocales = (_a = composition.composition._locales) != null ? _a : [];
765
+ if (compositionLocales.length > 0 && !compositionLocales.includes(uniformSourceLocale)) {
766
+ return createErrorResult("entity-locales-mismatch");
767
+ }
768
+ let updated = false;
769
+ const translatedComposition = (0, import_immer.produce)(composition, (draft) => {
770
+ var _a2, _b, _c;
771
+ draft.state = import_canvas5.CANVAS_DRAFT_STATE;
772
+ if (!((_a2 = draft.composition._locales) == null ? void 0 : _a2.length)) {
773
+ (_c = (_b = draft.composition)._locales) != null ? _c : _b._locales = [];
774
+ draft.composition._locales.push(uniformSourceLocale);
775
+ }
776
+ if (!draft.composition._locales.includes(uniformTargetLocale)) {
777
+ draft.composition._locales.push(uniformTargetLocale);
778
+ }
779
+ (0, import_canvas5.walkNodeTree)(draft.composition, ({ node: component, type, actions }) => {
780
+ if (type !== "component") {
781
+ actions.stopProcessingDescendants();
782
+ return;
783
+ }
784
+ if (!component.type || !component._id) {
785
+ actions.stopProcessingDescendants();
786
+ return;
787
+ }
788
+ const translatedComponent = translationPayload.components[component._id];
789
+ if (!translatedComponent || component.type !== translatedComponent.type) {
790
+ return;
791
+ }
792
+ const { updated: isComponentUpdated } = processComponentTranslation({
793
+ uniformSourceLocale,
794
+ uniformTargetLocale,
795
+ originalNode: component,
796
+ translatedComponent
797
+ });
798
+ if (isComponentUpdated) {
799
+ updated = true;
800
+ }
801
+ });
802
+ });
803
+ return { result: translatedComposition, updated };
804
+ };
805
+
806
+ // src/mergeCompositionTranslationToUniform.ts
807
+ var mergeCompositionTranslationToUniform = async ({
808
+ canvasClient,
809
+ translationPayload,
810
+ updateComposition = defaultUpdateComposition,
811
+ onNotFound,
812
+ onNotTranslatedResult
813
+ }) => {
814
+ if (!translationPayload) {
815
+ return { translationMerged: false };
816
+ }
817
+ const entityType = translationPayload.metadata.entityType;
818
+ const entityId = translationPayload.metadata.entity.id;
819
+ if (entityType !== "composition" && entityType !== "componentPattern") {
820
+ return { translationMerged: false, entityId };
821
+ }
822
+ const composition = await getCurrentCompositionFromPayload({
823
+ canvasClient,
824
+ translationPayload
825
+ });
826
+ if (!composition) {
827
+ await (onNotFound == null ? void 0 : onNotFound({
828
+ translationPayload
829
+ }));
830
+ return { translationMerged: false, entityId };
831
+ }
832
+ const translationResult = translateComposition({
833
+ composition,
834
+ translationPayload
835
+ });
836
+ const { updated, errorKind, errorText, result: translatedComposition } = translationResult;
837
+ if (translatedComposition && updated && !errorKind) {
838
+ const translationMerged = await updateComposition({
839
+ canvasClient,
840
+ translationPayload,
841
+ composition: translatedComposition
842
+ });
843
+ return { translationMerged, entityId };
844
+ } else {
845
+ await (onNotTranslatedResult == null ? void 0 : onNotTranslatedResult({ updated, errorKind, errorText }));
846
+ return { translationMerged: false, entityId };
847
+ }
848
+ };
849
+ var getCurrentCompositionFromPayload = async ({
850
+ canvasClient,
851
+ translationPayload
852
+ }) => {
853
+ const compositionId = translationPayload.metadata.entity.id;
854
+ const releaseId = translationPayload.metadata.uniformReleaseId;
855
+ const currentComposition = await getCompositionForTranslation({
856
+ canvasClient,
857
+ compositionId,
858
+ releaseId,
859
+ state: import_canvas6.CANVAS_DRAFT_STATE
860
+ });
861
+ return currentComposition;
862
+ };
863
+ var defaultUpdateComposition = async ({
864
+ canvasClient,
865
+ composition
866
+ }) => {
867
+ await canvasClient.updateComposition(composition);
868
+ return true;
869
+ };
870
+
871
+ // src/mergeEntryTranslationToUniform.ts
872
+ var import_canvas8 = require("@uniformdev/canvas");
873
+
874
+ // src/translateEntry.ts
875
+ var import_canvas7 = require("@uniformdev/canvas");
876
+ var import_immer2 = require("immer");
877
+ var translateEntry = ({
878
+ entry,
879
+ translationPayload
880
+ }) => {
881
+ var _a;
882
+ if (!entry || !translationPayload) {
883
+ return createErrorResult("invalid-args");
884
+ }
885
+ if (entry.projectId !== translationPayload.metadata.uniformProjectId) {
886
+ return createErrorResult("project-id-mismatch");
887
+ }
888
+ if ((entry == null ? void 0 : entry.entry._id) !== translationPayload.metadata.entity.id) {
889
+ return createErrorResult("entity-id-mismatch");
890
+ }
891
+ const entryLocales = (_a = entry.entry._locales) != null ? _a : [];
892
+ const uniformSourceLocale = translationPayload.metadata.uniformSourceLocale;
893
+ const uniformTargetLocale = translationPayload.metadata.uniformTargetLocale;
894
+ if (!entryLocales.includes(uniformSourceLocale)) {
895
+ return createErrorResult("entity-locales-mismatch");
896
+ }
897
+ let updated = false;
898
+ const translatedEntry = (0, import_immer2.produce)(entry, (draft) => {
899
+ var _a2, _b;
900
+ draft.state = import_canvas7.CANVAS_DRAFT_STATE;
901
+ if (!entryLocales.includes(uniformTargetLocale)) {
902
+ (_b = (_a2 = draft.entry)._locales) != null ? _b : _a2._locales = [];
903
+ draft.entry._locales.push(uniformTargetLocale);
904
+ }
905
+ (0, import_canvas7.walkNodeTree)(draft.entry, ({ node: component, type, actions }) => {
906
+ if (type !== "entry") {
907
+ actions.stopProcessingDescendants();
908
+ return;
909
+ }
910
+ if (!component.type || !component._id) {
911
+ actions.stopProcessingDescendants();
912
+ return;
913
+ }
914
+ const translatedComponent = translationPayload.components[component._id];
915
+ if (!translatedComponent || component.type !== translatedComponent.type) {
916
+ return;
917
+ }
918
+ const { updated: isComponentUpdated } = processComponentTranslation({
919
+ uniformSourceLocale,
920
+ uniformTargetLocale,
921
+ originalNode: component,
922
+ translatedComponent
923
+ });
924
+ if (isComponentUpdated) {
925
+ updated = true;
926
+ }
927
+ });
928
+ });
929
+ return { result: translatedEntry, updated };
930
+ };
931
+
932
+ // src/mergeEntryTranslationToUniform.ts
933
+ var mergeEntryTranslationToUniform = async ({
934
+ contentClient,
935
+ translationPayload,
936
+ updateEntry = defaultUpdateEntry,
937
+ onNotFound,
938
+ onNotTranslatedResult
939
+ }) => {
940
+ if (!translationPayload) {
941
+ return { translationMerged: false };
942
+ }
943
+ const entityType = translationPayload.metadata.entityType;
944
+ const entityId = translationPayload.metadata.entity.id;
945
+ if (entityType !== "entry" && entityType !== "entryPattern") {
946
+ return { translationMerged: false, entityId };
947
+ }
948
+ const entry = await getCurrentEntryFromPayload({
949
+ contentClient,
950
+ translationPayload
951
+ });
952
+ if (!entry) {
953
+ await (onNotFound == null ? void 0 : onNotFound({
954
+ translationPayload
955
+ }));
956
+ return { translationMerged: false, entityId };
957
+ }
958
+ const translationResult = translateEntry({
959
+ entry,
960
+ translationPayload
961
+ });
962
+ const { updated, errorKind, errorText, result: translatedEntry } = translationResult;
963
+ if (translatedEntry && updated && !errorKind) {
964
+ const translationMerged = await updateEntry({
965
+ contentClient,
966
+ translationPayload,
967
+ entry: translatedEntry
968
+ });
969
+ return { translationMerged, entityId };
970
+ } else {
971
+ await (onNotTranslatedResult == null ? void 0 : onNotTranslatedResult({ updated, errorKind, errorText }));
972
+ return { translationMerged: false, entityId };
973
+ }
974
+ };
975
+ var getCurrentEntryFromPayload = async ({
976
+ contentClient,
977
+ translationPayload
978
+ }) => {
979
+ const entityType = translationPayload.metadata.entityType;
980
+ const entryId = translationPayload.metadata.entity.id;
981
+ const releaseId = translationPayload.metadata.uniformReleaseId;
982
+ const currentEntry = await getEntryForTranslation({
983
+ contentClient,
984
+ entryId,
985
+ releaseId,
986
+ pattern: entityType === "entryPattern",
987
+ state: import_canvas8.CANVAS_DRAFT_STATE
988
+ });
989
+ return currentEntry;
990
+ };
991
+ var defaultUpdateEntry = async ({
992
+ contentClient,
993
+ entry
994
+ }) => {
995
+ await contentClient.upsertEntry(entry);
996
+ return true;
997
+ };
998
+
999
+ // src/mergeTranslationToUniform.ts
1000
+ var mergeTranslationToUniform = async ({
1001
+ canvasClient,
1002
+ contentClient,
1003
+ translationPayload,
1004
+ updateComposition,
1005
+ updateEntry,
1006
+ onNotFound,
1007
+ onNotTranslatedResult
1008
+ }) => {
1009
+ if (!translationPayload) {
1010
+ return { translationMerged: false };
1011
+ }
1012
+ const entityType = translationPayload.metadata.entityType;
1013
+ const entityId = translationPayload.metadata.entity.id;
1014
+ if (entityType === "composition" || entityType === "componentPattern") {
1015
+ return await mergeCompositionTranslationToUniform({
1016
+ canvasClient,
1017
+ translationPayload,
1018
+ updateComposition,
1019
+ onNotFound,
1020
+ onNotTranslatedResult
1021
+ });
1022
+ } else if (entityType === "entry" || entityType === "entryPattern") {
1023
+ return await mergeEntryTranslationToUniform({
1024
+ contentClient,
1025
+ translationPayload,
1026
+ updateEntry,
1027
+ onNotFound,
1028
+ onNotTranslatedResult
1029
+ });
1030
+ }
1031
+ return { translationMerged: false, entityId };
1032
+ };
1033
+ // Annotate the CommonJS export names for ESM import in node:
1034
+ 0 && (module.exports = {
1035
+ collectTranslationPayload,
1036
+ getCompositionForTranslation,
1037
+ getEntryForTranslation,
1038
+ mergeCompositionTranslationToUniform,
1039
+ mergeEntryTranslationToUniform,
1040
+ mergeTranslationToUniform,
1041
+ translateComposition,
1042
+ translateEntry
1043
+ });