Files
web/scripts/i18n/formatter.ts
Anton Gunnarsson 233c685e52 Merged in feat/sw-2333-package-and-sas-i18n (pull request #2538)
feat(SW-2333): I18n for multiple apps and packages

* Set upp i18n in partner-sas

* Adapt lokalise workflow to monorepo

* Fix layout props


Approved-by: Linus Flood
2025-07-10 07:00:03 +00:00

98 lines
2.6 KiB
TypeScript

// https://docs.lokalise.com/en/articles/3229161-structured-json
import { logger } from '@scandic-hotels/common/logger'
import type { MessageDescriptor } from '@formatjs/intl'
interface LokaliseMessageDescriptor extends Omit<MessageDescriptor, 'description'> {
description: {
context?: string
limit?: number
tags?: string
}
}
type TranslationEntry = {
translation: string
notes?: string
context?: string
limit?: number
tags?: string[]
}
type CompiledEntries = Record<string, string>
type LokaliseStructuredJson = Record<string, TranslationEntry>
export function format(msgs: LokaliseMessageDescriptor[]): LokaliseStructuredJson {
const results: LokaliseStructuredJson = {}
for (const [id, msg] of Object.entries(msgs)) {
const { defaultMessage, description } = msg
if (typeof defaultMessage === 'string') {
const entry: TranslationEntry = {
translation: defaultMessage,
}
if (description) {
if (typeof description === 'string') {
logger.warn(
`Unsupported type for description, expected 'object', got ${typeof description}. Skipping!`,
msg
)
} else {
const { context, limit, tags } = description
if (context) {
if (typeof context === 'string') {
entry.context = context
} else {
logger.warn(`Unsupported type for context, expected 'string', got ${typeof context}`, msg)
}
}
if (limit) {
if (limit && typeof limit === 'number') {
entry.limit = limit
} else {
logger.warn(`Unsupported type for limit, expected 'number', got ${typeof limit}`, msg)
}
}
if (tags) {
if (tags && typeof tags === 'string') {
const tagArray = tags.split(',').map((s) => s.trim())
if (tagArray.length) {
entry.tags = tagArray
}
} else {
logger.warn(`Unsupported type for tags, expected Array, got ${typeof tags}`, msg)
}
}
}
}
results[id] = entry
} else {
logger.warn(
`Skipping message, unsupported type for defaultMessage, expected string, got ${typeof defaultMessage}`,
{
id,
msg,
}
)
}
}
return results
}
export function compile(msgs: LokaliseStructuredJson): CompiledEntries {
const results: CompiledEntries = {}
for (const [id, msg] of Object.entries(msgs)) {
results[id] = msg.translation
}
return results
}