diff --git a/server/src/functions/should-set-downloaded-property.ts b/server/src/functions/should-set-downloaded-property.ts index 18e20d1..01ae2e7 100644 --- a/server/src/functions/should-set-downloaded-property.ts +++ b/server/src/functions/should-set-downloaded-property.ts @@ -36,68 +36,85 @@ export enum ShouldSetDownloadedPropertyReturnType { JSON = 'json', } -export const shouldSetDownloadedProperty = ( +/** + * Locate the field a downloaded key belongs to, using the Content Transfer Setup. + * + * - `YES`: the key is a plain field enabled for transfer (the field is the key's last segment). + * - `JSON`: the key is one leaf of an enabled `json` or `blocks` field, which the upload flattens + * into one key per leaf; `fieldSegmentIndex` is the index in `parsedKeyRest` of the segment + * naming that field. Everything before it is the path to the entry or component owning the + * field (dynamic zone `id;component` segments and component ids included); everything after it + * is the leaf's path inside the field's value, e.g. for + * `beats[3;about.timeline].stops[10].notes[0].children[0].text` the field is `notes` (index 4) + * of stop 10 of timeline 3, and for `tags[0]` or `years.2024` it is `tags` / `years` (index 0). + * - `NO`: anything else (field disabled or unknown, component gone, model not set up). + */ +export const locateDownloadedField = ( modelContentTransferSetup: ModelContentTransferSetup, parsedKeyRest: string[] -): ShouldSetDownloadedPropertyReturnType => { +): { type: ShouldSetDownloadedPropertyReturnType; fieldSegmentIndex: number } => { + const notFound = { type: ShouldSetDownloadedPropertyReturnType.NO, fieldSegmentIndex: -1 }; if (!modelContentTransferSetup.__model__) { - return ShouldSetDownloadedPropertyReturnType.NO; + return notFound; } - if (hasDynamicZoneKeySegment(parsedKeyRest)) { - const dynamicZonePropertyName = getDynamicZonePropertyName(parsedKeyRest); - const componentName = getComponentNameFromDynamicZoneKeySegment(getDynamicZoneKeySegment(parsedKeyRest)); + let setupModel: unknown = modelContentTransferSetup; + let startIndex = 0; + if (hasDynamicZoneKeySegment(parsedKeyRest)) { + const dynamicZoneKeySegmentIndex = getDynamicZoneKeySegmentIndex(parsedKeyRest); + const componentName = getComponentNameFromDynamicZoneKeySegment(parsedKeyRest[dynamicZoneKeySegmentIndex]); const dzContentTransferSetupModel = get( modelContentTransferSetup, - dynamicZonePropertyName + getDynamicZonePropertyName(parsedKeyRest) ) as ModelContentTransferSetupDZFields[]; if (!Array.isArray(dzContentTransferSetupModel)) { - return ShouldSetDownloadedPropertyReturnType.NO; + return notFound; } - - const dzContentTransferSetupComponentModel = dzContentTransferSetupModel.find( - (c) => c.__component__ === componentName - ); - - if (!dzContentTransferSetupComponentModel) { - return ShouldSetDownloadedPropertyReturnType.NO; + setupModel = dzContentTransferSetupModel.find((c) => c.__component__ === componentName); + if (!setupModel) { + return notFound; } + startIndex = dynamicZoneKeySegmentIndex + 1; + } - const dynamicZoneKeySegmentIndex = getDynamicZoneKeySegmentIndex(parsedKeyRest); - const slicedParsedKeyRest = parsedKeyRest.slice(dynamicZoneKeySegmentIndex + 1); - const filteredSlicedParsedKeyRest = slicedParsedKeyRest.filter((segment) => isNaN(parseInt(segment))); - - if (get(dzContentTransferSetupComponentModel, filteredSlicedParsedKeyRest) === true) { - return ShouldSetDownloadedPropertyReturnType.YES; + // positions of the named (non-numeric) segments; numeric ones are array positions or component ids + const namedSegmentIndexes: number[] = []; + for (let index = startIndex; index < parsedKeyRest.length; index++) { + if (isNaN(parseInt(parsedKeyRest[index]))) { + namedSegmentIndexes.push(index); } + } - // json fields - while (filteredSlicedParsedKeyRest.length > 0) { - // last segment out - filteredSlicedParsedKeyRest.pop(); - if (get(dzContentTransferSetupComponentModel, filteredSlicedParsedKeyRest) === true) { - return ShouldSetDownloadedPropertyReturnType.JSON; - } + // the longest named path enabled in the setup is the field + for (let length = namedSegmentIndexes.length; length > 0; length--) { + const fieldPath = namedSegmentIndexes.slice(0, length).map((index) => parsedKeyRest[index]); + if (get(setupModel, fieldPath) === true) { + const fieldSegmentIndex = namedSegmentIndexes[length - 1]; + // anything after the field's own segment is a path inside a json/blocks value + const type = + fieldSegmentIndex === parsedKeyRest.length - 1 + ? ShouldSetDownloadedPropertyReturnType.YES + : ShouldSetDownloadedPropertyReturnType.JSON; + return { type, fieldSegmentIndex }; } + } - return ShouldSetDownloadedPropertyReturnType.NO; - } else { - const filteredParsedKeyRest = parsedKeyRest.filter((partialKey) => isNaN(parseInt(partialKey))); - - if (get(modelContentTransferSetup, filteredParsedKeyRest) === true) { - return ShouldSetDownloadedPropertyReturnType.YES; - } + return notFound; +}; - // json fields - while (filteredParsedKeyRest.length > 0) { - // last segment out - filteredParsedKeyRest.pop(); - if (get(modelContentTransferSetup, filteredParsedKeyRest) === true) { - return ShouldSetDownloadedPropertyReturnType.JSON; - } - } +export const shouldSetDownloadedProperty = ( + modelContentTransferSetup: ModelContentTransferSetup, + parsedKeyRest: string[] +): ShouldSetDownloadedPropertyReturnType => { + return locateDownloadedField(modelContentTransferSetup, parsedKeyRest).type; +}; - return ShouldSetDownloadedPropertyReturnType.NO; - } +/** Index of the `json`/`blocks` field's own segment in `parsedKeyRest`, or -1 (see `locateDownloadedField`). */ +export const getJsonFieldSegmentIndex = ( + modelContentTransferSetup: ModelContentTransferSetup, + parsedKeyRest: string[] +): number => { + const { type, fieldSegmentIndex } = locateDownloadedField(modelContentTransferSetup, parsedKeyRest); + return type === ShouldSetDownloadedPropertyReturnType.JSON ? fieldSegmentIndex : -1; }; diff --git a/server/src/services/localazy-transfer-download-service.ts b/server/src/services/localazy-transfer-download-service.ts index f1f685b..fe82342 100644 --- a/server/src/services/localazy-transfer-download-service.ts +++ b/server/src/services/localazy-transfer-download-service.ts @@ -1,11 +1,7 @@ -import { findSetupModelByCollectionUid } from '../utils/transfer-setup-utils'; import config from '../config'; import { isoLocalazyToStrapi } from '../utils/iso-locales-utils'; -import { - shouldSetDownloadedProperty, - ShouldSetDownloadedPropertyReturnType, -} from '../functions/should-set-downloaded-property'; -import { set, get, isEmpty } from 'lodash-es'; +import { collectDownloadedContent, DownloadedLocalazyKey } from '../utils/collect-downloaded-content'; +import { isEmpty } from 'lodash-es'; import RequestInitiatorHelper from '../utils/request-initiator-helper'; import PluginSettingsServiceHelper from '../services/helpers/plugin-settings-service-helper'; import { EventType } from '../constants/events'; @@ -22,7 +18,7 @@ import { getEntryExclusionService, getActivityLogsService, } from '../core'; -import { Language, Locales } from '@localazy/api-client'; +import { Locales } from '@localazy/api-client'; import { SyncCursor } from '../db/model/sync-cursor'; import { JobNotificationServiceType } from './helpers/job-notification-service'; @@ -282,15 +278,9 @@ const LocalazyTransferDownloadService = ({ strapi }: { strapi: Core.Strapi }) => /** * Parse Localazy content */ - type ParsedLocalazyContent = Record>>; - - const parsedLocalazyContent: ParsedLocalazyContent = {}; const strapiContentTypesModels = await StrapiService.getModels(); - const jsonFields = []; - - // Track which Localazy keys contribute to each Strapi entry: "isoStrapi:uid:documentId" → [{lang, id, event}] - const entryKeySourceMap: Record> = {}; + const languagesToParse: Array<{ isoStrapi: string; keys: DownloadedLocalazyKey[] }> = []; for (const [isoLocalazy, keys] of Object.entries(localazyContent)) { const isoStrapi = isoLocalazyToStrapi(isoLocalazy); if (!isoStrapi) { @@ -299,100 +289,17 @@ const LocalazyTransferDownloadService = ({ strapi }: { strapi: Core.Strapi }) => }); continue; } - - for (const localazyEntry of keys) { - const key = localazyEntry.key[0]; - const value = localazyEntry.value; - const localazyKeyId: string = localazyEntry.id; - const localazyKeyEvent: number | undefined = localazyEntry.event; - - // Skip keys already processed at the same or newer event for this language - const storedEvent = processedKeys[isoStrapi]?.[localazyKeyId]; - if (storedEvent !== undefined && localazyKeyEvent !== undefined && localazyKeyEvent <= storedEvent) { - continue; - } - - const parsedKey = StrapiI18nService.parseLocalazyKey(key); - - // Track source key for this entry - const entryKey = `${isoStrapi}:${parsedKey.uid}:${parsedKey.id}`; - if (!entryKeySourceMap[entryKey]) { - entryKeySourceMap[entryKey] = []; - } - entryKeySourceMap[entryKey].push({ lang: isoStrapi, id: localazyKeyId, event: localazyKeyEvent }); - - const modelContentTransferSetup = findSetupModelByCollectionUid( - contentTransferSetup, - strapiContentTypesModels, - parsedKey.uid - ); - - if (typeof modelContentTransferSetup !== 'undefined') { - const shouldSetDownloadedPropertyResult = shouldSetDownloadedProperty( - modelContentTransferSetup, - parsedKey.rest - ); - if (shouldSetDownloadedPropertyResult === ShouldSetDownloadedPropertyReturnType.NO) { - continue; - } - - let parsedKeyRestWithoutComponents = parsedKey.rest; - if (shouldSetDownloadedPropertyResult === ShouldSetDownloadedPropertyReturnType.JSON) { - const setKey = [isoStrapi, parsedKey.uid, parsedKey.id]; - - // handle dynamic zones and components here - let updatedParsedKeyRestWithoutComponents = parsedKeyRestWithoutComponents; - let segmentsToAdd = []; - for (const segment of parsedKeyRestWithoutComponents) { - const hasEntry = get(modelContentTransferSetup, [...segmentsToAdd, segment]); - const hasEntryNotFinal = hasEntry && typeof hasEntry !== 'boolean'; - // const isDZ = Array.isArray(hasEntry) && hasEntry.every((entry) => entry.__component__); - // processed till here in iterations and `segment` is numeric - const isComponent = parseInt(segment) > 0; - - if (hasEntryNotFinal || (!hasEntry && isComponent)) { - segmentsToAdd.push(segment); - setKey.push(segment); - updatedParsedKeyRestWithoutComponents = updatedParsedKeyRestWithoutComponents.slice(1); - } else { - break; - } - } - parsedKeyRestWithoutComponents = updatedParsedKeyRestWithoutComponents; - - let foundJsonFieldIndex = jsonFields.findIndex((jsonField) => { - return jsonField.setKey.join() === setKey.join(); - }); - if (foundJsonFieldIndex === -1) { - jsonFields.push({ - setKey, - jsonKey: parsedKeyRestWithoutComponents[0], - jsonValue: {}, - }); - } - - foundJsonFieldIndex = foundJsonFieldIndex === -1 ? jsonFields.length - 1 : foundJsonFieldIndex; - const foundJsonField = jsonFields[foundJsonFieldIndex]; - // rest from index 1 - const restSliced = parsedKeyRestWithoutComponents.slice(1); - set(foundJsonField, ['jsonValue', ...restSliced], value); - jsonFields[foundJsonFieldIndex] = foundJsonField; - } - - if (shouldSetDownloadedPropertyResult === ShouldSetDownloadedPropertyReturnType.YES) { - const setKey = [isoStrapi, parsedKey.uid, parsedKey.id, ...parsedKeyRestWithoutComponents]; - set(parsedLocalazyContent, setKey, value); - } - } - } + languagesToParse.push({ isoStrapi, keys }); } - /** - * Set json fields if applicable - */ - for (const jsonField of jsonFields) { - set(parsedLocalazyContent, [...jsonField.setKey, jsonField.jsonKey], jsonField.jsonValue); - } + // Track which Localazy keys contribute to each Strapi entry: "isoStrapi:uid:documentId" → [{lang, id, event}] + const { parsedLocalazyContent, entryKeySourceMap } = collectDownloadedContent({ + languages: languagesToParse, + processedKeys, + contentTransferSetup, + models: strapiContentTypesModels, + parseLocalazyKey: (key) => StrapiI18nService.parseLocalazyKey(key), + }); /** * Iterate over parsed Localazy content and insert/update content in Strapi diff --git a/server/src/services/strapi-i18n-service.ts b/server/src/services/strapi-i18n-service.ts index 582a2c9..41a5c78 100644 --- a/server/src/services/strapi-i18n-service.ts +++ b/server/src/services/strapi-i18n-service.ts @@ -2,6 +2,7 @@ import type { Core, UID, Modules } from '@strapi/strapi'; import { intlDisplayName } from '../utils/intl-display-name'; import { isoLocalazyToStrapi } from '../utils/iso-locales-utils.js'; import { omitDeep } from '../utils/omit-deep.js'; +import { parseLocalazyKey } from '../utils/parse-localazy-key'; // import { getStrapiService } from '../core'; import type { Locale } from '../models/strapi/locale'; // TODO: ADD TYPES @@ -36,14 +37,7 @@ const StrapiI18nService = ({ strapi }: { strapi: Core.Strapi }) => ({ } }, parseLocalazyKey(key: string) { - const split = key.split(/\.(?![^[]*])|\[|\]/); - const filteredSplit = split.filter((item) => item !== ''); - - return { - uid: `${filteredSplit[0]}.${filteredSplit[1]}`, - id: filteredSplit[2], - rest: filteredSplit.slice(3), - }; + return parseLocalazyKey(key); }, async getEntryInLocale( diff --git a/server/src/services/strapi-localazy-i18n-service.ts b/server/src/services/strapi-localazy-i18n-service.ts index 194b5d6..1f58c5a 100644 --- a/server/src/services/strapi-localazy-i18n-service.ts +++ b/server/src/services/strapi-localazy-i18n-service.ts @@ -1,9 +1,6 @@ -import { parsedLocalazyEntryToCreateEntry } from '../utils/parsed-localazy-entry-to-create-entry'; +import { buildLocalizedCreateEntry } from '../utils/build-localized-create-entry'; import { parsedLocalazyEntryToUpdateEntry } from '../utils/parsed-localazy-entry-to-update-entry'; -import { omitDeep } from '../utils/omit-deep'; -import { merge } from 'lodash-es'; import { Core, UID } from '@strapi/strapi'; -import { dropDocumentIdExceptMedia } from '../utils/drop-property-deep'; import { getStrapiI18nService /*, getStrapiService*/ } from '../core'; // TODO: ADD TYPES @@ -15,7 +12,7 @@ const StrapiLocalazyI18nService = ({ strapi }: { strapi: Core.Strapi }) => ({ // Strapi i18n Service const StrapiI18nService = getStrapiI18nService(); - const { createEntry } = parsedLocalazyEntryToCreateEntry( + const mergedCreateEntry = buildLocalizedCreateEntry( strapiContentTypesModels, translatedModel, baseEntry, @@ -23,22 +20,6 @@ const StrapiLocalazyI18nService = ({ strapi }: { strapi: Core.Strapi }) => ({ isoStrapi ); - const omitKeys = ['locale', 'localizations', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy', 'publishedAt']; - - let filteredBaseEntry = omitDeep(baseEntry, omitKeys); - // TODO: Deal with relations - must be omitted - // Drop documentId from all objects except media objects (images, files, etc.) - filteredBaseEntry = dropDocumentIdExceptMedia(filteredBaseEntry); - - /** - * Items positioning is done by the `toCreateEntry` function - * that's why can entry can be merged now - */ - let mergedCreateEntry: Record = {}; - merge(mergedCreateEntry, filteredBaseEntry, createEntry); - mergedCreateEntry = omitDeep(mergedCreateEntry, omitKeys); - - mergedCreateEntry.locale = isoStrapi; const createdEntry = await StrapiI18nService.createLocalizationForAnExistingEntry( uid, baseEntry, diff --git a/server/src/utils/__tests__/json-fields-download.test.ts b/server/src/utils/__tests__/json-fields-download.test.ts new file mode 100644 index 0000000..76ccae6 --- /dev/null +++ b/server/src/utils/__tests__/json-fields-download.test.ts @@ -0,0 +1,210 @@ +import { getJsonFieldSegmentIndex } from '../../functions/should-set-downloaded-property'; +import { collectDownloadedContent } from '../collect-downloaded-content'; +import { parseLocalazyKey } from '../parse-localazy-key'; +import { parsedLocalazyEntryToCreateEntry } from '../parsed-localazy-entry-to-create-entry'; + +/** + * Regression cover for downloading json/blocks fields that are not alone at the top level of an + * entry: two blocks fields in one component, and blocks inside components nested in a dynamic + * zone. Shapes mirror a real Strapi 5 "About" single type. + */ + +const uid = 'api::about.about'; +const documentId = 'zi29ijoosccc2qg7a1tr7h3j'; + +const paragraph = (...children: Record[]) => ({ type: 'paragraph', children }); +const text = (value: string, marks: Record = {}) => ({ type: 'text', text: value, ...marks }); + +const models = [ + { + uid, + collectionName: 'about', + attributes: { + beats: { type: 'dynamiczone', components: ['about.hero', 'about.timeline', 'about.today'] }, + }, + }, + { + uid: 'about.hero', + attributes: { chapter: { type: 'string' }, title: { type: 'blocks' }, line: { type: 'blocks' } }, + }, + { + uid: 'about.timeline', + attributes: { + title: { type: 'string' }, + stops: { type: 'component', repeatable: true, component: 'about.stop' }, + }, + }, + { + uid: 'about.stop', + attributes: { + label: { type: 'string' }, + notes: { type: 'blocks' }, + quote: { type: 'component', repeatable: false, component: 'about.quote' }, + }, + }, + { uid: 'about.quote', attributes: { text: { type: 'blocks' }, attribution: { type: 'string' } } }, + { + uid: 'about.today', + attributes: { + bridge: { type: 'blocks' }, + counter: { type: 'blocks' }, + work: { type: 'component', repeatable: false, component: 'about.side' }, + }, + }, + { uid: 'about.side', attributes: { lead: { type: 'string' }, text: { type: 'blocks' }, aside: { type: 'blocks' } } }, +]; + +// Content Transfer Setup as the plugin stores it for this model +const modelContentTransferSetup: any = { + __model__: true, + beats: [ + { __component__: 'about.hero', chapter: true, title: true, line: true }, + { + __component__: 'about.timeline', + title: true, + stops: { label: true, notes: true, quote: { text: true, attribution: true } }, + }, + { + __component__: 'about.today', + bridge: true, + counter: true, + work: { lead: true, text: true, aside: true }, + }, + ], +}; + +// Source-locale entry (Czech) as read by the download service, with DB ids +const baseEntry = { + documentId, + beats: [ + { + __component: 'about.hero', + id: 1, + chapter: 'Úvod', + title: [paragraph(text('Jsem obklopen přírodou. '), text('Ztrácím pojem o čase.', { bold: true }))], + line: [paragraph(text('Stav flow, který rád zažívám nejčastěji…'))], + }, + { + __component: 'about.timeline', + id: 3, + title: 'Komu za to vděčím?', + stops: [ + { id: 10, label: 'Děčín', notes: [paragraph(text('Odtud pocházím.'))] }, + { + id: 11, + label: 'První fotoaparát', + notes: [paragraph(text('Malý stříbrný Canon.'))], + quote: { id: 7, text: [paragraph(text('Máš hezký sloh.'))], attribution: 'Mamka' }, + }, + ], + }, + { + __component: 'about.today', + id: 2, + bridge: [paragraph(text('Je třeba udržet rovnováhu.'))], + counter: [paragraph(text('Práce mi umožňuje objevovat.'))], + work: { id: 4, lead: 'Práce', text: [paragraph(text('Bavím se logikou.'))], aside: [paragraph(text('V týmu.'))] }, + }, + ], +}; + +// Downloaded English keys, in the order the upload produced them +const downloadedKeys: Record = { + 'beats[1;about.hero].chapter': 'Introduction', + 'beats[1;about.hero].title[0].children[0].text': "I'm surrounded by nature. ", + 'beats[1;about.hero].title[0].children[1].text': 'I lose track of time.', + 'beats[1;about.hero].line[0].children[0].text': 'That flow state I love slipping into…', + 'beats[3;about.timeline].title': 'Who do I owe it to?', + 'beats[3;about.timeline].stops[10].label': 'Děčín', + 'beats[3;about.timeline].stops[10].notes[0].children[0].text': 'This is where I come from.', + 'beats[3;about.timeline].stops[11].label': 'My first camera', + 'beats[3;about.timeline].stops[11].notes[0].children[0].text': 'A small silver Canon.', + 'beats[3;about.timeline].stops[11].quote[7].text[0].children[0].text': 'You have a nice way with words.', + 'beats[3;about.timeline].stops[11].quote[7].attribution': 'Mum', + 'beats[2;about.today].bridge[0].children[0].text': 'It is about balance.', + 'beats[2;about.today].counter[0].children[0].text': 'My work lets me explore.', + 'beats[2;about.today].work[4].lead': 'Work', + 'beats[2;about.today].work[4].text[0].children[0].text': 'I enjoy logic.', + 'beats[2;about.today].work[4].aside[0].children[0].text': 'In the team.', +}; + +// the part of a key after the document id, as the download parses it +const parseRest = (key: string) => parseLocalazyKey(`${uid}[${documentId}].${key}`).rest; + +const buildParsedContent = (keys: Record) => + collectDownloadedContent({ + languages: [ + { + isoStrapi: 'en', + keys: Object.entries(keys).map(([key, value], index) => ({ + id: `k${index}`, + key: [`${uid}[${documentId}].${key}`], + value, + })), + }, + ], + processedKeys: {}, + contentTransferSetup: { has_setup: true, setup: [{ about: modelContentTransferSetup }] }, + models, + parseLocalazyKey, + }).parsedLocalazyContent; + +describe('getJsonFieldSegmentIndex', () => { + it.each([ + ['beats[1;about.hero].title[0].children[0].text', 2], + ['beats[1;about.hero].line[0].children[0].text', 2], + ['beats[3;about.timeline].stops[10].notes[0].children[0].text', 4], + ['beats[3;about.timeline].stops[11].quote[7].text[0].children[0].text', 6], + ['beats[2;about.today].work[4].aside[0].children[0].text', 4], + ])('finds the field segment of %s', (key, expected) => { + expect(getJsonFieldSegmentIndex(modelContentTransferSetup, parseRest(key))).toBe(expected); + }); + + it('handles json fields outside dynamic zones, including inside components', () => { + const setup: any = { __model__: true, meta: true, seo: { structuredData: true } }; + expect(getJsonFieldSegmentIndex(setup, parseRest('meta.author.name'))).toBe(0); + expect(getJsonFieldSegmentIndex(setup, parseRest('seo[5].structuredData.items[0].label'))).toBe(2); + }); + + it('returns -1 for plain fields, disabled fields and unknown components', () => { + expect(getJsonFieldSegmentIndex(modelContentTransferSetup, parseRest('beats[1;about.hero].chapter'))).toBe(-1); + expect(getJsonFieldSegmentIndex(modelContentTransferSetup, parseRest('beats[9;about.gone].x[0].text'))).toBe(-1); + }); +}); + +describe('downloading json/blocks fields next to each other and inside nested components', () => { + const parsed = buildParsedContent(downloadedKeys); + const { createEntry } = parsedLocalazyEntryToCreateEntry(models, parsed['en'][uid][documentId], baseEntry, uid, 'en'); + const [hero, timeline, today] = createEntry.beats; + + it('keeps two blocks fields of one component apart', () => { + expect(hero.title).toEqual([ + paragraph(text("I'm surrounded by nature. "), text('I lose track of time.', { bold: true })), + ]); + expect(today.bridge).toEqual([paragraph(text('It is about balance.'))]); + expect(today.counter).toEqual([paragraph(text('My work lets me explore.'))]); + }); + + it('translates the second blocks field instead of leaving it in the source language', () => { + expect(hero.line).toEqual([paragraph(text('That flow state I love slipping into…'))]); + }); + + it('writes blocks inside repeatable components nested in a dynamic zone, keeping their siblings', () => { + expect(timeline.title).toBe('Who do I owe it to?'); + expect(timeline.stops).toHaveLength(2); + expect(timeline.stops[0]).toMatchObject({ label: 'Děčín', notes: [paragraph(text('This is where I come from.'))] }); + expect(timeline.stops[1]).toMatchObject({ + label: 'My first camera', + notes: [paragraph(text('A small silver Canon.'))], + quote: { text: [paragraph(text('You have a nice way with words.'))], attribution: 'Mum' }, + }); + }); + + it('writes blocks inside single components nested in a dynamic zone', () => { + expect(today.work).toMatchObject({ + lead: 'Work', + text: [paragraph(text('I enjoy logic.'))], + aside: [paragraph(text('In the team.'))], + }); + }); +}); diff --git a/server/src/utils/__tests__/overlay-json-translation.test.ts b/server/src/utils/__tests__/overlay-json-translation.test.ts new file mode 100644 index 0000000..545d303 --- /dev/null +++ b/server/src/utils/__tests__/overlay-json-translation.test.ts @@ -0,0 +1,83 @@ +import { set } from 'lodash-es'; +import { flattenObject } from '../flatten-object'; +import { parseLocalazyKey } from '../parse-localazy-key'; +import { overlayJsonTranslation } from '../overlay-json-translation'; +import { + locateDownloadedField, + ShouldSetDownloadedPropertyReturnType, +} from '../../functions/should-set-downloaded-property'; + +/** Upload a json value the way the plugin does, translate every string, and rebuild it. */ +const roundTrip = (source: any, translate: (text: string) => string) => { + const flat = flattenObject({ 'api::x.x': { documentId: 'doc', data: source } }); + const translated: any = {}; + for (const [key, value] of Object.entries(flat)) { + const { rest } = parseLocalazyKey(key); + // rest[0] is the field (`data`); the leaf path inside the value follows + set(translated, rest.slice(1), typeof value === 'string' ? translate(value) : value); + } + return overlayJsonTranslation(source, translated); +}; + +const EN = (text: string) => `EN ${text}`; + +describe('overlayJsonTranslation', () => { + it.each([ + ['a nested object', { og: { title: 'Titulek' }, count: 3, active: true, none: null }], + ['numeric keys', { years: { '2024': 'Rok cest', '2025': 'Rok doma' } }], + ['objects with ids', { author: { id: 7, name: 'Autor' } }], + ['array items with ids', [{ id: 5, label: 'Instagram' }, { label: 'Kontakt' }, { documentId: 'x1', label: 'Web' }]], + ['a top-level array of strings', ['příroda', 'fotografie']], + ['nested arrays', { matrix: [['a', 'b'], ['c']] }], + ['an object with its own id', { id: 9, title: 'Titulek', items: [{ text: 'Položka' }] }], + ])('rebuilds %s with the same shape and every string translated', (_, source) => { + const expected = JSON.parse( + JSON.stringify(source, (key, value) => + typeof value === 'string' && !['documentId'].includes(key) ? EN(value) : value + ) + ); + expect(roundTrip(source, EN)).toEqual(expected); + }); + + it('keeps the source text for untranslated leaves and ignores leaves no longer in the source', () => { + const source = { og: { title: 'Titulek', description: 'Popis' }, links: [{ label: 'A' }] }; + const translated = { + og: { title: 'Title', removed: 'X' }, + links: { '0': { label: 'A2' }, '3': { label: 'gone' } }, + }; + + expect(overlayJsonTranslation(source, translated)).toEqual({ + og: { title: 'Title', description: 'Popis' }, + links: [{ label: 'A2' }], + }); + }); + + it('returns undefined without a source value, and never translates non-strings', () => { + expect(overlayJsonTranslation(undefined, { a: 'x' })).toBeUndefined(); + expect(overlayJsonTranslation(null, { a: 'x' })).toBeUndefined(); + expect(overlayJsonTranslation({ n: 1, b: false }, { n: '2', b: 'true' })).toEqual({ n: 1, b: false }); + }); +}); + +describe('locateDownloadedField', () => { + const setup: any = { __model__: true, title: true, tags: true, meta: true, seo: { data: true, title: true } }; + const rest = (key: string) => parseLocalazyKey(`api::x.x[doc].${key}`).rest; + + it.each([ + ['title', ShouldSetDownloadedPropertyReturnType.YES, 0], + ['seo[3].title', ShouldSetDownloadedPropertyReturnType.YES, 2], + ['tags[0]', ShouldSetDownloadedPropertyReturnType.JSON, 0], + ['meta.years.2024', ShouldSetDownloadedPropertyReturnType.JSON, 0], + ['meta.author[7].name', ShouldSetDownloadedPropertyReturnType.JSON, 0], + ['seo[3].data.items[0].label', ShouldSetDownloadedPropertyReturnType.JSON, 2], + ['unknown', ShouldSetDownloadedPropertyReturnType.NO, -1], + ])('%s → %s', (key, type, fieldSegmentIndex) => { + expect(locateDownloadedField(setup, rest(key))).toEqual({ type, fieldSegmentIndex }); + }); + + it('finds nothing for a model without setup', () => { + expect(locateDownloadedField({ __model__: false } as any, rest('title')).type).toBe( + ShouldSetDownloadedPropertyReturnType.NO + ); + }); +}); diff --git a/server/src/utils/__tests__/populate-create-update-entry-with-base-entry.test.ts b/server/src/utils/__tests__/populate-create-update-entry-with-base-entry.test.ts new file mode 100644 index 0000000..72e64c0 --- /dev/null +++ b/server/src/utils/__tests__/populate-create-update-entry-with-base-entry.test.ts @@ -0,0 +1,73 @@ +import { populateCreateUpdateEntryWithBaseEntry } from '../populate-create-update-entry-with-base-entry'; + +/** + * Relations are resolved asynchronously (one document lookup each). The ones inside dynamic zone + * items and repeatable components must be resolved before the populated entry is returned, or + * they are written into the update payload while Strapi is already processing it. + */ + +const uid = 'api::about.about'; + +const models = [ + { uid, attributes: { beats: { type: 'dynamiczone', components: ['about.timeline'] } } }, + { + uid: 'about.timeline', + attributes: { + title: { type: 'string' }, + stops: { type: 'component', repeatable: true, component: 'about.stop' }, + }, + }, + { + uid: 'about.stop', + attributes: { + label: { type: 'string' }, + glyph: { type: 'relation', relation: 'oneToOne', target: 'api::glyph.glyph' }, + }, + }, +]; + +const baseEntry = { + beats: [ + { + __component: 'about.timeline', + id: 3, + title: 'Má cesta', + stops: [ + { id: 10, label: 'Děčín', glyph: { id: 1, documentId: 'glyph-river' } }, + { id: 11, label: 'Krkonoše', glyph: { id: 2, documentId: 'glyph-mountain' } }, + ], + }, + ], +}; + +const updateEntry = { + beats: [ + { + __component: 'about.timeline', + title: 'My Journey', + stops: [{ label: 'Děčín' }, { label: 'Krkonoše Mountains' }], + }, + ], +}; + +describe('populateCreateUpdateEntryWithBaseEntry', () => { + const originalDocuments = (global as any).strapi.documents; + + beforeEach(() => { + (global as any).strapi.documents = jest.fn(() => ({ + // resolve on a later tick, like a database lookup + findOne: jest.fn(({ documentId }) => new Promise((resolve) => setTimeout(() => resolve({ documentId }), 5))), + })); + }); + + afterEach(() => { + (global as any).strapi.documents = originalDocuments; + }); + + it('resolves relations inside repeatable components of dynamic zone items before returning', async () => { + const populated = await populateCreateUpdateEntryWithBaseEntry(models, updateEntry, baseEntry, {}, uid, 'en'); + + expect(populated.beats[0].stops[0]).toMatchObject({ label: 'Děčín', glyph: ['glyph-river'] }); + expect(populated.beats[0].stops[1]).toMatchObject({ label: 'Krkonoše Mountains', glyph: ['glyph-mountain'] }); + }); +}); diff --git a/server/src/utils/__tests__/transfer-round-trip.test.ts b/server/src/utils/__tests__/transfer-round-trip.test.ts new file mode 100644 index 0000000..8b89cd1 --- /dev/null +++ b/server/src/utils/__tests__/transfer-round-trip.test.ts @@ -0,0 +1,520 @@ +import { cloneDeep, isPlainObject } from 'lodash-es'; +import { projectBlocksFields } from '../blocks-to-translatable'; +import { flattenObject } from '../flatten-object'; +import { pickEntries } from '../pick-entries'; +import { getPickPathsWithComponents } from '../transfer-setup-utils'; +import { collectDownloadedContent, DownloadedLocalazyKey } from '../collect-downloaded-content'; +import { buildLocalizedCreateEntry } from '../build-localized-create-entry'; +import { parsedLocalazyEntryToUpdateEntry } from '../parsed-localazy-entry-to-update-entry'; +import { parseLocalazyKey } from '../parse-localazy-key'; + +/** + * Upload → translate → download round trip through the plugin's own transforms, for a schema + * that puts json and blocks fields everywhere Strapi allows them: top level (two side by side), + * single and repeatable components, components nested in components, dynamic zones, and + * repeatable components nested in dynamic zone items. The expected result comes from an + * independent walk over the schema (`translateBySetup`), not from the plugin code. + */ + +const uid = 'api::page.page'; +const documentId = 'page-doc-1'; + +// --------------------------------------------------------------------------------------------- +// Schema, Content Transfer Setup and source entry +// --------------------------------------------------------------------------------------------- + +const models: any[] = [ + { + uid, + collectionName: 'pages', + pluginOptions: { i18n: { localized: true } }, + attributes: { + slug: { type: 'uid' }, + title: { type: 'string' }, + intro: { type: 'blocks' }, + body: { type: 'blocks' }, + meta: { type: 'json' }, + links: { type: 'json' }, + tags: { type: 'json' }, + seo: { type: 'component', repeatable: false, component: 'shared.seo' }, + faqs: { type: 'component', repeatable: true, component: 'shared.faq' }, + sections: { + type: 'dynamiczone', + components: ['sections.hero', 'sections.timeline', 'sections.gallery'], + }, + }, + }, + { uid: 'shared.seo', attributes: { metaTitle: { type: 'string' }, summary: { type: 'blocks' } } }, + { + uid: 'shared.faq', + attributes: { + question: { type: 'string' }, + answer: { type: 'blocks' }, + note: { type: 'component', repeatable: false, component: 'shared.note' }, + }, + }, + { uid: 'shared.note', attributes: { text: { type: 'blocks' }, author: { type: 'string' } } }, + { + uid: 'sections.hero', + attributes: { eyebrow: { type: 'string' }, heading: { type: 'blocks' }, line: { type: 'blocks' } }, + }, + { + uid: 'sections.timeline', + attributes: { + title: { type: 'string' }, + stops: { type: 'component', repeatable: true, component: 'sections.stop' }, + }, + }, + { + uid: 'sections.stop', + attributes: { + label: { type: 'string' }, + notes: { type: 'blocks' }, + quote: { type: 'component', repeatable: false, component: 'sections.quote' }, + glyph: { type: 'relation', relation: 'oneToOne', target: 'api::glyph.glyph' }, + }, + }, + { uid: 'sections.quote', attributes: { text: { type: 'blocks' }, attribution: { type: 'string' } } }, + { + uid: 'sections.gallery', + attributes: { items: { type: 'component', repeatable: true, component: 'sections.item' } }, + }, + { uid: 'sections.item', attributes: { caption: { type: 'string' }, alt: { type: 'string' } } }, +]; + +const setupModel: any = { + __model__: true, + slug: null, + title: true, + intro: true, + body: true, + meta: true, + links: true, + tags: true, + seo: { metaTitle: true, summary: true }, + faqs: { question: true, answer: true, note: { text: true, author: true } }, + sections: [ + { __component__: 'sections.hero', eyebrow: true, heading: true, line: true }, + { + __component__: 'sections.timeline', + title: true, + stops: { label: true, notes: true, quote: { text: true, attribution: true }, glyph: null }, + }, + { __component__: 'sections.gallery', items: { caption: true, alt: true } }, + ], +}; +const contentTransferSetup = { has_setup: true, setup: [{ pages: setupModel }] }; + +const t = (type: string, text: string, marks: Record = {}) => ({ type, text, ...marks }); +const p = (...children: any[]) => ({ type: 'paragraph', children }); + +const buildSourceEntry = () => ({ + documentId, + locale: 'cs', + slug: 'o-mne', + title: 'O mně', + intro: [ + { type: 'heading', level: 2, children: [t('text', 'Nadpis úvodu')] }, + p(t('text', 'Jsem obklopen přírodou. '), t('text', 'Ztrácím pojem o čase.', { bold: true })), + p(t('text', 'Druhý odstavec.')), + ], + body: [ + p( + t('text', 'Více na '), + { type: 'link', url: 'https://localazy.com', children: [t('text', 'Localazy')] }, + t('text', ' a jinde.') + ), + { + type: 'list', + format: 'unordered', + children: [ + { type: 'list-item', children: [t('text', 'První bod')] }, + { type: 'list-item', children: [t('text', 'Druhý bod', { italic: true })] }, + ], + }, + { type: 'quote', children: [t('text', 'Citát v těle.')] }, + { type: 'image', image: { url: '/uploads/a.jpg', alternativeText: 'a' }, children: [t('text', '')] }, + ], + meta: { + keywords: ['příroda', 'fotografie'], + og: { title: 'Sdílený titulek' }, + years: { '2024': 'Rok cest', '2025': 'Rok doma' }, // numeric keys stay object keys + author: { id: 7, name: 'Autor', active: true }, // flattened as `author[7].name` + count: 3, + }, + links: [{ id: 5, label: 'Instagram', url: 'https://instagram.com' }, { label: 'Kontakt' }], // `links[5]`, `links[1]` + tags: ['příroda', 'fotografie'], + seo: { id: 91, metaTitle: 'O mně | Web', summary: [p(t('text', 'Shrnutí stránky.'))] }, + faqs: [ + { + id: 31, + question: 'Proč?', + answer: [p(t('text', 'Protože '), t('text', 'chci.', { bold: true }))], + note: { id: 51, text: [p(t('text', 'Poznámka k otázce.'))], author: 'Autor' }, + }, + { id: 32, question: 'Kdy?', answer: [p(t('text', 'Brzy.'))] }, + ], + sections: [ + { + __component: 'sections.hero', + id: 7, + eyebrow: 'Úvod', + heading: [p(t('text', 'Jsem obklopen přírodou. '), t('text', 'Ztrácím pojem o čase.', { bold: true }))], + line: [p(t('text', 'Stav flow, který rád zažívám…'))], + }, + { + __component: 'sections.timeline', + id: 3, + title: 'Má cesta', + stops: [ + { id: 10, label: 'Děčín', notes: [p(t('text', 'Odtud pocházím.'))], glyph: { id: 1, documentId: 'g-river' } }, + { + id: 11, + label: 'První fotoaparát', + notes: [p(t('text', 'Malý stříbrný Canon.')), p(t('text', 'Druhý odstavec poznámek.'))], + quote: { id: 70, text: [p(t('text', 'Máš hezký sloh.'))], attribution: 'Mamka' }, + glyph: { id: 2, documentId: 'g-camera' }, + }, + { id: 12, label: 'Krkonoše', notes: [p(t('text', 'Sem mě brávala babička.'))], glyph: null }, + ], + }, + { + __component: 'sections.gallery', + id: 4, + items: [ + { id: 20, caption: 'První fotka', alt: 'popis 1' }, + { id: 21, caption: '', alt: '' }, // nothing to translate in this item + { id: 22, caption: 'Třetí fotka', alt: 'popis 3' }, + ], + }, + ], +}); + +// --------------------------------------------------------------------------------------------- +// Independent oracle: translate every string the setup enables, walking the schema +// --------------------------------------------------------------------------------------------- + +const getModel = (modelUid: string) => models.find((model) => model.uid === modelUid); + +const mapStrings = (value: any, fn: (text: string) => string): any => { + if (typeof value === 'string') return value ? fn(value) : value; + if (Array.isArray(value)) return value.map((item) => mapStrings(item, fn)); + if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, mapStrings(v, fn)])); + return value; +}; + +const mapBlocksText = (nodes: any[], fn: (text: string) => string): any[] => + nodes.map((node) => { + const mapped = { ...node }; + if (typeof node.text === 'string' && node.text) mapped.text = fn(node.text); + if (Array.isArray(node.children)) mapped.children = mapBlocksText(node.children, fn); + return mapped; + }); + +const translateBySetup = (value: any, model: any, setup: any, fn: (text: string) => string): any => { + if (!value) return value; + const result = { ...value }; + for (const [name, attribute] of Object.entries(model.attributes)) { + const fieldSetup = setup?.[name]; + const fieldValue = value[name]; + if (!fieldSetup || fieldValue === undefined || fieldValue === null) continue; + if (attribute.type === 'blocks') result[name] = mapBlocksText(fieldValue, fn); + else if (attribute.type === 'json') result[name] = mapStrings(fieldValue, fn); + else if (attribute.type === 'component') { + const componentModel = getModel(attribute.component); + result[name] = attribute.repeatable + ? fieldValue.map((item) => translateBySetup(item, componentModel, fieldSetup, fn)) + : translateBySetup(fieldValue, componentModel, fieldSetup, fn); + } else if (attribute.type === 'dynamiczone') { + result[name] = fieldValue.map((item) => + translateBySetup( + item, + getModel(item.__component), + fieldSetup.find((c) => c.__component__ === item.__component), + fn + ) + ); + } else if (fieldSetup === true && typeof fieldValue === 'string') { + result[name] = fieldValue ? fn(fieldValue) : fieldValue; + } + } + return result; +}; + +const IGNORED_KEYS = ['id', 'documentId', 'locale', 'localizations', 'glyph', '__component', 'publishedAt']; +const normalize = (value: any): any => { + if (Array.isArray(value)) return value.map(normalize); + if (isPlainObject(value)) { + return Object.fromEntries( + Object.entries(value) + .filter(([key]) => !IGNORED_KEYS.includes(key)) + .map(([key, v]) => [key, normalize(v)]) + ); + } + return value; +}; + +// --------------------------------------------------------------------------------------------- +// Pipeline: the plugin's upload transforms, a fake Localazy, the plugin's download transforms +// --------------------------------------------------------------------------------------------- + +const upload = (sourceEntry: any): Record => { + const projected = projectBlocksFields(sourceEntry, getModel(uid), getModel); + const flat = flattenObject({ [uid]: projected }); + const pickPaths = getPickPathsWithComponents(setupModel).map((path) => `${uid}.${path}`); + const picked = pickEntries(flat, pickPaths); + // Localazy stores no empty source strings + return Object.fromEntries(Object.entries(picked).filter(([, v]) => typeof v === 'string' && v !== '')) as any; +}; + +const toLocalazyKeys = (uploaded: Record, translate: (key: string, value: string) => string) => + Object.entries(uploaded).map( + ([key, value], index): DownloadedLocalazyKey => ({ + id: `k${index}:${key}`, + key: [key], + value: translate(key, value), + }) + ); + +const download = (keys: DownloadedLocalazyKey[], processedKeys: Record> = {}) => + collectDownloadedContent({ + languages: [{ isoStrapi: 'en', keys }], + processedKeys, + contentTransferSetup, + models, + parseLocalazyKey, + }); + +const EN = (text: string) => `[en] ${text}`; + +// The localized entry as Strapi stores it: same structure, its own component ids +const reId = (value: any, offset = 1000): any => { + if (Array.isArray(value)) return value.map((item) => reId(item, offset)); + if (isPlainObject(value)) { + const result = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, reId(v, offset)])); + if (typeof value.id === 'number' && !value.documentId) result.id = value.id + offset; + return result; + } + return value; +}; + +const update = async (translatedModel: any, currentEntry: any, sourceEntry: any) => + parsedLocalazyEntryToUpdateEntry(models, translatedModel, currentEntry, currentEntry, sourceEntry, uid, 'en'); + +describe('transfer round trip (upload → translate → download)', () => { + const originalDocuments = (global as any).strapi.documents; + + beforeEach(() => { + // relation lookups resolve on a later tick, like the database + (global as any).strapi.documents = jest.fn(() => ({ + findOne: jest.fn( + ({ documentId: id }) => new Promise((resolve) => setTimeout(() => resolve({ documentId: id }), 2)) + ), + })); + }); + + afterEach(() => { + (global as any).strapi.documents = originalDocuments; + }); + + it('uploads exactly one key per translatable leaf, wherever the field lives', () => { + const keys = Object.keys(upload(buildSourceEntry())); + expect(keys).toEqual( + expect.arrayContaining([ + `${uid}[${documentId}].intro[1].children[1].text`, + `${uid}[${documentId}].body[0].children[1].children[0].text`, + `${uid}[${documentId}].meta.og.title`, + `${uid}[${documentId}].seo[91].summary[0].children[0].text`, + `${uid}[${documentId}].faqs[31].note[51].text[0].children[0].text`, + `${uid}[${documentId}].sections[7;sections.hero].line[0].children[0].text`, + `${uid}[${documentId}].sections[3;sections.timeline].stops[11].quote[70].text[0].children[0].text`, + `${uid}[${documentId}].sections[4;sections.gallery].items[22].alt`, + ]) + ); + expect(keys.some((key) => key.includes('.slug'))).toBe(false); + expect(keys.some((key) => key.includes('items[21]'))).toBe(false); + }); + + it('creates a localization with every leaf translated in place and the structure untouched', () => { + const source = buildSourceEntry(); + const { parsedLocalazyContent } = download(toLocalazyKeys(upload(source), (_, value) => EN(value))); + + const created = buildLocalizedCreateEntry(models, parsedLocalazyContent.en[uid][documentId], source, uid, 'en'); + + expect(normalize(created)).toEqual(normalize(translateBySetup(source, getModel(uid), setupModel, EN))); + expect(created.sections.map((s) => s.__component)).toEqual(source.sections.map((s) => s.__component)); + }); + + it('updates an existing localization to the same result, keeping relations', async () => { + const source = buildSourceEntry(); + const expected = translateBySetup(source, getModel(uid), setupModel, EN); + const current = reId(cloneDeep(expected)); + const { parsedLocalazyContent } = download(toLocalazyKeys(upload(source), (_, value) => EN(value))); + + const updated = await update(parsedLocalazyContent.en[uid][documentId], current, source); + + expect(normalize(updated)).toEqual(normalize(expected)); + expect(updated.sections[1].stops.map((stop) => stop.glyph)).toEqual([['g-river'], ['g-camera'], null]); + }); + + it('incremental: rewrites only what changed, keeping every other translation and item in place', async () => { + const source = buildSourceEntry(); + const expected = translateBySetup(source, getModel(uid), setupModel, EN); + const current = reId(cloneDeep(expected)); + + const changedKeys = [ + `${uid}[${documentId}].sections[3;sections.timeline].stops[11].notes[1].children[0].text`, + `${uid}[${documentId}].sections[3;sections.timeline].stops[12].label`, + `${uid}[${documentId}].sections[4;sections.gallery].items[22].caption`, + `${uid}[${documentId}].intro[1].children[0].text`, + ]; + const keys = toLocalazyKeys(upload(source), (key, value) => + changedKeys.includes(key) ? `[en v2] ${value}` : EN(value) + ); + // everything was downloaded before at event 1; the changed keys are at event 2 now + const processedKeys = { en: Object.fromEntries(keys.map((key) => [key.id, 1])) }; + keys.forEach((key) => (key.event = changedKeys.includes(key.key[0]) ? 2 : 1)); + + const { parsedLocalazyContent } = download(keys, processedKeys); + const updated = await update(parsedLocalazyContent.en[uid][documentId], current, source); + + const v2 = cloneDeep(expected); + v2.sections[1].stops[1].notes[1].children[0].text = '[en v2] Druhý odstavec poznámek.'; + v2.sections[1].stops[2].label = '[en v2] Krkonoše'; + v2.sections[2].items[2].caption = '[en v2] Třetí fotka'; + v2.intro[1].children[0].text = '[en v2] Jsem obklopen přírodou. '; + expect(normalize(updated)).toEqual(normalize(v2)); + }); + + it('keeps languages apart when several are downloaded at once', () => { + const source = buildSourceEntry(); + const uploaded = upload(source); + const PL = (text: string) => `[pl] ${text}`; + const { parsedLocalazyContent } = collectDownloadedContent({ + languages: [ + { isoStrapi: 'en', keys: toLocalazyKeys(uploaded, (_, value) => EN(value)) }, + { isoStrapi: 'pl', keys: toLocalazyKeys(uploaded, (_, value) => PL(value)) }, + ], + processedKeys: {}, + contentTransferSetup, + models, + parseLocalazyKey, + }); + + for (const [iso, fn] of [ + ['en', EN], + ['pl', PL], + ] as const) { + const created = buildLocalizedCreateEntry(models, parsedLocalazyContent[iso][uid][documentId], source, uid, iso); + expect(normalize(created)).toEqual(normalize(translateBySetup(source, getModel(uid), setupModel, fn))); + } + }); + + it('incremental: an untouched entry is not rewritten at all', () => { + const source = buildSourceEntry(); + const keys = toLocalazyKeys(upload(source), (_, value) => EN(value)).map((key) => ({ ...key, event: 1 })); + const processedKeys = { en: Object.fromEntries(keys.map((key) => [key.id, 1])) }; + + const { parsedLocalazyContent, entryKeySourceMap } = download(keys, processedKeys); + + expect(parsedLocalazyContent).toEqual({}); + expect(entryKeySourceMap).toEqual({}); + }); + + it('follows source structure changes (marks, removed paragraphs) when updating', async () => { + const before = buildSourceEntry(); + const current = reId(translateBySetup(before, getModel(uid), setupModel, EN)); + + const source = buildSourceEntry(); + delete (source.intro[1].children[1] as any).bold; // bold dropped in the source + source.intro.pop(); // last paragraph deleted in the source + source.sections[1].stops[1].notes.pop(); // a paragraph deleted inside a nested component + + const { parsedLocalazyContent } = download(toLocalazyKeys(upload(source), (_, value) => EN(value))); + const updated = await update(parsedLocalazyContent.en[uid][documentId], current, source); + + expect(normalize(updated)).toEqual(normalize(translateBySetup(source, getModel(uid), setupModel, EN))); + }); + + it('ignores keys still active in Localazy for content removed from the source', () => { + const source = buildSourceEntry(); + const uploaded = upload(source); + const stale = { + [`${uid}[${documentId}].links[9].label`]: 'Odstraněný odkaz', + [`${uid}[${documentId}].meta.og.description`]: 'Odstraněný popis', + [`${uid}[${documentId}].intro[7].children[0].text`]: 'Odstraněný odstavec', + [`${uid}[${documentId}].sections[3;sections.timeline].stops[99].label`]: 'Odstraněná zastávka', + [`${uid}[${documentId}].sections[42;sections.hero].eyebrow`]: 'Odstraněná sekce', + }; + const { parsedLocalazyContent } = download(toLocalazyKeys({ ...uploaded, ...stale }, (_, value) => EN(value))); + + const created = buildLocalizedCreateEntry(models, parsedLocalazyContent.en[uid][documentId], source, uid, 'en'); + + expect(normalize(created)).toEqual(normalize(translateBySetup(source, getModel(uid), setupModel, EN))); + }); + + it('rebuilds lists whose layout changed in the source (dynamic zone item removed, stop inserted)', async () => { + const before = buildSourceEntry(); + const current = reId(translateBySetup(before, getModel(uid), setupModel, EN)); + + const source = buildSourceEntry(); + source.sections.shift(); // the hero is removed: the timeline is now first + source.sections[0].stops.splice(1, 0, { + id: 13, + label: 'Nová zastávka', + notes: [p(t('text', 'Vložená poznámka.'))], + glyph: { id: 3, documentId: 'g-new' }, + } as any); + + const { parsedLocalazyContent } = download(toLocalazyKeys(upload(source), (_, value) => EN(value))); + const updated = await update(parsedLocalazyContent.en[uid][documentId], current, source); + + expect(normalize(updated)).toEqual(normalize(translateBySetup(source, getModel(uid), setupModel, EN))); + expect(updated.sections.map((s) => s.__component)).toEqual(['sections.timeline', 'sections.gallery']); + // rebuilt items are new components: no ids of the source locale's components + expect(updated.sections.every((s) => s.id === undefined)).toBe(true); + expect(updated.sections[0].stops.map((stop) => stop.glyph)).toEqual([['g-river'], ['g-new'], ['g-camera'], null]); + }); + + it('incremental after a reorder in the source: every stop gets its own translation', async () => { + const before = buildSourceEntry(); + const current = reId(translateBySetup(before, getModel(uid), setupModel, EN)); + + const source = buildSourceEntry(); + const [river, camera, mountains] = source.sections[1].stops; + source.sections[1].stops = [mountains, river, camera]; + + // only the river stop's label changed since the last download + const changedKey = `${uid}[${documentId}].sections[3;sections.timeline].stops[10].label`; + const keys = toLocalazyKeys(upload(source), (key, value) => (key === changedKey ? `[en v2] ${value}` : EN(value))); + const processedKeys = { en: Object.fromEntries(keys.map((key) => [key.id, 1])) }; + keys.forEach((key) => (key.event = key.key[0] === changedKey ? 2 : 1)); + + const { parsedLocalazyContent } = download(keys, processedKeys); + const updated = await update(parsedLocalazyContent.en[uid][documentId], current, source); + + const stops = updated.sections[1].stops; + expect(stops.map((stop) => stop.label)).toEqual(['[en] Krkonoše', '[en v2] Děčín', '[en] První fotoaparát']); + expect(stops.map((stop) => normalize(stop.notes))).toEqual( + [mountains, river, camera].map((stop) => normalize(mapBlocksText(stop.notes, EN))) + ); + // relations set in the source follow the source; a stop without one keeps whatever its localized + // slot had (the plugin never clears localized relations), as a same-length reorder is undetectable + expect(stops.slice(1).map((stop) => stop.glyph)).toEqual([['g-river'], ['g-camera']]); + }); + + it('writes json arrays as arrays even when the localization has none yet', async () => { + const source = buildSourceEntry(); + const current = reId(translateBySetup(source, getModel(uid), setupModel, EN)); + current.links = null; + current.tags = []; + + const { parsedLocalazyContent } = download(toLocalazyKeys(upload(source), (_, value) => EN(value))); + const updated = await update(parsedLocalazyContent.en[uid][documentId], current, source); + + expect(Object.keys(updated.links)).toEqual(['0', '1']); + expect(Object.keys(updated.tags)).toEqual(['0', '1']); + expect(updated.links).toEqual(translateBySetup(source, getModel(uid), setupModel, EN).links); + expect(updated.tags).toEqual(['[en] příroda', '[en] fotografie']); + }); +}); diff --git a/server/src/utils/align-localized-entry-to-source.ts b/server/src/utils/align-localized-entry-to-source.ts new file mode 100644 index 0000000..b5c0eb2 --- /dev/null +++ b/server/src/utils/align-localized-entry-to-source.ts @@ -0,0 +1,92 @@ +import { cloneDeep, isPlainObject } from 'lodash-es'; +import { findModel } from './model-utils'; + +/** Remove the ids of components and dynamic zone items (not of media or relations) in place. */ +const dropComponentIds = (models, item: any, model: any): void => { + if (!isPlainObject(item)) { + return; + } + delete item.id; + for (const [name, attribute] of Object.entries(model?.attributes || {})) { + const value = item[name]; + if (attribute.type === 'component') { + const componentModel = findModel(models, attribute.component); + (Array.isArray(value) ? value : [value]).forEach((child) => dropComponentIds(models, child, componentModel)); + } else if (attribute.type === 'dynamiczone' && Array.isArray(value)) { + value.forEach((child) => dropComponentIds(models, child, findModel(models, child?.__component))); + } + } +}; + +/** A source-locale item, ready to be written into the localization as a new component. */ +const asNewComponent = (models, sourceItem: any, model: any) => { + const copy = cloneDeep(sourceItem); + dropComponentIds(models, copy, model); + return copy; +}; + +/** + * Downloaded values are positioned by the source-locale entry: the n-th repeatable component or + * dynamic zone item of the source goes to the n-th item of the localization. That holds only while + * both lists have the same layout. When the source list was changed (items added or removed, + * dynamic zone components replaced or reordered), the localized list is rebuilt from the source + * items instead of merging translations into unrelated items. + * + * Only lists that receive downloaded values (present in `downloadedEntry`) are aligned; other + * localized values are kept as they are. + */ +export const alignLocalizedEntryToSource = ( + models, + localizedEntry: any, + sourceEntry: any, + model: any, + downloadedEntry: any +): any => { + if (!isPlainObject(localizedEntry) || !isPlainObject(sourceEntry) || !isPlainObject(downloadedEntry)) { + return localizedEntry; + } + + const aligned = { ...localizedEntry }; + for (const [name, attribute] of Object.entries(model?.attributes || {})) { + const source = sourceEntry[name]; + const current = localizedEntry[name]; + const downloaded = downloadedEntry[name]; + if (downloaded === undefined || downloaded === null || current === undefined) { + continue; + } + + if (attribute.type === 'component') { + const componentModel = findModel(models, attribute.component); + if (attribute.repeatable) { + if (!Array.isArray(source)) continue; + const currentItems = Array.isArray(current) ? current : []; + aligned[name] = + currentItems.length === source.length + ? currentItems.map((item, index) => + alignLocalizedEntryToSource(models, item, source[index], componentModel, downloaded[index]) + ) + : source.map((item) => asNewComponent(models, item, componentModel)); + } else if (isPlainObject(source) && isPlainObject(current)) { + aligned[name] = alignLocalizedEntryToSource(models, current, source, componentModel, downloaded); + } + } else if (attribute.type === 'dynamiczone') { + if (!Array.isArray(source)) continue; + const currentItems = Array.isArray(current) ? current : []; + const sameLayout = + currentItems.length === source.length && + currentItems.every((item, index) => item?.__component === source[index]?.__component); + aligned[name] = sameLayout + ? currentItems.map((item, index) => + alignLocalizedEntryToSource( + models, + item, + source[index], + findModel(models, item.__component), + downloaded[index] + ) + ) + : source.map((item) => asNewComponent(models, item, findModel(models, item.__component))); + } + } + return aligned; +}; diff --git a/server/src/utils/build-localized-create-entry.ts b/server/src/utils/build-localized-create-entry.ts new file mode 100644 index 0000000..c34063e --- /dev/null +++ b/server/src/utils/build-localized-create-entry.ts @@ -0,0 +1,26 @@ +import { merge } from 'lodash-es'; +import { parsedLocalazyEntryToCreateEntry } from './parsed-localazy-entry-to-create-entry'; +import { omitDeep } from './omit-deep'; +import { dropDocumentIdExceptMedia } from './drop-property-deep'; + +const OMIT_KEYS = ['locale', 'localizations', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy', 'publishedAt']; + +/** + * Data for creating a new localization of `baseEntry` (the source-locale entry) from the + * translated model downloaded from Localazy: the source entry with the translated values put in + * place. Items positioning is done by `parsedLocalazyEntryToCreateEntry`, so the two can be merged. + */ +export const buildLocalizedCreateEntry = (models, translatedModel, baseEntry, uid, isoStrapi: string) => { + const { createEntry } = parsedLocalazyEntryToCreateEntry(models, translatedModel, baseEntry, uid, isoStrapi); + + // TODO: Deal with relations - must be omitted + // Drop documentId from all objects except media objects (images, files, etc.) + const filteredBaseEntry = dropDocumentIdExceptMedia(omitDeep(baseEntry, OMIT_KEYS)); + + let mergedCreateEntry: Record = {}; + merge(mergedCreateEntry, filteredBaseEntry, createEntry); + mergedCreateEntry = omitDeep(mergedCreateEntry, OMIT_KEYS); + mergedCreateEntry.locale = isoStrapi; + + return mergedCreateEntry; +}; diff --git a/server/src/utils/collect-downloaded-content.ts b/server/src/utils/collect-downloaded-content.ts new file mode 100644 index 0000000..f1f6235 --- /dev/null +++ b/server/src/utils/collect-downloaded-content.ts @@ -0,0 +1,101 @@ +import { set } from 'lodash-es'; +import { findSetupModelByCollectionUid } from './transfer-setup-utils'; +import { + locateDownloadedField, + ShouldSetDownloadedPropertyReturnType, +} from '../functions/should-set-downloaded-property'; +import { createJsonFieldsDownloadAccumulator } from './json-fields-download-accumulator'; + +export type DownloadedLocalazyKey = { + id: string; + key: string[]; + value: unknown; + event?: number; +}; + +export type DownloadedKeySource = { lang: string; id: string; event: number | undefined }; + +/** `{ [isoStrapi]: { [uid]: { [documentId]: translatedModel } } }` */ +export type ParsedLocalazyContent = Record>>; + +type ParseLocalazyKey = (key: string) => { uid: string; id: string; rest: string[] }; + +/** + * Turns the keys downloaded from Localazy into one translated model per Strapi entry and locale, + * and records which keys changed for each entry (so they can be marked processed once the entry + * is written). + * + * With a sync cursor (`processedKeys`), only entries with at least one key changed since it was + * last processed are taken, but each of them with all of its keys: an incremental download + * rewrites a changed entry exactly as a full sync would. Applying the changed keys alone is not + * enough, because a json/blocks field is rebuilt from all of its leaves and list items are placed + * by the source entry, so a partial set of keys would put source-language text or wrong items into + * everything that did not change. + */ +export const collectDownloadedContent = ({ + languages, + processedKeys, + contentTransferSetup, + models, + parseLocalazyKey, +}: { + languages: Array<{ isoStrapi: string; keys: DownloadedLocalazyKey[] }>; + processedKeys: Record>; + contentTransferSetup: any; + models: any[]; + parseLocalazyKey: ParseLocalazyKey; +}) => { + const parsedLocalazyContent: ParsedLocalazyContent = {}; + const entryKeySourceMap: Record = {}; + const jsonFieldsAccumulator = createJsonFieldsDownloadAccumulator(); + + for (const { isoStrapi, keys } of languages) { + const parsedKeys = keys.map((localazyEntry) => { + const storedEvent = processedKeys[isoStrapi]?.[localazyEntry.id]; + const isChanged = !( + storedEvent !== undefined && + localazyEntry.event !== undefined && + localazyEntry.event <= storedEvent + ); + const parsedKey = parseLocalazyKey(localazyEntry.key[0]); + return { localazyEntry, parsedKey, isChanged, entryKey: `${isoStrapi}:${parsedKey.uid}:${parsedKey.id}` }; + }); + + for (const { localazyEntry, entryKey, isChanged } of parsedKeys) { + if (isChanged) { + if (!entryKeySourceMap[entryKey]) { + entryKeySourceMap[entryKey] = []; + } + entryKeySourceMap[entryKey].push({ lang: isoStrapi, id: localazyEntry.id, event: localazyEntry.event }); + } + } + + for (const { localazyEntry, parsedKey, entryKey } of parsedKeys) { + if (!entryKeySourceMap[entryKey]) { + continue; // nothing changed in this entry + } + + const modelContentTransferSetup = findSetupModelByCollectionUid(contentTransferSetup, models, parsedKey.uid); + if (typeof modelContentTransferSetup === 'undefined') { + continue; + } + + const { type, fieldSegmentIndex } = locateDownloadedField(modelContentTransferSetup, parsedKey.rest); + if (type === ShouldSetDownloadedPropertyReturnType.JSON) { + // before the field's own segment: path to the owning entry/component; after it: the + // leaf's path inside the field's value + jsonFieldsAccumulator.add( + [isoStrapi, parsedKey.uid, parsedKey.id, ...parsedKey.rest.slice(0, fieldSegmentIndex + 1)], + parsedKey.rest.slice(fieldSegmentIndex + 1), + localazyEntry.value + ); + } else if (type === ShouldSetDownloadedPropertyReturnType.YES) { + set(parsedLocalazyContent, [isoStrapi, parsedKey.uid, parsedKey.id, ...parsedKey.rest], localazyEntry.value); + } + } + } + + jsonFieldsAccumulator.applyTo(parsedLocalazyContent); + + return { parsedLocalazyContent, entryKeySourceMap }; +}; diff --git a/server/src/utils/json-fields-download-accumulator.ts b/server/src/utils/json-fields-download-accumulator.ts new file mode 100644 index 0000000..99cda16 --- /dev/null +++ b/server/src/utils/json-fields-download-accumulator.ts @@ -0,0 +1,38 @@ +import { set } from 'lodash-es'; + +/** + * Collects the downloaded keys of `json` and `blocks` fields. On upload such a field is flattened + * into one Localazy key per leaf; on download the leaves are put back together into one value per + * field, which is then written into the parsed Localazy content at the field's own path. + * + * A field is identified by its full path (owner path + field name), so two json/blocks fields of + * the same entry or component (e.g. a component's `title` and `line`) never share one value, and + * a field inside a nested component is written at its own level instead of replacing the + * component it lives in. + */ +export const createJsonFieldsDownloadAccumulator = () => { + const fields = new Map }>(); + + return { + /** + * @param fieldKey path to the field in the parsed content: `[iso, uid, documentId, ...ownerPath, fieldName]` + * @param valuePath path of this leaf inside the field's value + */ + add(fieldKey: string[], valuePath: string[], value: unknown) { + const id = JSON.stringify(fieldKey); + let field = fields.get(id); + if (!field) { + field = { fieldKey, value: {} }; + fields.set(id, field); + } + set(field.value, valuePath, value); + }, + + /** Write every collected field value into `parsedContent` at its own path. */ + applyTo(parsedContent: Record) { + for (const { fieldKey, value } of fields.values()) { + set(parsedContent, fieldKey, value); + } + }, + }; +}; diff --git a/server/src/utils/model-utils.ts b/server/src/utils/model-utils.ts index 7059104..f58b52d 100644 --- a/server/src/utils/model-utils.ts +++ b/server/src/utils/model-utils.ts @@ -30,9 +30,13 @@ const isBlocks = (attributeObj) => { return attributeObj.type === BLOCKS_ATTRIBUTE_TYPE; }; +const isJson = (attributeObj) => { + return attributeObj.type === 'json'; +}; + const findModel = (models, uid) => { const model = models.find((model) => model.uid === uid); return model; }; -export { getAttribute, isComponent, isDynamicZone, isRepeatable, isRelation, isBlocks, findModel }; +export { getAttribute, isComponent, isDynamicZone, isRepeatable, isRelation, isBlocks, isJson, findModel }; diff --git a/server/src/utils/overlay-json-translation.ts b/server/src/utils/overlay-json-translation.ts new file mode 100644 index 0000000..dfbb9af --- /dev/null +++ b/server/src/utils/overlay-json-translation.ts @@ -0,0 +1,67 @@ +import { cloneDeep, get, isPlainObject } from 'lodash-es'; + +/** + * The key segment `flattenObject` uses for an array item: `id;__component` for component-like + * objects, else the item's `documentId` or `id`, else its index. + */ +const arrayItemSegment = (item: any, index: number): string => { + if (isPlainObject(item) && item.id && item.__component) { + return `${item.id};${item.__component}`; + } + return String(item?.documentId || item?.id || index); +}; + +/** `flattenObject` adds an object's own `documentId` / `id` as an extra key segment. */ +const objectIdSegment = (value: any): string | undefined => { + if (isPlainObject(value) && (value.documentId || value.id)) { + return String(value.documentId || value.id); + } + return undefined; +}; + +const overlayValue = (source: any, translated: any): any => { + if (typeof source === 'string') { + return typeof translated === 'string' ? translated : source; + } + + if (Array.isArray(source)) { + // an array item's id already is its segment; it is not added a second time + return source.map((item, index) => overlayValue(item, get(translated, [arrayItemSegment(item, index)]))); + } + + if (isPlainObject(source)) { + const result: Record = {}; + for (const [key, value] of Object.entries(source)) { + // never uploaded (`flattenObject` skips them), so never translated + result[key] = key === 'id' || key === 'documentId' ? value : overlayChild(value, get(translated, [key])); + } + return result; + } + + // numbers, booleans, null: not translatable + return source; +}; + +const overlayChild = (source: any, translated: any): any => { + const idSegment = Array.isArray(source) ? undefined : objectIdSegment(source); + return overlayValue(source, idSegment ? get(translated, [idSegment]) : translated); +}; + +/** + * Download side of a `json` field. On upload, every leaf of the source-locale value becomes one + * Localazy key (see `flattenObject`); `translated` is those leaves put back together by key path. + * The result is a copy of the source value with each string leaf replaced by its translation, so + * its shape (objects vs arrays, numeric keys, non-string values) always matches the source, leaves + * that are no longer in the source are ignored, and untranslated leaves keep the source text. + * + * Returns `undefined` when there is no source value to overlay onto. + */ +export const overlayJsonTranslation = (sourceValue: any, translated: any): any => { + if (sourceValue === undefined || sourceValue === null) { + return undefined; + } + if (typeof sourceValue !== 'object') { + return typeof sourceValue === 'string' && typeof translated === 'string' ? translated : sourceValue; + } + return overlayChild(cloneDeep(sourceValue), translated); +}; diff --git a/server/src/utils/parse-localazy-key.ts b/server/src/utils/parse-localazy-key.ts new file mode 100644 index 0000000..0eec327 --- /dev/null +++ b/server/src/utils/parse-localazy-key.ts @@ -0,0 +1,16 @@ +/** + * Split a Localazy key produced by the upload (`flattenObject`) into the content type uid, the + * document id and the remaining path segments, e.g. + * `api::page.page[doc].sections[3;sections.timeline].stops[11].label` → + * `{ uid: 'api::page.page', id: 'doc', rest: ['sections', '3;sections.timeline', 'stops', '11', 'label'] }`. + */ +export const parseLocalazyKey = (key: string) => { + const split = key.split(/\.(?![^[]*])|\[|\]/); + const filteredSplit = split.filter((item) => item !== ''); + + return { + uid: `${filteredSplit[0]}.${filteredSplit[1]}`, + id: filteredSplit[2], + rest: filteredSplit.slice(3), + }; +}; diff --git a/server/src/utils/parsed-localazy-entry-to-create-entry.ts b/server/src/utils/parsed-localazy-entry-to-create-entry.ts index 0e8bc39..57a1ed6 100644 --- a/server/src/utils/parsed-localazy-entry-to-create-entry.ts +++ b/server/src/utils/parsed-localazy-entry-to-create-entry.ts @@ -1,10 +1,17 @@ import { set, get } from 'lodash-es'; -import { resetArrayKeysDeep } from './reset-array-keys-deep'; -import { getAttribute, isComponent, isDynamicZone, isRepeatable, isBlocks, findModel } from './model-utils'; +import { getAttribute, isComponent, isDynamicZone, isRepeatable, isBlocks, isJson, findModel } from './model-utils'; import { overlayBlocksTranslation } from './blocks-to-translatable'; +import { overlayJsonTranslation } from './overlay-json-translation'; /** - * Items positioning is done by the `toCreateEntry` function + * Items positioning is done by the `toCreateEntry` function: repeatable component and dynamic + * zone items are placed at their position in `baseEntry` (the source-locale entry), so arrays may + * have holes for items without downloaded values. They are not compacted, because callers merge + * the result onto a complete entry (the source entry, or the current localization), and shifting + * items would put translations into the wrong item. + * + * `rebuiltFieldPaths` lists where blocks and json fields were written; each holds a complete value + * rebuilt from the source value (see `overlayBlocksTranslation`, `overlayJsonTranslation`). */ export const parsedLocalazyEntryToCreateEntry = ( models: any, @@ -14,8 +21,8 @@ export const parsedLocalazyEntryToCreateEntry = ( locale = '' ) => { const createEntry: Record = {}; - const repeatableComponentsKeystoFilter = []; const dynamicZoneComponentKeys = []; + const rebuiltFieldPaths: string[] = []; const toCreateEntry = ( entry: any, @@ -33,10 +40,6 @@ export const parsedLocalazyEntryToCreateEntry = ( Object.entries(entry).forEach(([baseEntryItemId, value]) => { if (value !== null) { if (component && isRepeatableComponent) { - // used for indices filtering in repeatable components - if (!repeatableComponentsKeystoFilter.includes(prefix)) { - repeatableComponentsKeystoFilter.push(prefix); - } const baseEntryRepeatableItemId = parseInt(baseEntryItemId); const baseEntryRepeateableGroup = get(baseEntry, prefix); if (baseEntryRepeateableGroup !== undefined) { @@ -60,10 +63,6 @@ export const parsedLocalazyEntryToCreateEntry = ( } if (!component && isRepeatableComponent) { - // used for indices filtering in dynamic zones - if (!repeatableComponentsKeystoFilter.includes(prefix)) { - repeatableComponentsKeystoFilter.push(prefix); - } const baseEntryRepeatableItemId = parseInt(baseEntryItemId); const baseEntryRepeateableGroup = get(baseEntry, prefix); if (baseEntryRepeateableGroup !== undefined) { @@ -173,15 +172,24 @@ export const parsedLocalazyEntryToCreateEntry = ( newPrefixBase = `${dzParamKey}.${baseEntryDZIndex}`; newPrefix = `${newPrefixBase}.${objectKey}`; } - // A blocks field arrives as a text-only skeleton (one segment per text node). Rebuild the - // full AST by overlaying the translated text onto the source-locale AST, so structure and - // formatting are restored from the source. Skip when there is no source AST to overlay - // onto rather than write an invalid document. - const valueToSet = isBlocks(attribute) ? overlayBlocksTranslation(get(baseEntry, newPrefix), value) : value; + // A blocks or json field arrives as its translated leaves. Rebuild the full value by + // overlaying them onto the source-locale value, so structure, formatting and + // non-translatable values come from the source. Skip when there is no source value to + // overlay onto rather than write an invalid one. + const isRebuiltField = isBlocks(attribute) || isJson(attribute); + let valueToSet = value; + if (isBlocks(attribute)) { + valueToSet = overlayBlocksTranslation(get(baseEntry, newPrefix), value); + } else if (isJson(attribute)) { + valueToSet = overlayJsonTranslation(get(baseEntry, newPrefix), value); + } if (valueToSet === undefined) { return; } set(createEntry, newPrefix, valueToSet); + if (isRebuiltField) { + rebuiltFieldPaths.push(newPrefix); + } if (component) { const componentKeyToSet = `${newPrefixBase}.__component`; @@ -209,6 +217,5 @@ export const parsedLocalazyEntryToCreateEntry = ( createEntry.locale = locale; } - resetArrayKeysDeep(createEntry, repeatableComponentsKeystoFilter); - return { createEntry, dynamicZoneComponentKeys }; + return { createEntry, dynamicZoneComponentKeys, rebuiltFieldPaths }; }; diff --git a/server/src/utils/parsed-localazy-entry-to-update-entry.ts b/server/src/utils/parsed-localazy-entry-to-update-entry.ts index e097adc..7b133c2 100644 --- a/server/src/utils/parsed-localazy-entry-to-update-entry.ts +++ b/server/src/utils/parsed-localazy-entry-to-update-entry.ts @@ -1,7 +1,9 @@ -import { set, merge } from 'lodash-es'; +import { set, get, merge, cloneDeep } from 'lodash-es'; import { parsedLocalazyEntryToCreateEntry } from './parsed-localazy-entry-to-create-entry'; import { omitDeep } from './omit-deep'; import { populateCreateUpdateEntryWithBaseEntry } from './populate-create-update-entry-with-base-entry'; +import { alignLocalizedEntryToSource } from './align-localized-entry-to-source'; +import { findModel } from './model-utils'; export const parsedLocalazyEntryToUpdateEntry = async ( allModels, @@ -12,23 +14,26 @@ export const parsedLocalazyEntryToUpdateEntry = async ( uid, locale ) => { - const { createEntry, dynamicZoneComponentKeys } = parsedLocalazyEntryToCreateEntry( + const { createEntry, dynamicZoneComponentKeys, rebuiltFieldPaths } = parsedLocalazyEntryToCreateEntry( allModels, localazyEntry, baseEntry, uid ); - /** - * TODO: possibly improve for the following case: - * A `key` is deleted from the base entry, and the same `key` still exist in the localized entry. - * Even though the `key` is deprecated in Localazy, it concludes that the `key` is still used in the localized entry. - * Therefore, it leads to an error when updating the entry. - * - * The solution for now: Delete the localized entry and re-download to force the creation process. - */ + // Downloaded values are positioned by the source entry; lists whose layout changed in the source + // are rebuilt from it before merging (see `alignLocalizedEntryToSource`). + const model = findModel(allModels, uid); + const alignedCurrentEntry = alignLocalizedEntryToSource(allModels, currentEntry, baseEntry, model, createEntry); + let updateEntry = {}; - merge(updateEntry, currentEntry, createEntry); + merge(updateEntry, alignedCurrentEntry, createEntry); + // A downloaded blocks or json field is a complete value rebuilt from the current source value. + // Replace the localized one instead of deep-merging into it, which would keep marks, nodes, + // paragraphs and keys that no longer exist in the source. + for (const rebuiltFieldPath of rebuiltFieldPaths) { + set(updateEntry, rebuiltFieldPath, cloneDeep(get(createEntry, rebuiltFieldPath))); + } updateEntry = omitDeep(updateEntry, [ // '__component', // do not omit the __component 'locale', @@ -54,16 +59,19 @@ export const parsedLocalazyEntryToUpdateEntry = async ( 'updatedBy', 'publishedAt', ]); - const filteredFullyPopulatedLocalizedEntry = omitDeep(fullyPopulatedLocalizedEntry, [ - // "__component", // do not omit the __component - 'locale', - 'localizations', - 'createdAt', - 'createdBy', - 'updatedAt', - 'updatedBy', - 'publishedAt', - ]); + const filteredFullyPopulatedLocalizedEntry = omitDeep( + alignLocalizedEntryToSource(allModels, fullyPopulatedLocalizedEntry, baseEntry, model, createEntry), + [ + // "__component", // do not omit the __component + 'locale', + 'localizations', + 'createdAt', + 'createdBy', + 'updatedAt', + 'updatedBy', + 'publishedAt', + ] + ); const populatedEntry = await populateCreateUpdateEntryWithBaseEntry( allModels, updateEntry, diff --git a/server/src/utils/populate-create-update-entry-with-base-entry.ts b/server/src/utils/populate-create-update-entry-with-base-entry.ts index 0aecd04..ac6795b 100644 --- a/server/src/utils/populate-create-update-entry-with-base-entry.ts +++ b/server/src/utils/populate-create-update-entry-with-base-entry.ts @@ -1,5 +1,14 @@ import { cloneDeep, set, get, isEmpty } from 'lodash-es'; -import { getAttribute, isComponent, isRepeatable, isDynamicZone, isRelation, findModel } from './model-utils'; +import { + getAttribute, + isComponent, + isRepeatable, + isDynamicZone, + isRelation, + isBlocks, + isJson, + findModel, +} from './model-utils'; const doesExistInPopulatedLocalizedEntry = (val) => { if (Array.isArray(val)) { @@ -64,17 +73,19 @@ export const populateCreateUpdateEntryWithBaseEntry = async ( } } } else if (!component && isRepeatableComponent && isDZ) { - Object.entries(partialBaseEntry).forEach(async ([partialBaseEntryItemIndex, partialBaseEntryItem]) => { + // awaited in sequence: items can hold relations resolved asynchronously, which must be in + // place before the populated entry is returned (and handed to Strapi) + for (const [partialBaseEntryItemIndex, partialBaseEntryItem] of Object.entries(partialBaseEntry)) { const component = partialBaseEntryItem.__component; const model = findModel(models, component); const newPrefix = `${prefix}.${partialBaseEntryItemIndex}`; await populateEntry(partialBaseEntryItem, model, partialBaseEntryItemIndex, newPrefix); - }); + } } else if (component && isRepeatableComponent) { - Object.entries(partialBaseEntry).forEach(async ([partialBaseEntryItemIndex, partialBaseEntryItem]) => { + for (const [partialBaseEntryItemIndex, partialBaseEntryItem] of Object.entries(partialBaseEntry)) { const newPrefix = `${prefix}.${partialBaseEntryItemIndex}`; await populateEntry(partialBaseEntryItem, model, partialBaseEntryItemIndex, newPrefix); - }); + } } } else if (typeof partialBaseEntry === 'object') { // is object @@ -206,7 +217,8 @@ export const populateCreateUpdateEntryWithBaseEntry = async ( } else { set(populatedEntry, newPrefix, value); } - } else { + } else if (!isBlocks(attribute) && !isJson(attribute)) { + // a json/blocks value is complete as it is, not a structure of the model to populate await populateEntry(value, model, objectKey, newPrefix); } } diff --git a/server/src/utils/reset-array-keys-deep.ts b/server/src/utils/reset-array-keys-deep.ts deleted file mode 100644 index 489ad03..0000000 --- a/server/src/utils/reset-array-keys-deep.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { set, get } from 'lodash-es'; - -export const resetArrayKeysDeep = (object: Record, keysToFilter: string[]) => { - // sort keys from deep to shallow (so we won't rewrite indices) - const sortedKeysToFilter = keysToFilter.sort((a, b) => { - const aLvl = a.match(/\./g)?.length || 0; - const bLvl = b.match(/\./g)?.length || 0; - - return bLvl - aLvl; - }); - for (const key of sortedKeysToFilter) { - const part = get(object, key); - const filteredPart = part.filter((item) => item !== undefined); - set(object, key, filteredPart); - } -}; diff --git a/server/src/utils/transfer-setup-utils.ts b/server/src/utils/transfer-setup-utils.ts index 322cf04..3156b2b 100644 --- a/server/src/utils/transfer-setup-utils.ts +++ b/server/src/utils/transfer-setup-utils.ts @@ -15,7 +15,8 @@ const findSetupModelByCollectionUid = (contentTransferSetup, strapiContentTypesM const modelContentTransferSetup = contentTransferSetup.setup.find( (model) => Object.keys(model)[0] === currentModel.collectionName ); - return modelContentTransferSetup[currentModel.collectionName]; + // a model that is not part of the Content Transfer Setup (anymore) has no setup + return modelContentTransferSetup?.[currentModel.collectionName]; }; const getCollectionsNames = (setup) => {