AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(pieces): the piece selector loads faster in languages other than English (#16620)
Hazem Adel2fb561019f17
diff --git a/brain/knowledge/pieces-engine/pieces.md b/brain/knowledge/pieces-engine/pieces.mdindex 7901d3cc181..3c2c8ca4b7d 100644--- a/brain/knowledge/pieces-engine/pieces.md+++ b/brain/knowledge/pieces-engine/pieces.md@@ -24,8 +24,9 @@ The metadata catalog of automation integrations ("pieces") — each a named inte- Install and sync also enqueue a tool-search reindex, but only when `isToolSearchEnabled()`; no-op otherwise.- `delete` removes all versions sharing the name on that platform, and only for `CUSTOM` pieces the caller owns.- **A piece silently vanishes from the list when its `minimumSupportedRelease` is ahead of the root `package.json` version.** `fetchLatestPieces` filters every piece through `isSupportedRelease(apVersionUtil.getCurrentRelease(), piece)`. Pieces are routinely merged targeting the *next* release, so on `main` a couple dozen are invisible locally until the version bump lands. No warning is logged — it just isn't there. The same gate hides the version from exact-version lookups (`findExactVersion`), so a flow step saved on it fails to load on an older server, and `AP_DEV_PIECES` does not bypass it: the database copies are dropped by name and the dev copy by release, so the piece vanishes entirely. To test a piece that targets the next release, bump the root `package.json` version locally and do not commit it. A server that already reports that release but lacks the server code the piece needs is the dangerous case; check `origin/main`'s root version at merge time.-- **`/v1/pieces` is uncached, so a new `piece_metadata` column must be added to `PIECE_COLUMNS_WITHOUT_TRANSLATIONS` or it silently will not appear in the list.** `pieceCache` caches only the *registry* (name/version/platformId tuples) for `get`/`findExactVersion`/`registry`; the list path never touches it, and the `dedupe()` helper in `piece-metadata-service.ts` is in-flight-only (it deletes the key in `finally`), so it collapses concurrent callers but caches nothing between requests. Every request therefore re-runs the whole pipeline against the DB. Because of that, `fetchLatestCompatiblePiecesFromDB` selects an explicit column list that deliberately omits `i18n` — that column holds every locale for the piece (~50 MB across the catalogue, written by `pieceInstallService`) and the list path discards it, so loading it was pure waste. Non-English requests now pull only the one locale in a second query (`pm."i18n" -> :locale`) and hand it to `pieceTranslation.translatePiece`, which also shrinks its `JSON.parse(JSON.stringify(...))` deep clone. The cost is that the explicit select is a list to keep in sync with the entity.-- **Piece sorting mutates its input, which is why the list result cannot simply be cached.** `pieceSorting`'s comparators and `reverseIfDesc` sort in place (`pieces.sort(...)`, `pieces.reverse()`). That is safe only because the array is rebuilt per request; making them non-mutating is a prerequisite for ever caching the built list, or requests would reorder shared state under each other. Same trap in `pieceTranslation.translatePiece`: when the piece has no entry for the locale it returns the *original* object rather than a clone, so any `piece.i18n = undefined` after it would mutate the shared row — take the no-translations branch before calling it.+- **`/v1/pieces` is uncached, so a new `piece_metadata` column must be added to `PIECE_COLUMNS_WITHOUT_TRANSLATIONS` or it silently will not appear in the list.** `pieceCache` caches only the *registry* (name/version/platformId tuples) for `get`/`findExactVersion`/`registry`; the list path never touches it, and the `dedupe()` helper in `piece-metadata-service.ts` is in-flight-only (it deletes the key in `finally`), so it collapses concurrent callers but caches nothing between requests. Every request therefore re-runs the whole pipeline against the DB. Because of that, `fetchLatestCompatiblePiecesFromDB` selects an explicit column list that deliberately omits `i18n` — that column holds every locale for the piece (~50 MB across the catalogue, written by `pieceInstallService`) and the list path discards it, so loading it was pure waste. Non-English requests now pull only the one locale in a second query (`pm."i18n" -> :locale`) and hand it to `pieceTranslation.translatePiece`. The single-piece path (`get`/`getOrThrow`) selects the same columns and goes through the same `translatePieces`, so no response ever carries `i18n`. The cost is that the explicit select is a list to keep in sync with the entity.+- **Piece sorting mutates its input, which is why the list result cannot simply be cached.** `pieceSorting`'s comparators and `reverseIfDesc` sort in place (`pieces.sort(...)`, `pieces.reverse()`). That is safe only because the array is rebuilt per request; making them non-mutating is a prerequisite for ever caching the built list, or requests would reorder shared state under each other.+- **`translatePiece` is copy-on-write: never deep-clone a piece to translate it, and never cache translated lists.** It copies only the objects on a translated path and returns the input's other subtrees by reference, in one walk over a tree built from `pathsToValuesToTranslate`. The input is shared through `dedupe()` across concurrent requests in different locales, so mutating it leaks one locale into another. The old `JSON.parse(JSON.stringify(piece))` made every non-English list ~3x slower than English (GIT-1891), and caching the translated catalogue per locale was tried twice (#15340, #15639) and dropped over memory. `packages/pieces/framework/test/i18n.test.ts` fails if a deep clone comes back. What remains is the `i18n -> :locale` read on a `json` column (~100 ms, paid even for a locale with no rows); moving to `jsonb` or a per-locale table is the next lever if that matters.- **DynamicProperties clears its value before it knows the new schema, so the merge source must be a snapshot.** `DynamicPropertiesImplementation` re-fetches the child schema on every refresher change, clearing the form value synchronously and re-populating it in the mutation callback. The merge source for `getDefaultValueForProperties` has to be a `lastKnownValue` ref captured *before* the clear — reading `form.getValues()` in the callback sees the cleared `null` and defaults every child (GIT-1514). The snapshot must be spread-cloned: RHF `getValues(name)` hands back the live object and the clear's `setValue(...child, null)` mutates it in place. Guard the ref with `isNil` so it survives rapid successive changes, where later effect runs already observe `null`.- `DynamicPropertiesContext` tracks loading by property name only, so two in-flight requests for the same property let the first completion clear the flag for both — briefly re-enabling Test Step while the value is still cleared.- **`POST /v1/pieces/options` cost scales with the whole flow's sample data, not with the property being resolved.** The handler builds an `EXECUTE_PROPERTY` job whose payload carries `sampleData` — and `getSampleDataForFlow` reads *every* step's sample-data `file` row. That payload then crosses Postgres → API → Redis → worker → engine socket, so a big flow pays megabytes to resolve a trivial resolver like the HTTP piece's `authFields`: measured 7.3 MB on a 25-step flow, and a panel open fires three of these in parallel (GIT-1822). The engine only uses `sampleData` to seed step outputs so `{{step.x}}` inside the property's `input` resolves, so callers must use `getSampleDataReferencedBy` and pass the request `input` — which narrows the read to the steps that input names. When narrowing, a referenced `LOOP_ON_ITEMS` step also needs whatever its `items` expression references: `stateFromFlowVersion` derives a loop's `item` by resolving its settings against the context built so far, never from `sampleData[loopName]`. Matching step names as substrings of the serialized input over-approximates, which is the safe direction — a step reference always spells the name literally, in both the property-path and script branches of `props-resolver`.diff --git a/packages/pieces/framework/src/lib/i18n.ts b/packages/pieces/framework/src/lib/i18n.tsindex 124a4cee522..62da87a3b7a 100644--- a/packages/pieces/framework/src/lib/i18n.ts+++ b/packages/pieces/framework/src/lib/i18n.ts@@ -5,26 +5,12 @@ import path from 'path';import fs from 'fs/promises';export const pieceTranslation = {- translatePiece: <T extends PieceMetadataModelSummary | PieceMetadataModel>(params: TranslatePieceParams<T>): T => {- const { piece, locale, mutate = false } = params- if (!locale) {- return piece- }- try {- const target = piece.i18n?.[locale]- if (!target) {- return piece- }- const translatedPiece: T = mutate ? piece : JSON.parse(JSON.stringify(piece))- pieceTranslation.pathsToValuesToTranslate.forEach(key => {- translateProperty(translatedPiece, key, target)- })- return translatedPiece- }- catch (err) {- console.error(`error translating piece ${piece.name}:`, err)+ translatePiece: <T extends PieceMetadataModelSummary | PieceMetadataModel>({ piece, locale }: TranslatePieceParams<T>): T => {+ const translations = locale ? piece.i18n?.[locale] : undefined+ if (!translations) {return piece}+ return translateNode({ node: piece, tree: translationTree, translations })},/**Gets the piece metadata regardles of piece location (node_modules or dist), wasn't included inside piece.metadata() for backwards compatibility issues (if an old ap version installs a new piece it would fail)*/@@ -71,30 +57,40 @@ export const pieceTranslation = {]}+const translationTree = pieceTranslation.pathsToValuesToTranslate.reduce<TranslationTree>((tree, path) => addPath({ tree, keys: path.split('.') }), {})-/**This function translates a property inside a piece, i.e description, displayName, etc...- *- * @param pieceModelOrProperty - The piece model or property to translate- * @param path - The path to the property to translate, i.e auth.username.displayName- * @param i18n - The i18n object- */-function translateProperty(pieceModelOrProperty: Record<string, unknown>, path: string, i18n: Record<string, string>) {- const parsedKeys = path.split('.');- if (parsedKeys[0] === '*') {- return Object.values(pieceModelOrProperty).forEach(item => translateProperty(item as Record<string, unknown>, parsedKeys.slice(1).join('.'), i18n))- }- const nextObject = pieceModelOrProperty[parsedKeys[0]] as Record<string, unknown>;- if (!nextObject) {- return;+function addPath({ tree, keys: [key, ...rest] }: AddPathParams): TranslationTree {+ return { ...tree, [key]: rest.length === 0 ? null : addPath({ tree: tree[key] ?? {}, keys: rest }) }+}++function translateNode<N>({ node, tree, translations }: TranslateNodeParams<N>): N {+ if (!isRecord(node)) {+ return node}- if (parsedKeys.length > 1) {- return translateProperty(nextObject, parsedKeys.slice(1).join('.'), i18n);+ const changes: Record<string, unknown> = {}+ let changed = false+ for (const [key, subtree] of Object.entries(tree)) {+ for (const childKey of key === '*' ? Object.keys(node) : [key]) {+ const child = node[childKey]+ const translated = subtree === null ? translateValue({ value: child, translations }) : translateNode({ node: child, tree: subtree, translations })+ if (translated !== child) {+ changes[childKey] = translated+ changed = true+ }+ }}- const propertyValue = pieceModelOrProperty[parsedKeys[0]] as string- const valueInI18n = i18n[propertyValue.slice(0, MAX_KEY_LENGTH_FOR_CORWDIN)]- if (valueInI18n) {- pieceModelOrProperty[parsedKeys[0]] = valueInI18n+ return changed ? Object.assign(Array.isArray(node) ? [] : {}, node, changes) : node+}++function translateValue({ value, translations }: TranslateValueParams): unknown {+ if (typeof value !== 'string') {+ return value}+ return translations[value.slice(0, MAX_KEY_LENGTH_FOR_CORWDIN)] || value+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null}async function fileExists(filePath: string) {@@ -128,5 +124,24 @@ const readLocaleFile = async (locale: LocalesEnum, pieceOutputPath: string) => {type TranslatePieceParams<T extends PieceMetadataModelSummary | PieceMetadataModel> = {piece: Tlocale?: LocalesEnum- mutate?: boolean+}++type TranslationTree = {+ [key: string]: TranslationTree | null+}++type AddPathParams = {+ tree: TranslationTree+ keys: string[]+}++type TranslateNodeParams<N> = {+ node: N+ tree: TranslationTree+ translations: Record<string, string>+}++type TranslateValueParams = {+ value: unknown+ translations: Record<string, string>}diff --git a/packages/pieces/framework/test/i18n.test.ts b/packages/pieces/framework/test/i18n.test.tsnew file mode 100644index 00000000000..03ac0b0ac01--- /dev/null+++ b/packages/pieces/framework/test/i18n.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest';+import { LocalesEnum } from '@activepieces/core-utils';+import { PackageType, PieceType } from '@activepieces/core-piece-types';+import { createAction } from '../src/lib/action/action';+import { pieceTranslation } from '../src/lib/i18n';+import { createPiece } from '../src/lib/piece';+import { PieceMetadataModel } from '../src/lib/piece-metadata';+import { PieceAuth, Property } from '../src/lib/property';++const buildPiece = (): PieceMetadataModel => JSON.parse(JSON.stringify({+ ...createPiece({+ displayName: 'Mailer',+ description: 'Send mail',+ logoUrl: 'https://example.com/logo.png',+ auth: PieceAuth.SecretText({ displayName: 'API key', description: 'Your API key', required: true }),+ actions: [+ createAction({+ name: 'send',+ displayName: 'Send email',+ description: 'Sends an email',+ props: {+ to: Property.ShortText({ displayName: 'To', required: true }),+ format: Property.StaticDropdown({+ displayName: 'Format',+ required: true,+ options: { options: [{ label: 'Plain', value: 'plain' }, { label: 'HTML', value: 'html' }] },+ }),+ },+ run: async () => undefined,+ }),+ createAction({+ name: 'archive',+ displayName: 'Archive',+ props: {},+ run: async () => undefined,+ }),+ ],+ triggers: [],+ }).metadata(),+ name: '@activepieces/piece-mailer',+ version: '0.1.0',+ projectUsage: 0,+ pieceType: PieceType.OFFICIAL,+ packageType: PackageType.REGISTRY,+ i18n: {+ [LocalesEnum.JAPANESE]: {+ 'Send mail': 'メール送信',+ 'Your API key': 'あなたのAPIキー',+ 'Send email': 'メールを送信',+ 'To': '宛先',+ 'HTML': 'HTML形式',+ },+ },+}));++describe('pieceTranslation.translatePiece', () => {+ it('translates every configured path', () => {+ const translated = pieceTranslation.translatePiece({ piece: buildPiece(), locale: LocalesEnum.JAPANESE });++ expect(translated.description).toBe('メール送信');+ expect(translated.auth).toMatchObject({ displayName: 'API key', description: 'あなたのAPIキー' });+ expect(translated.actions['send'].displayName).toBe('メールを送信');+ expect(translated.actions['send'].props['to'].displayName).toBe('宛先');+ expect(translated.actions['send'].props['format']).toMatchObject({+ options: { options: [{ label: 'Plain', value: 'plain' }, { label: 'HTML形式', value: 'html' }] },+ });+ });++ it('never mutates the input piece', () => {+ const piece = buildPiece();+ const snapshot = structuredClone(piece);++ pieceTranslation.translatePiece({ piece, locale: LocalesEnum.JAPANESE });++ expect(piece).toEqual(snapshot);+ });++ it('shares untranslated subtrees with the input instead of copying them', () => {+ const piece = buildPiece();++ const translated = pieceTranslation.translatePiece({ piece, locale: LocalesEnum.JAPANESE });++ expect(translated.actions['archive']).toBe(piece.actions['archive']);+ expect(translated.triggers).toBe(piece.triggers);+ });++ it('returns the same piece when the locale has no translations', () => {+ const piece = buildPiece();++ expect(pieceTranslation.translatePiece({ piece, locale: LocalesEnum.GERMAN })).toBe(piece);+ });+});diff --git a/packages/server/api/src/app/pieces/metadata/piece-metadata-service.ts b/packages/server/api/src/app/pieces/metadata/piece-metadata-service.tsindex 60e669d3da1..ae23d24a09e 100644--- a/packages/server/api/src/app/pieces/metadata/piece-metadata-service.ts+++ b/packages/server/api/src/app/pieces/metadata/piece-metadata-service.ts@@ -52,7 +52,7 @@ export const pieceMetadataService = (log: FastifyBaseLogger) => {version: piece.version,}))},- async get({ projectId, platformId, version, name }: GetOrThrowParams): Promise<PieceMetadataModel | undefined> {+ async get({ projectId, platformId, version, name, locale }: GetOrThrowParams): Promise<PieceMetadataModel | undefined> {const bestMatch = await findExactVersion(log, { name, version, platformId })if (isNil(bestMatch)) {return undefined@@ -67,15 +67,16 @@ export const pieceMetadataService = (log: FastifyBaseLogger) => {if (isNil(piece)) {return undefined}+ const [translatedPiece] = await translatePieces({ pieces: [piece], locale: locale ?? LocalesEnum.ENGLISH })const policy = await resolveVisibility({ platformId, projectId, log })if (isNil(policy)) {- return piece+ return translatedPiece}- if (!policy.isPieceVisible(piece.name)) {+ if (!policy.isPieceVisible(translatedPiece.name)) {return undefined}- return policy.filterPieceComponents(piece)+ return policy.filterPieceComponents(translatedPiece)},async checkActionsExist({ actions, platformId }: CheckActionsExistParams): Promise<ActionExistence> {const latestVersions = await Promise.all(Object.keys(actions).map((name) => findExactVersion(log, { name, version: undefined, platformId })))@@ -105,7 +106,7 @@ export const pieceMetadataService = (log: FastifyBaseLogger) => {return rows.reduce<ActionExistence>((acc, row) => ({ ...acc, [row.pieceName]: { ...acc[row.pieceName], [row.actionName]: row.exists } }), {})},async getOrThrow({ version, name, platformId, locale }: GetOrThrowParams): Promise<PieceMetadataModel> {- const piece = await this.get({ version, name, platformId })+ const piece = await this.get({ version, name, platformId, locale })if (isNil(piece)) {throw new ActivepiecesError({code: ErrorCode.ENTITY_NOT_FOUND,@@ -114,10 +115,7 @@ export const pieceMetadataService = (log: FastifyBaseLogger) => {},})}- if (isNil(locale) || locale === LocalesEnum.ENGLISH) {- return piece- }- return pieceTranslation.translatePiece<PieceMetadataModel>({ piece, locale, mutate: false })+ return piece},async updateUsage({ id, usage }: UpdateUsage): Promise<void> {const existingMetadata = await pieceRepos().findOneByOrFail({@@ -431,18 +429,13 @@ async function fetchLatestPieces({ platformId, locale = LocalesEnum.ENGLISH, logconst currentRelease = apVersionUtil.getCurrentRelease()const latestPieces = await dedupe(`latest-pieces:${currentRelease}`, () => fetchLatestCompatiblePiecesFromDB(currentRelease))- const translatedPieces = await translatePieces({ pieces: latestPieces, locale })-const devPieces = await loadDevPiecesIfEnabled(log)- const translatedDevPieces = devPieces.map((piece) =>- pieceTranslation.translatePiece<PieceMetadataSchema>({ piece, locale, mutate: true }),- )- const devPieceNames = new Set(translatedDevPieces.map((p) => p.name))- const merged = [...translatedPieces.filter((p) => !devPieceNames.has(p.name)), ...translatedDevPieces]+ const devPieceNames = new Set(devPieces.map((p) => p.name))+ const merged = [...latestPieces.filter((p) => !devPieceNames.has(p.name)), ...devPieces].filter((piece) => filterPieceBasedOnType(platformId, piece)).filter((piece) => isSupportedRelease(currentRelease, piece))- return lastVersionOfEachPiece(merged)+ return translatePieces({ pieces: lastVersionOfEachPiece(merged), locale })}async function fetchPieceVersion({ pieceName, version, platformId, log }: FetchPieceVersionParams): Promise<PieceMetadataSchema | null> {@@ -458,6 +451,7 @@ async function fetchPieceVersion({ pieceName, version, platformId, log }: FetchPversion,platformId: platformId ?? IsNull(),},+ select: PIECE_COLUMNS_WITHOUT_TRANSLATIONS,})return foundPiece ?? null}@@ -518,17 +512,15 @@ async function translatePieces({ pieces, locale }: TranslatePiecesParams): Promi}const translationsByPieceId = await fetchTranslationsForLocale({ pieceIds: pieces.map((piece) => piece.id), locale })return pieces.map((piece) => {- const translations = translationsByPieceId.get(piece.id)+ const translations = translationsByPieceId.get(piece.id) ?? piece.i18n?.[locale]if (isNil(translations)) {return { ...piece, i18n: undefined }}const translated = pieceTranslation.translatePiece<PieceMetadataSchema>({piece: { ...piece, i18n: { [locale]: translations } },locale,- mutate: false,})- translated.i18n = undefined- return translated+ return { ...translated, i18n: undefined }})}diff --git a/packages/server/api/test/integration/ce/pieces/dev-piece-translation.test.ts b/packages/server/api/test/integration/ce/pieces/dev-piece-translation.test.tsnew file mode 100644index 00000000000..860b96125e7--- /dev/null+++ b/packages/server/api/test/integration/ce/pieces/dev-piece-translation.test.ts@@ -0,0 +1,64 @@+import { apId, LocalesEnum } from '@activepieces/core-utils'+import { PackageType, PieceType, PrincipalType } from '@activepieces/shared'+import { FastifyBaseLogger, FastifyInstance } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { pieceCache } from '../../../../src/app/pieces/metadata/piece-cache'+import { PieceMetadataSchema } from '../../../../src/app/pieces/metadata/piece-metadata-entity'+import { generateMockToken } from '../../../helpers/auth'+import { createMockPieceMetadata } from '../../../helpers/mocks'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++const devPiece: PieceMetadataSchema = {+ ...createMockPieceMetadata({+ name: 'dev-translated-piece',+ version: '0.1.0',+ pieceType: PieceType.OFFICIAL,+ packageType: PackageType.REGISTRY,+ description: 'Send a message',+ i18n: {+ [LocalesEnum.GERMAN]: { 'Send a message': 'Eine Nachricht senden' },+ },+ }),+}++vi.mock('../../../../src/app/pieces/metadata/utils', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../../src/app/pieces/metadata/utils')>()),+ loadDevPiecesIfEnabled: async () => [devPiece],+}))++let app: FastifyInstance | null = null+let mockLog: FastifyBaseLogger++beforeAll(async () => {+ app = await setupTestEnvironment()+ mockLog = app!.log!+ await pieceCache(mockLog).setup()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('dev pieces carrying their own translations', () => {+ it('are translated in the list and the single-piece route without leaking i18n', async () => {+ const testToken = await generateMockToken({+ type: PrincipalType.UNKNOWN,+ id: apId(),+ })+ const headers = { authorization: `Bearer ${testToken}` }++ const [list, single] = await Promise.all([+ app?.inject({ method: 'GET', url: '/api/v1/pieces?locale=de', headers }),+ app?.inject({ method: 'GET', url: '/api/v1/pieces/dev-translated-piece?locale=de', headers }),+ ])++ expect(list?.statusCode).toBe(StatusCodes.OK)+ expect(single?.statusCode).toBe(StatusCodes.OK)+ const listed = list?.json().find((piece: { name: string }) => piece.name === 'dev-translated-piece')+ expect(listed.description).toBe('Eine Nachricht senden')+ expect(listed.i18n).toBeUndefined()+ expect(single?.json().description).toBe('Eine Nachricht senden')+ expect(single?.json().i18n).toBeUndefined()+ expect(devPiece.description).toBe('Send a message')+ })+})diff --git a/packages/server/api/test/integration/ce/pieces/piece-metadata.test.ts b/packages/server/api/test/integration/ce/pieces/piece-metadata.test.tsindex 5a18fa7d3bf..bfcfd38a0d9 100644--- a/packages/server/api/test/integration/ce/pieces/piece-metadata.test.ts+++ b/packages/server/api/test/integration/ce/pieces/piece-metadata.test.ts@@ -255,6 +255,40 @@ describe('Piece Metadata CE API', () => {expect(body.displayName).toBe('CE Get Test')})+ it('translates the piece into the requested locale and never leaks i18n', async () => {+ const mockPiece = createMockPieceMetadata({+ name: 'locale-get-piece',+ pieceType: PieceType.OFFICIAL,+ description: 'Send a message',+ packageType: PackageType.REGISTRY,+ i18n: {+ [LocalesEnum.GERMAN]: { 'Send a message': 'Eine Nachricht senden' },+ [LocalesEnum.FRENCH]: { 'Send a message': 'Envoyer un message' },+ },+ })+ await db.save('piece_metadata', mockPiece)+ await pieceCache(mockLog).setup()++ const testToken = await generateMockToken({+ type: PrincipalType.UNKNOWN,+ id: apId(),+ })++ const responses = await Promise.all([LocalesEnum.GERMAN, LocalesEnum.ENGLISH].map((locale) => app?.inject({+ method: 'GET',+ url: `/api/v1/pieces/locale-get-piece?locale=${locale}`,+ headers: {+ authorization: `Bearer ${testToken}`,+ },+ })))++ const [german, english] = responses.map((response) => response?.json())+ expect(german.description).toBe('Eine Nachricht senden')+ expect(english.description).toBe('Send a message')+ expect(german.i18n).toBeUndefined()+ expect(english.i18n).toBeUndefined()+ })+it('should return 404 for non-existent piece', async () => {await pieceCache(mockLog).setup()