Skip to content

Commit

Permalink
feat(@formatjs/cli): allow formatter to provide custom serialization …
Browse files Browse the repository at this point in the history
…fn, fix #4149
  • Loading branch information
longlho committed Sep 18, 2023
1 parent 2b5a4ed commit 6331408
Show file tree
Hide file tree
Showing 6 changed files with 381 additions and 407 deletions.
7 changes: 5 additions & 2 deletions packages/cli-lib/src/extract.ts
Expand Up @@ -198,7 +198,7 @@ export async function extract(
)
}

const formatter = await resolveBuiltinFormatter(opts.format)
const formatter: Formatter = await resolveBuiltinFormatter(opts.format)
const extractionResults = rawResults.filter((r): r is ExtractionResult => !!r)

const extractedMessages = new Map<string, MessageDescriptor>()
Expand Down Expand Up @@ -247,7 +247,10 @@ ${JSON.stringify(message, undefined, 2)}`
}
results[id] = msg
}
return stringify(formatter.format(results), {
if (typeof formatter.serialize === 'function') {
return formatter.serialize(formatter.format(results as any))
}
return stringify(formatter.format(results as any), {
space: 2,
cmp: formatter.compareMessages || undefined,
})
Expand Down
5 changes: 4 additions & 1 deletion packages/cli-lib/src/formatters/default.ts
@@ -1,5 +1,4 @@
import {MessageDescriptor} from '@formatjs/ts-transformer'

export type FormatFn<T = Record<string, MessageDescriptor>> = (
msgs: Record<string, MessageDescriptor>
) => T
Expand All @@ -8,6 +7,10 @@ export type CompileFn<T = Record<string, MessageDescriptor>> = (
msgs: T
) => Record<string, string>

export type SerializeFn<T = Record<string, MessageDescriptor>> = (
msgs: T
) => string

export const format: FormatFn = msgs => msgs

export const compile: CompileFn = msgs => {
Expand Down
5 changes: 3 additions & 2 deletions packages/cli-lib/src/formatters/index.ts
@@ -1,15 +1,16 @@
import * as defaultFormatter from './default'
import {FormatFn, CompileFn} from './default'
import {FormatFn, SerializeFn, CompileFn} from './default'
import * as transifex from './transifex'
import * as smartling from './smartling'
import * as simple from './simple'
import * as lokalise from './lokalise'
import * as crowdin from './crowdin'
import {Comparator} from 'json-stable-stringify'
import type {Comparator} from 'json-stable-stringify'
import {resolve} from 'path'
import {pathToFileURL} from 'url'

export interface Formatter {
serialize: SerializeFn
format: FormatFn
compile: CompileFn
compareMessages?: Comparator
Expand Down
2 changes: 1 addition & 1 deletion packages/cli-lib/src/formatters/smartling.ts
@@ -1,4 +1,4 @@
import {Comparator} from 'json-stable-stringify'
import type {Comparator} from 'json-stable-stringify'
import {CompileFn, FormatFn} from './default'

export interface SmartlingDirectives {
Expand Down

0 comments on commit 6331408

Please sign in to comment.