diff --git a/.gitignore b/.gitignore index b044dcd..73c21b5 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ ditto bin/ .env coverage +.DS_Store \ No newline at end of file diff --git a/lib/src/commands/pull.test.ts b/lib/src/commands/pull.test.ts index 215e3ea..fcd10ef 100644 --- a/lib/src/commands/pull.test.ts +++ b/lib/src/commands/pull.test.ts @@ -11,12 +11,15 @@ jest.mock("../http/client"); // Create a mock client with a mock 'get' method const mockHttpClient = { get: jest.fn(), + post: jest.fn(), }; // Make getHttpClient return the mock client (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); -// Test data factories +/********************************************************** + * HELPERS + **********************************************************/ const createMockTextItem = (overrides: Partial = {}) => ({ id: "text-1", text: "Plain text content", @@ -54,6 +57,108 @@ const createMockVariable = (overrides: any = {}) => ({ ...overrides, }); +const createMockData = () => { + // project-1 and project-2 each have at least one base text item + const baseTextItems = [ + createMockTextItem({ + projectId: "project-1", + variantId: null, + id: "text-1", + }), + createMockTextItem({ + projectId: "project-1", + variantId: null, + id: "text-2", + }), + createMockTextItem({ + projectId: "project-2", + variantId: null, + id: "text-3", + }), + ]; + + // project-1 and project-2 each have a variant-a text item + const variantATextItems = [ + createMockTextItem({ + projectId: "project-1", + variantId: "variant-a", + id: "text-4", + }), + createMockTextItem({ + projectId: "project-2", + variantId: "variant-a", + id: "text-5", + }), + ]; + + // Only project-1 has variant-b, so only project-1 should get a variant-b file + const variantBTextItems = [ + createMockTextItem({ + projectId: "project-1", + variantId: "variant-b", + id: "text-6", + }), + createMockTextItem({ + projectId: "project-1", + variantId: "variant-b", + id: "text-7", + }), + ]; + + const componentsBase = [ + createMockComponent({ + id: "comp-1", + variantId: null, + folderId: null, + }), + createMockComponent({ + id: "comp-2", + variantId: null, + folderId: "folder-1", + }), + createMockComponent({ + id: "comp-3", + variantId: null, + folderId: "folder-2", + }), + ]; + + const componentsVariantA = [ + createMockComponent({ + id: "comp-4", + variantId: "variant-a", + folderId: null, + }), + createMockComponent({ + id: "comp-5", + variantId: "variant-a", + folderId: "folder-1", + }), + ]; + + const componentsVariantB = [ + createMockComponent({ + id: "comp-6", + variantId: "variant-b", + folderId: null, + }), + createMockComponent({ + id: "comp-7", + variantId: "variant-b", + folderId: "folder-1", + }), + ]; + + return { + textItems: [...baseTextItems, ...variantATextItems, ...variantBTextItems], + components: [ + ...componentsBase, + ...componentsVariantA, + ...componentsVariantB, + ], + }; +}; + // Helper functions const setupMocks = ({ textItems = [], @@ -78,6 +183,44 @@ const setupMocks = ({ }); }; +const setupExportMocks = ({ + textItems, + components, + variables = [], +}: { + textItems: any; + components?: any; + variables?: any[]; +}) => { + mockHttpClient.get.mockImplementation((url: string, config?: any) => { + if (url.includes("/v2/textItems/export")) { + return Promise.resolve({ + data: textItems, + }); + } + if (url.includes("/v2/variables")) { + return Promise.resolve({ data: variables }); + } + if (url.includes("/v2/components/export")) { + return Promise.resolve({ + data: components, + }); + } + return Promise.resolve({ data: [] }); + }); +}; + +const setupSwiftDriverMocks = () => { + mockHttpClient.post.mockImplementation((url: string, config?: any) => { + if (url.includes("/v2/cli/swiftDriver")) { + return Promise.resolve({ + data: "import SwiftUI", + }); + } + return Promise.resolve({ data: [] }); + }); +}; + const parseJsonFile = (filepath: string) => { const content = fs.readFileSync(filepath, "utf-8"); return JSON.parse(content); @@ -97,6 +240,10 @@ const assertFilesCreated = (outputDir: string, expectedFiles: string[]) => { expect(actualFiles).toEqual(expectedFiles.toSorted()); }; +/********************************************************** + * E2E Tests + **********************************************************/ + describe("pull command - end-to-end tests", () => { // Create a temporary directory for tests let testDir: string; @@ -469,9 +616,135 @@ describe("pull command - end-to-end tests", () => { }); }); - describe("Output files", () => { + describe("iosLocales Feature", () => { + let outputOutDir: string; + + beforeEach(() => { + outputOutDir = path.join(testDir, "output-outDir"); + }); + + it("should not add swift file to directory if iosLocales is not configured", async () => { + fs.mkdirSync(outputOutDir, { recursive: true }); + setupMocks(createMockData()); + + appContext.setProjectConfig({ + projects: [{ id: "project-1" }, { id: "project-2" }], + iosLocales: [{ spanish: "es" }], + outputs: [ + { + format: "json", + outDir: outputOutDir, + }, + ], + }); + + await pull({}); + + const actualFiles = fs.readdirSync(outputOutDir).toSorted(); + expect(actualFiles.some((file) => file.includes(".swift"))).toEqual( + false + ); + }); + + it("should not add swift file to directory if iosLocales configured but no iOS output provided", async () => { + fs.mkdirSync(outputOutDir, { recursive: true }); + setupMocks(createMockData()); + + appContext.setProjectConfig({ + projects: [{ id: "project-1" }, { id: "project-2" }], + iosLocales: [{ spanish: "es" }], + outputs: [ + { + format: "json", + outDir: outputOutDir, + }, + ], + }); + + await pull({}); + + const actualFiles = fs.readdirSync(outputOutDir).toSorted(); + expect(actualFiles.some((file) => file.includes(".swift"))).toEqual( + false + ); + }); + + it("should add swift file to root directory if iosLocales is configured and an iOS output is provided", async () => { + fs.mkdirSync(outputOutDir, { recursive: true }); + const { textItems, components } = createMockData(); + setupExportMocks({ + textItems: textItems + .map((textItem) => `"${textItem.id}" = "${textItem.text}"`) + .join("\n\n"), + components: components + .map((component) => `"${component.id}" = "${component.text}"`) + .join("\n\n"), + }); + setupSwiftDriverMocks(); + + appContext.setProjectConfig({ + projects: [{ id: "project-1" }, { id: "project-2" }], + iosLocales: [{ spanish: "es" }], + outputs: [ + { + format: "ios-strings", + outDir: outputOutDir, + }, + ], + }); + + await pull({}); + + const actualFiles = fs.readdirSync("ditto").toSorted(); + expect(actualFiles.some((file) => file.includes(".swift"))).toBe(true); + + // should not be in output-specific dir + const outputDirFiles = fs.readdirSync(outputOutDir).toSorted(); + expect(outputDirFiles.some((file) => file.includes(".swift"))).toBe( + false + ); + }); + }); + + /********************************************************** + * OUTPUT TESTS - JSON + **********************************************************/ + describe("Output files - JSON", () => { + const expectedJSONFiles = [ + "project-1___base.json", + "project-1___variant-a.json", + "project-1___variant-b.json", + "project-2___base.json", + "project-2___variant-a.json", + "components___base.json", + "components___variant-a.json", + "components___variant-b.json", + "variables.json", + ]; + it("should create output files for each project and variant returned from the API", async () => { fs.mkdirSync(outputDir, { recursive: true }); + setupMocks(createMockData()); + appContext.setProjectConfig({ + projects: [], + components: {}, + outputs: [ + { + format: "json", + outDir: outputDir, + }, + ], + }); + + await pull({}); + + // Verify a file was created for each project and variant present in the (mocked) API response + assertFilesCreated(outputDir, expectedJSONFiles); + }); + + it("should create index.js file when framework: i18next provided", async () => { + fs.mkdirSync(outputDir, { recursive: true }); + setupMocks(createMockData()); appContext.setProjectConfig({ projects: [], @@ -480,127 +753,193 @@ describe("pull command - end-to-end tests", () => { { format: "json", outDir: outputDir, + framework: "i18next", + }, + ], + }); + + await pull({}); + + assertFilesCreated(outputDir, [...expectedJSONFiles, "index.js"]); + }); + + it("should create index.js file when framework: vue-18n provided", async () => { + fs.mkdirSync(outputDir, { recursive: true }); + setupMocks(createMockData()); + + appContext.setProjectConfig({ + projects: [], + components: {}, + outputs: [ + { + format: "json", + outDir: outputDir, + framework: "i18next", + }, + ], + }); + + await pull({}); + + assertFilesCreated(outputDir, [...expectedJSONFiles, "index.js"]); + }); + }); + + /********************************************************** + * OUTPUT TESTS - ios-strings + **********************************************************/ + describe("Output files - ios-strings", () => { + it("should create correct output files for each project and variant returned from the API", async () => { + fs.mkdirSync(outputDir, { recursive: true }); + + appContext.setProjectConfig({ + components: {}, + outputs: [ + { + format: "ios-strings", + outDir: outputDir, + projects: [{ id: "project-1" }, { id: "project-2" }], + variants: [ + { id: "base" }, + { id: "variant-a" }, + { id: "variant-b" }, + ], }, ], }); + // create exports like so + /* + "this-is-a-ditto-text-item" = "No its not"; + + "this-is-a-text-layer-on-figma" = "This is a Ditto text item (LinkedNode)"; + + "update-preferences" = "Update preferences"; + */ + const { textItems, components } = createMockData(); + setupExportMocks({ + textItems: textItems + .map((textItem) => `"${textItem.id}" = "${textItem.text}"`) + .join("\n\n"), + components: components + .map((component) => `"${component.id}" = "${component.text}"`) + .join("\n\n"), + }); + + await pull({}); - // project-1 and project-2 each have at least one base text item - const baseTextItems = [ - createMockTextItem({ - projectId: "project-1", - variantId: null, - id: "text-1", - }), - createMockTextItem({ - projectId: "project-1", - variantId: null, - id: "text-2", - }), - createMockTextItem({ - projectId: "project-2", - variantId: null, - id: "text-3", - }), - ]; - - // project-1 and project-2 each have a variant-a text item - const variantATextItems = [ - createMockTextItem({ - projectId: "project-1", - variantId: "variant-a", - id: "text-4", - }), - createMockTextItem({ - projectId: "project-2", - variantId: "variant-a", - id: "text-5", - }), - ]; - - // Only project-1 has variant-b, so only project-1 should get a variant-b file - const variantBTextItems = [ - createMockTextItem({ - projectId: "project-1", - variantId: "variant-b", - id: "text-6", - }), - createMockTextItem({ - projectId: "project-1", - variantId: "variant-b", - id: "text-7", - }), - ]; - - const componentsBase = [ - createMockComponent({ - id: "comp-1", - variantId: null, - folderId: null, - }), - createMockComponent({ - id: "comp-2", - variantId: null, - folderId: "folder-1", - }), - createMockComponent({ - id: "comp-3", - variantId: null, - folderId: "folder-2", - }), - ]; - - const componentsVariantA = [ - createMockComponent({ - id: "comp-4", - variantId: "variant-a", - folderId: null, - }), - createMockComponent({ - id: "comp-5", - variantId: "variant-a", - folderId: "folder-1", - }), - ]; - - const componentsVariantB = [ - createMockComponent({ - id: "comp-6", - variantId: "variant-b", - folderId: null, - }), - createMockComponent({ - id: "comp-7", - variantId: "variant-b", - folderId: "folder-1", - }), - ]; - - setupMocks({ - textItems: [ - ...baseTextItems, - ...variantATextItems, - ...variantBTextItems, + // Verify a file was created for each project and variant present in the (mocked) API response + assertFilesCreated(outputDir, [ + "project-1___base.strings", + "project-1___variant-a.strings", + "project-1___variant-b.strings", + "project-2___base.strings", + "project-2___variant-a.strings", + "project-2___variant-b.strings", + "components___base.strings", + "components___variant-a.strings", + "components___variant-b.strings", + ]); + }); + }); + + /********************************************************** + * OUTPUT TESTS - ios-strings + **********************************************************/ + describe("Output files - ios-stringsdict", () => { + it("should create correct output files for each project and variant returned from the API", async () => { + fs.mkdirSync(outputDir, { recursive: true }); + + appContext.setProjectConfig({ + components: {}, + outputs: [ + { + format: "ios-stringsdict", + outDir: outputDir, + projects: [{ id: "project-1" }, { id: "project-2" }], + variants: [ + { id: "base" }, + { id: "variant-a" }, + { id: "variant-b" }, + ], + }, ], - components: [ - ...componentsBase, - ...componentsVariantA, - ...componentsVariantB, + }); + const { textItems, components } = createMockData(); + setupExportMocks({ + // Todo: once we have plurals let's make some real mock data here + textItems: textItems.join("\n"), + components: components.join("\n"), + }); + + await pull({}); + + // Verify a file was created for each project and variant present in the (mocked) API response + assertFilesCreated(outputDir, [ + "project-1___base.stringsdict", + "project-1___variant-a.stringsdict", + "project-1___variant-b.stringsdict", + "project-2___base.stringsdict", + "project-2___variant-a.stringsdict", + "project-2___variant-b.stringsdict", + "components___base.stringsdict", + "components___variant-a.stringsdict", + "components___variant-b.stringsdict", + ]); + }); + }); + + /********************************************************** + * OUTPUT TESTS - ios-strings + **********************************************************/ + describe("Output files - Android XML", () => { + it("should create correct output files for each project and variant returned from the API", async () => { + fs.mkdirSync(outputDir, { recursive: true }); + + appContext.setProjectConfig({ + components: {}, + outputs: [ + { + format: "android", + outDir: outputDir, + projects: [{ id: "project-1" }, { id: "project-2" }], + variants: [ + { id: "base" }, + { id: "variant-a" }, + { id: "variant-b" }, + ], + }, ], }); + const { textItems, components } = createMockData(); + setupExportMocks({ + textItems: textItems + .map( + (ti) => + `${ti.text}` + ) + .join("\n"), + components: components + .map( + (cmp) => + `${cmp.text}` + ) + .join("\n"), + }); + await pull({}); // Verify a file was created for each project and variant present in the (mocked) API response assertFilesCreated(outputDir, [ - "project-1___base.json", - "project-1___variant-a.json", - "project-1___variant-b.json", - "project-2___base.json", - "project-2___variant-a.json", - "components___base.json", - "components___variant-a.json", - "components___variant-b.json", - "variables.json", + "project-1___base.xml", + "project-1___variant-a.xml", + "project-1___variant-b.xml", + "project-2___base.xml", + "project-2___variant-a.xml", + "project-2___variant-b.xml", + "components___base.xml", + "components___variant-a.xml", + "components___variant-b.xml", ]); }); }); diff --git a/lib/src/commands/pull.ts b/lib/src/commands/pull.ts index 56daea2..18d10c2 100644 --- a/lib/src/commands/pull.ts +++ b/lib/src/commands/pull.ts @@ -1,9 +1,31 @@ import appContext from "../utils/appContext"; +import logger from "../utils/logger"; +import getSwiftDriverFile from "../utils/getSwiftDriverFile"; +import { writeFile } from "../utils/fileSystem"; import formatOutput from "../formatters"; import { CommandMetaFlags } from "../http/types"; +const IOS_FORMATS = new Set(["ios-strings", "ios-stringsdict"]); + export const pull = async (meta: CommandMetaFlags) => { + const hasIOSLocales = (appContext.projectConfig.iosLocales ?? []).length > 0; + const hasIOSFormat = appContext.selectedProjectConfigOutputs.some((output) => + IOS_FORMATS.has(output.format) + ); + const shouldGenerateSwiftFile = hasIOSFormat && hasIOSLocales; + for (const output of appContext.selectedProjectConfigOutputs) { await formatOutput(output, appContext.projectConfig, meta); } + + if (shouldGenerateSwiftFile) { + const swiftDriverFile = await getSwiftDriverFile( + meta, + appContext.projectConfig + ); + await writeFile(swiftDriverFile.fullPath, swiftDriverFile.formattedContent); + logger.writeLine( + `Successfully saved to ${logger.info(swiftDriverFile.fullPath)}` + ); + } }; diff --git a/lib/src/formatters/android.test.ts b/lib/src/formatters/android.test.ts new file mode 100644 index 0000000..6d5b3d4 --- /dev/null +++ b/lib/src/formatters/android.test.ts @@ -0,0 +1,119 @@ +import AndroidOutputFile from "./shared/fileTypes/AndroidOutputFile"; +import { Output } from "../outputs"; +import { ProjectConfigYAML } from "../services/projectConfig"; +import { CommandMetaFlags } from "../http/types"; +import AndroidXMLFormatter from "./android"; + +// @ts-ignore +class TestAndroidXMLFormatter extends AndroidXMLFormatter { + public createOutputFilePublic( + filePrefix: string, + fileName: string, + variantId: string, + content: string + ) { + // @ts-ignore + return super.createOutputFile(filePrefix, fileName, variantId, content); + } + + public getExportFormat() { + // @ts-ignore + return this.exportFormat; + } + + public getOutputFiles() { + // @ts-ignore + return this.outputFiles; + } +} + +describe("AndroidXMLFormatter", () => { + // @ts-ignore + const createMockOutput = (overrides: Partial = {}): Output => ({ + format: "android", + ...overrides, + }); + + const createMockProjectConfig = ( + overrides: Partial = {} + ): ProjectConfigYAML => ({ + projects: [], + variants: [], + components: { + folders: [], + }, + outputs: [ + { + format: "android", + } as any, + ], + ...overrides, + }); + + const createMockMeta = (): CommandMetaFlags => ({}); + + it("has export format of android", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestAndroidXMLFormatter( + output, + projectConfig, + createMockMeta() + ); + + expect(formatter.getExportFormat()).toBe("android"); + }); + + it("creates AndroidOutputFile with correct metadata and content", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestAndroidXMLFormatter( + output, + projectConfig, + createMockMeta() + ); + + const projectId = "cli-testing-project"; + const fileName = `${projectId}___spanish`; + const variantId = "spanish"; + const content = "file-content"; + + formatter.createOutputFilePublic(projectId, fileName, variantId, content); + + const files = formatter.getOutputFiles(); + const file = files[fileName] as AndroidOutputFile<{ + variantId: string; + }>; + + expect(file).toBeInstanceOf(AndroidOutputFile); + expect(file.fullPath).toBe( + "/test/output/cli-testing-project___spanish.xml" + ); + expect(file.metadata).toEqual({ variantId: "spanish" }); + expect(file.content).toBe("file-content"); + }); + + it("defaults variantId metadata to 'base' when variantId is falsy", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestAndroidXMLFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filePrefix = "cli-testing-project"; + const fileName = `${filePrefix}___base`; + const content = "base-content"; + + formatter.createOutputFilePublic(filePrefix, fileName, "" as any, content); + + const files = formatter.getOutputFiles(); + const file = files[fileName] as AndroidOutputFile<{ + variantId: string; + }>; + + expect(file.metadata).toEqual({ variantId: "base" }); + expect(file.content).toBe("base-content"); + }); +}); diff --git a/lib/src/formatters/android.ts b/lib/src/formatters/android.ts new file mode 100644 index 0000000..4cd68d1 --- /dev/null +++ b/lib/src/formatters/android.ts @@ -0,0 +1,24 @@ +import BaseExportFormatter from "./shared/baseExport"; +import AndroidOutputFile from "./shared/fileTypes/AndroidOutputFile"; +import { PullQueryParams } from "../http/types"; +import { BASE_VARIANT_ID } from "../utils/constants"; + +export default class AndroidXMLFormatter extends BaseExportFormatter< + AndroidOutputFile<{ variantId: string }> +> { + protected exportFormat: PullQueryParams["format"] = "android"; + + protected createOutputFile( + _filePrefix: string, + fileName: string, + variantId: string, + content: string + ): void { + this.outputFiles[fileName] ??= new AndroidOutputFile({ + filename: fileName, + path: this.outDir, + metadata: { variantId: variantId || BASE_VARIANT_ID }, + content: content, + }); + } +} diff --git a/lib/src/formatters/index.ts b/lib/src/formatters/index.ts index d02e8d8..a6da286 100644 --- a/lib/src/formatters/index.ts +++ b/lib/src/formatters/index.ts @@ -1,6 +1,10 @@ import { CommandMetaFlags } from "../http/types"; import { Output } from "../outputs"; import { ProjectConfigYAML } from "../services/projectConfig"; +import AndroidXMLFormatter from "./android"; +import JSONICUFormatter from "./jsonICU"; +import IOSStringsFormatter from "./iosStrings"; +import IOSStringsDictFormatter from "./iosStringsDict"; import JSONFormatter from "./json"; export default function formatOutput( @@ -8,10 +12,19 @@ export default function formatOutput( projectConfig: ProjectConfigYAML, meta: CommandMetaFlags ) { - switch (output.format) { + const format = output.format; + switch (format) { case "json": return new JSONFormatter(output, projectConfig, meta).format(); + case "android": + return new AndroidXMLFormatter(output, projectConfig, meta).format(); + case "ios-strings": + return new IOSStringsFormatter(output, projectConfig, meta).format(); + case "ios-stringsdict": + return new IOSStringsDictFormatter(output, projectConfig, meta).format(); + case "json_icu": + return new JSONICUFormatter(output, projectConfig, meta).format(); default: - throw new Error(`Unsupported output format: ${output}`); + throw new Error(`Unsupported output format: ${format}`); } } diff --git a/lib/src/formatters/iosStrings.test.ts b/lib/src/formatters/iosStrings.test.ts new file mode 100644 index 0000000..b51ae46 --- /dev/null +++ b/lib/src/formatters/iosStrings.test.ts @@ -0,0 +1,276 @@ +import IOSStringsOutputFile from "./shared/fileTypes/IOSStringsOutputFile"; +import { Output } from "../outputs"; +import { ProjectConfigYAML } from "../services/projectConfig"; +import { CommandMetaFlags } from "../http/types"; +import IOSStringsFormatter from "./iosStrings"; + +jest.mock("../utils/appContext", () => ({ + __esModule: true, + default: { + outDir: "/mock/app/context/outDir", + }, +})); + +// @ts-ignore +class TestIOSStringsFormatter extends IOSStringsFormatter { + public createOutputFilePublic( + filePrefix: string, + fileName: string, + variantId: string, + content: string + ) { + // @ts-ignore + return super.createOutputFile(filePrefix, fileName, variantId, content); + } + + public getExportFormat() { + // @ts-ignore + return this.exportFormat; + } + + public getOutputFiles() { + // @ts-ignore + return this.outputFiles; + } + + public getLocalesPath(variantId: string) { + // @ts-ignore + return super.getLocalesPath(variantId); + } + + public getVariantLocale(variantId: string) { + // @ts-ignore + return super.getVariantLocale(variantId); + } +} + +describe("IOSStringsFormatter", () => { + // @ts-ignore + const createMockOutput = (overrides: Partial = {}): Output => ({ + format: "ios-strings", + ...overrides, + }); + + const createMockProjectConfig = ( + overrides: Partial = {} + ): ProjectConfigYAML => ({ + projects: [], + variants: [], + components: { + folders: [], + }, + outputs: [ + { + format: "ios-strings", + } as any, + ], + ...overrides, + }); + + const createMockMeta = (): CommandMetaFlags => ({}); + + it("has export format of ios-strings", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + expect(formatter.getExportFormat()).toBe("ios-strings"); + }); + + it("creates IOSStringsOutputFile with correct metadata and content", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filePrefix = "cli-testing-project"; + const fileName = `${filePrefix}___spanish`; + const variantId = "spanish"; + const content = "file-content"; + + formatter.createOutputFilePublic(filePrefix, fileName, variantId, content); + + const files = formatter.getOutputFiles(); + const file = files[fileName] as IOSStringsOutputFile<{ + variantId: string; + }>; + + expect(file).toBeInstanceOf(IOSStringsOutputFile); + expect(file.fullPath).toBe( + "/test/output/cli-testing-project___spanish.strings" + ); + expect(file.metadata).toEqual({ variantId: "spanish" }); + expect(file.content).toBe("file-content"); + }); + + it("defaults variantId metadata to 'base' when variantId is falsy", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filePrefix = "cli-testing-project"; + const fileName = `${filePrefix}___base`; + const content = "base-content"; + + formatter.createOutputFilePublic(filePrefix, fileName, "" as any, content); + + const files = formatter.getOutputFiles(); + const file = files[fileName] as IOSStringsOutputFile<{ + variantId: string; + }>; + + expect(file.metadata).toEqual({ variantId: "base" }); + expect(file.content).toBe("base-content"); + }); + + describe("getVariantLocale", () => { + it("should return undefined when iosLocales is not configured", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: undefined, + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getVariantLocale("base"); + + expect(result).toBe(undefined); + }); + + it("should return undefined when iosLocales is configured but variant doesn't have match", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { spanish: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getVariantLocale("japanese"); + + expect(result).toBe(undefined); + }); + + it("should return matching locale when iosLocales is configured and variant has a match", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { spanish: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getVariantLocale("spanish"); + + expect(result).toEqual({ spanish: "es" }); + }); + }); + + describe("getLocalesPath", () => { + it("should return output outDir when iosLocales is not configured", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: undefined, + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("base"); + + expect(result).toBe("/test/output"); + }); + + it("should return output outDir when iosLocales is empty array", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: undefined, + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("base"); + + expect(result).toBe("/test/output"); + }); + + it("should return locale path when iosLocales is configured and variantId matches", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { variant1: "es" }, { variant2: "fr" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("variant1"); + + expect(result).toBe("/mock/app/context/outDir/es.lproj"); + }); + + it("should return output's outDir when iosLocales is configured but variantId does not exist in iosLocales map", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { variant1: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("variant2"); + + expect(result).toBe("/test/output"); + }); + + it("should return locale path for base variant when configured", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { variant1: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("base"); + + expect(result).toBe("/mock/app/context/outDir/en.lproj"); + }); + }); +}); diff --git a/lib/src/formatters/iosStrings.ts b/lib/src/formatters/iosStrings.ts new file mode 100644 index 0000000..cecf20f --- /dev/null +++ b/lib/src/formatters/iosStrings.ts @@ -0,0 +1,53 @@ +import BaseExportFormatter from "./shared/baseExport"; +import IOSStringsOutputFile from "./shared/fileTypes/IOSStringsOutputFile"; +import { PullQueryParams } from "../http/types"; +import appContext from "../utils/appContext"; +import { BASE_VARIANT_ID } from "../utils/constants"; + +export default class IOSStringsFormatter extends BaseExportFormatter< + IOSStringsOutputFile<{ variantId: string }> +> { + protected exportFormat: PullQueryParams["format"] = "ios-strings"; + + protected createOutputFile( + filePrefix: string, + fileName: string, + variantId: string, + content: string + ): void { + const matchingLocale = this.getVariantLocale(variantId); + this.outputFiles[fileName] ??= new IOSStringsOutputFile({ + filename: matchingLocale ? filePrefix : fileName, // don't append "___"" when in locale directory + path: this.getLocalesPath(variantId), + metadata: { variantId: variantId || BASE_VARIANT_ID }, + content: content, + }); + } + + private getVariantLocale( + variantId: string + ): Record | undefined { + if (this.projectConfig.iosLocales) { + return this.projectConfig.iosLocales.find( + (localePair) => localePair[variantId] + ); + } + return undefined; + } + + /** + * If config.iosLocales configured, writes .strings files to root project outDir instead of the specific output + * This is because with both .strings and .stringsdict configured the locale files can get "overwritten" as far as + * the Ditto.swift file is concerned. We need to have all .strings and .stringsdict files in one directory + * + * Any variants not-configured in the iosLocales will get written to the output's outDir as expected (if that output outDir is configured) + */ + private getLocalesPath(variantId: string) { + let path = this.outDir; + const variantLocale = this.getVariantLocale(variantId); + if (variantLocale) { + path = `${appContext.outDir}/${variantLocale[variantId]}.lproj`; + } + return path; + } +} diff --git a/lib/src/formatters/iosStringsDict.test.ts b/lib/src/formatters/iosStringsDict.test.ts new file mode 100644 index 0000000..7774165 --- /dev/null +++ b/lib/src/formatters/iosStringsDict.test.ts @@ -0,0 +1,277 @@ +import IOSStringsDictFormatter from "./iosStringsDict"; +import IOSStringsDictOutputFile from "./shared/fileTypes/IOSStringsDictOutputFile"; +import { Output } from "../outputs"; +import { ProjectConfigYAML } from "../services/projectConfig"; +import { CommandMetaFlags } from "../http/types"; + +jest.mock("../utils/appContext", () => ({ + __esModule: true, + default: { + outDir: "/mock/app/context/outDir", + }, +})); + +// @ts-ignore +class TestIOSStringsDictFormatter extends IOSStringsDictFormatter { + public createOutputFilePublic( + filePrefix: string, + fileName: string, + variantId: string, + content: string + ) { + // @ts-ignore + return super.createOutputFile(filePrefix, fileName, variantId, content); + } + + public getExportFormat() { + // @ts-ignore + return this.exportFormat; + } + + public getOutputFiles() { + // @ts-ignore + return this.outputFiles; + } + + public getVariantLocale(variantId: string) { + // @ts-ignore + return super.getVariantLocale(variantId); + } + + public getLocalesPath(variantId: string) { + // @ts-ignore + return super.getLocalesPath(variantId); + } +} + +describe("IOSStringsDictFormatter", () => { + // @ts-ignore + const createMockOutput = (overrides: Partial = {}): Output => ({ + format: "ios-stringsdict", + ...overrides, + }); + + const createMockProjectConfig = ( + overrides: Partial = {} + ): ProjectConfigYAML => ({ + projects: [], + variants: [], + components: { + folders: [], + }, + outputs: [ + { + // Minimal valid output config for this formatter + format: "ios-stringsdict", + } as any, + ], + ...overrides, + }); + + const createMockMeta = (): CommandMetaFlags => ({}); + + it("has export format of ios-stringsdict", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + expect(formatter.getExportFormat()).toBe("ios-stringsdict"); + }); + + it("creates IOSStringsDictOutputFile with correct metadata and content", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filePrefix = "cli-testing-project"; + const fileName = `${filePrefix}___spanish`; + const variantId = "spanish"; + const content = "file-content"; + + formatter.createOutputFilePublic(filePrefix, fileName, variantId, content); + + const files = formatter.getOutputFiles(); + const file = files[fileName] as IOSStringsDictOutputFile<{ + variantId: string; + }>; + + expect(file).toBeInstanceOf(IOSStringsDictOutputFile); + expect(file.fullPath).toBe( + "/test/output/cli-testing-project___spanish.stringsdict" + ); + expect(file.metadata).toEqual({ variantId: "spanish" }); + expect(file.content).toBe("file-content"); + }); + + it("defaults variantId metadata to 'base' when variantId is falsy", () => { + const output = createMockOutput({ outDir: "/test/output" }); + const projectConfig = createMockProjectConfig(); + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filePrefix = "cli-testing-project"; + const fileName = `${filePrefix}___base`; + const content = "base-content"; + + formatter.createOutputFilePublic(filePrefix, fileName, "" as any, content); + + const files = formatter.getOutputFiles(); + const file = files[fileName] as IOSStringsDictOutputFile<{ + variantId: string; + }>; + + expect(file.metadata).toEqual({ variantId: "base" }); + expect(file.content).toBe("base-content"); + }); + + describe("getVariantLocale", () => { + it("should return undefined when iosLocales is not configured", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: undefined, + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getVariantLocale("base"); + + expect(result).toBe(undefined); + }); + + it("should return undefined when iosLocales is configured but variant doesn't have match", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { spanish: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getVariantLocale("japanese"); + + expect(result).toBe(undefined); + }); + + it("should return matching locale when iosLocales is configured and variant has a match", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { spanish: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getVariantLocale("spanish"); + + expect(result).toEqual({ spanish: "es" }); + }); + }); + + describe("getLocalesPath", () => { + it("should return output outDir when iosLocales is not configured", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: undefined, + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("base"); + + expect(result).toBe("/test/output"); + }); + + it("should return output outDir when iosLocales is empty array", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: undefined, + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("base"); + + expect(result).toBe("/test/output"); + }); + + it("should return locale path when iosLocales is configured and variantId matches", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { variant1: "es" }, { variant2: "fr" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("variant1"); + + expect(result).toBe("/mock/app/context/outDir/es.lproj"); + }); + + it("should return output's outDir when iosLocales is configured but variantId does not exist in iosLocales map", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { variant1: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("variant2"); + + expect(result).toBe("/test/output"); + }); + + it("should return locale path for base variant when configured", () => { + const projectConfig = createMockProjectConfig({ + iosLocales: [{ base: "en" }, { variant1: "es" }], + }); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestIOSStringsDictFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = formatter.getLocalesPath("base"); + + expect(result).toBe("/mock/app/context/outDir/en.lproj"); + }); + }); +}); diff --git a/lib/src/formatters/iosStringsDict.ts b/lib/src/formatters/iosStringsDict.ts new file mode 100644 index 0000000..bf952f3 --- /dev/null +++ b/lib/src/formatters/iosStringsDict.ts @@ -0,0 +1,52 @@ +import BaseExportFormatter from "./shared/baseExport"; +import IOSStringsDictOutputFile from "./shared/fileTypes/IOSStringsDictOutputFile"; +import { PullQueryParams } from "../http/types"; +import appContext from "../utils/appContext"; +import { BASE_VARIANT_ID } from "../utils/constants"; +export default class IOSStringsDictFormatter extends BaseExportFormatter< + IOSStringsDictOutputFile<{ variantId: string }> +> { + protected exportFormat: PullQueryParams["format"] = "ios-stringsdict"; + + protected createOutputFile( + filePrefix: string, + fileName: string, + variantId: string, + content: string + ): void { + const matchingLocale = this.getVariantLocale(variantId); + this.outputFiles[fileName] ??= new IOSStringsDictOutputFile({ + filename: matchingLocale ? filePrefix : fileName, // don't append "___"" when in locale directory + path: this.getLocalesPath(variantId), + metadata: { variantId: variantId || BASE_VARIANT_ID }, + content: content, + }); + } + + private getVariantLocale( + variantId: string + ): Record | undefined { + if (this.projectConfig.iosLocales) { + return this.projectConfig.iosLocales.find( + (localePair) => localePair[variantId] + ); + } + return undefined; + } + + /** + * If config.iosLocales configured, writes .strings files to root project outDir instead of the specific output + * This is because with both .strings and .stringsdict configured the locale files can get "overwritten" as far as + * the Ditto.swift file is concerned. We need to have all .strings and .stringsdict files in one directory + * + * Any variants not-configured in the iosLocales will get written to the output's outDir as expected (if that output outDir is configured) + */ + private getLocalesPath(variantId: string) { + let path = this.outDir; + const variantLocale = this.getVariantLocale(variantId); + if (variantLocale) { + path = `${appContext.outDir}/${variantLocale[variantId]}.lproj`; + } + return path; + } +} diff --git a/lib/src/formatters/json.ts b/lib/src/formatters/json.ts index f52ebab..42ace58 100644 --- a/lib/src/formatters/json.ts +++ b/lib/src/formatters/json.ts @@ -1,12 +1,13 @@ -import fetchText from "../http/textItems"; -import { Component, ComponentsResponse, isTextItem, PullFilters, PullQueryParams, TextItem, TextItemsResponse } from "../http/types"; -import fetchComponents from "../http/components"; +import { fetchTextItems } from "../http/textItems"; +import { Component, ComponentsResponse, isTextItem, TextItem, TextItemsResponse } from "../http/types"; +import { fetchComponents } from "../http/components"; import fetchVariables, { Variable } from "../http/variables"; import BaseFormatter from "./shared/base"; import OutputFile from "./shared/fileTypes/OutputFile"; import JSONOutputFile from "./shared/fileTypes/JSONOutputFile"; import { applyMixins } from "./shared"; import { getFrameworkProcessor } from "./frameworks/json"; +import { BASE_VARIANT_ID } from "../utils/constants"; type JSONAPIData = { textItems: TextItemsResponse; @@ -14,10 +15,8 @@ type JSONAPIData = { variablesById: Record; }; -type RequestType = "textItem" | "component"; - export default class JSONFormatter extends applyMixins( - BaseFormatter) { + BaseFormatter, JSONAPIData>) { protected async fetchAPIData() { const textItems = await this.fetchTextItems(); @@ -32,7 +31,7 @@ export default class JSONFormatter extends applyMixins( return { textItems, variablesById, components }; } - protected async transformAPIData(data: JSONAPIData) { + protected transformAPIData(data: JSONAPIData) { for (let i = 0; i < data.textItems.length; i++) { const textItem = data.textItems[i]; this.transformAPITextEntity(textItem, data.variablesById); @@ -44,13 +43,13 @@ export default class JSONFormatter extends applyMixins( } let results: OutputFile[] = [ - ...Object.values(this.outputJsonFiles), + ...Object.values(this.outputFiles), this.variablesOutputFile, ] if (this.output.framework) { // process framework - results.push(...getFrameworkProcessor(this.output).process(this.outputJsonFiles)); + results.push(...getFrameworkProcessor(this.output).process(this.outputFiles)); } return results; @@ -62,12 +61,12 @@ export default class JSONFormatter extends applyMixins( * @param variablesById Mapping of devID <> variable data returned from API response. */ private transformAPITextEntity(textEntity: TextItem | Component, variablesById: Record) { - const fileName = isTextItem(textEntity) ? `${textEntity.projectId}___${textEntity.variantId || "base"}` : `components___${textEntity.variantId || "base"}`; + const fileName = isTextItem(textEntity) ? `${textEntity.projectId}___${textEntity.variantId || BASE_VARIANT_ID}` : `components___${textEntity.variantId || BASE_VARIANT_ID}`; - this.outputJsonFiles[fileName] ??= new JSONOutputFile({ + this.outputFiles[fileName] ??= new JSONOutputFile({ filename: fileName, path: this.outDir, - metadata: { variantId: textEntity.variantId || "base" }, + metadata: { variantId: textEntity.variantId || BASE_VARIANT_ID }, }); // Use richText if available and configured, otherwise use text @@ -78,79 +77,13 @@ export default class JSONFormatter extends applyMixins( ? textEntity.richText : textEntity.text; - this.outputJsonFiles[fileName].content[textEntity.id] = textValue; + this.outputFiles[fileName].content[textEntity.id] = textValue; for (const variableId of textEntity.variableIds) { const variable = variablesById[variableId]; this.variablesOutputFile.content[variableId] = variable.data; } } - private generateTextItemPullFilter() { - let filters: PullFilters = { - projects: this.projectConfig.projects, - variants: this.projectConfig.variants, - statuses: this.projectConfig.statuses - }; - - if (this.output.projects) { - filters.projects = this.output.projects; - } - - if (this.output.variants) { - filters.variants = this.output.variants; - } - - if (this.output.statuses) { - filters.statuses = this.output.statuses; - } - - return filters; - } - - private generateComponentPullFilter() { - let filters: PullFilters = { - ...(this.projectConfig.components?.folders && { folders: this.projectConfig.components.folders }), - variants: this.projectConfig.variants, - statuses: this.projectConfig.statuses - }; - - if (this.output.components) { - filters.folders = this.output.components?.folders; - } - - if (this.output.variants) { - filters.variants = this.output.variants; - } - - if (this.output.statuses) { - filters.statuses = this.output.statuses; - } - - return filters; - } - - /** - * Returns the query parameters for the fetchText API request - */ - private generateQueryParams(requestType: RequestType) { - const filter = requestType === "textItem" ? this.generateTextItemPullFilter() : this.generateComponentPullFilter(); - - let params: PullQueryParams = { - filter: JSON.stringify(filter), - }; - - if (this.projectConfig.richText) { - params.richText = this.projectConfig.richText; - } - - if (this.output.richText) { - params.richText = this.output.richText; - } - - - return params; - } - /** * Fetches text item data via API. * Skips the fetch request if projects field is not specified in config. @@ -159,8 +92,8 @@ export default class JSONFormatter extends applyMixins( */ private async fetchTextItems() { if (!this.projectConfig.projects && !this.output.projects) return []; - - return await fetchText(this.generateQueryParams("textItem"), this.meta); + const filters = super.generateTextItemPullFilter(); + return await fetchTextItems(super.generateQueryParams(filters), this.meta); } /** @@ -171,8 +104,8 @@ export default class JSONFormatter extends applyMixins( */ private async fetchComponents() { if (!this.projectConfig.components && !this.output.components) return []; - - return await fetchComponents(this.generateQueryParams("component"), this.meta); + const filters = super.generateComponentPullFilter(); + return await fetchComponents(super.generateQueryParams(filters), this.meta); } private async fetchVariables() { diff --git a/lib/src/formatters/jsonICU.ts b/lib/src/formatters/jsonICU.ts new file mode 100644 index 0000000..e58761e --- /dev/null +++ b/lib/src/formatters/jsonICU.ts @@ -0,0 +1,24 @@ +import BaseExportFormatter from "./shared/baseExport"; +import ICUOutputFile from "./shared/fileTypes/ICUOutputFile"; +import { PullQueryParams } from "../http/types"; +import { BASE_VARIANT_ID } from "../utils/constants"; + +export default class JSONICUFormatter extends BaseExportFormatter< + ICUOutputFile<{ variantId: string }> +> { + protected exportFormat: PullQueryParams["format"] = "json_icu"; + + protected createOutputFile( + _filePrefix: string, + fileName: string, + variantId: string, + content: Record + ): void { + this.outputFiles[fileName] ??= new ICUOutputFile({ + filename: fileName, + path: this.outDir, + metadata: { variantId: variantId || BASE_VARIANT_ID }, + content: content, + }); + } +} diff --git a/lib/src/formatters/shared/base.test.ts b/lib/src/formatters/shared/base.test.ts new file mode 100644 index 0000000..4338928 --- /dev/null +++ b/lib/src/formatters/shared/base.test.ts @@ -0,0 +1,402 @@ +import BaseFormatter from "./base"; +import { Output } from "../../outputs"; +import { ProjectConfigYAML } from "../../services/projectConfig"; +import { CommandMetaFlags, PullFilters } from "../../http/types"; +import JSONOutputFile from "./fileTypes/JSONOutputFile"; + +// fake test class to expose private methods +// @ts-ignore +class TestBaseFormatter extends BaseFormatter { + public generateTextItemPullFilter() { + return super["generateTextItemPullFilter"](); + } + + public generateComponentPullFilter() { + return super["generateComponentPullFilter"](); + } + + public generateQueryParams(filters: PullFilters = {}) { + return super.generateQueryParams(filters); + } +} + +describe("BaseFormatter", () => { + const createMockOutput = (overrides: Partial = {}): Output => ({ + format: "json", + ...overrides, + }); + + const createMockProjectConfig = ( + overrides: Partial = {} + ): ProjectConfigYAML => ({ + projects: [], + variants: [], + components: { + folders: [], + }, + outputs: [ + { + format: "json", + }, + ], + ...overrides, + }); + + const createMockMeta = (): CommandMetaFlags => ({}); + + /*********************************************************** + * generateTextItemPullFilter + ***********************************************************/ + + describe("generateTextItemPullFilter", () => { + it("should use projectConfig projects and variants when output does not override", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }, { id: "project2" }], + variants: [{ id: "variant1" }], + }); + const output = createMockOutput(); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filters = formatter.generateTextItemPullFilter(); + + expect(filters).toEqual({ + projects: [{ id: "project1" }, { id: "project2" }], + variants: [{ id: "variant1" }], + }); + }); + + it("should override projects with output.projects when provided", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }, { id: "project2" }], + variants: [{ id: "variant1" }], + }); + const output = createMockOutput({ + projects: [{ id: "project3" }], + }); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filters = formatter.generateTextItemPullFilter(); + + expect(filters).toEqual({ + projects: [{ id: "project3" }], + variants: [{ id: "variant1" }], + }); + }); + + it("should override variants with output.variants when provided", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + variants: [{ id: "variant1" }], + }); + const output = createMockOutput({ + variants: [{ id: "variant2" }, { id: "variant3" }], + }); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filters = formatter.generateTextItemPullFilter(); + + expect(filters).toEqual({ + projects: [{ id: "project1" }], + variants: [{ id: "variant2" }, { id: "variant3" }], + }); + }); + + it("should override both projects and variants when both are provided in output", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + variants: [{ id: "variant1" }], + }); + const output = createMockOutput({ + projects: [{ id: "project2" }], + variants: [{ id: "variant2" }], + }); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filters = formatter.generateTextItemPullFilter(); + + expect(filters).toEqual({ + projects: [{ id: "project2" }], + variants: [{ id: "variant2" }], + }); + }); + + it("should handle undefined projects and variants in projectConfig", () => { + const projectConfig = createMockProjectConfig({ + projects: undefined, + variants: undefined, + }); + const output = createMockOutput(); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const filters = formatter.generateTextItemPullFilter(); + + expect(filters).toEqual({ + projects: undefined, + variants: undefined, + }); + }); + }); + + /*********************************************************** + * generateComponentPullFilter + ***********************************************************/ + describe("generateComponentPullFilter", () => { + const getComponentPullFilters = ( + mockProjectConfig: any, + mockOutput?: any + ) => { + const projectConfig = createMockProjectConfig(mockProjectConfig); + const output = createMockOutput(mockOutput); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + return formatter.generateComponentPullFilter(); + }; + + it("should use projectConfig components.folders and variants when output is not provided", () => { + const filters = getComponentPullFilters({ + components: { + folders: [ + { id: "folder1" }, + { id: "folder2", excludeNestedFolders: true }, + ], + }, + variants: [{ id: "variant1" }], + }); + + expect(filters).toEqual({ + folders: [ + { id: "folder1" }, + { id: "folder2", excludeNestedFolders: true }, + ], + variants: [{ id: "variant1" }], + }); + }); + + it("should not include folders when projectConfig.components.folders is undefined", () => { + const filters = getComponentPullFilters({ + components: { + folders: undefined, + }, + variants: [{ id: "variant1" }], + }); + + expect(filters).toEqual({ + variants: [{ id: "variant1" }], + }); + expect(filters.folders).toBeUndefined(); + }); + + it("should override folders with output.components.folders when provided", () => { + const filters = getComponentPullFilters( + { + components: { + folders: [{ id: "folder1" }], + }, + variants: [{ id: "variant1" }], + }, + { + components: { + folders: [{ id: "folder2" }], + }, + } + ); + + expect(filters).toEqual({ + folders: [{ id: "folder2" }], + variants: [{ id: "variant1" }], + }); + }); + + it("should override variants with output.variants when provided", () => { + const filters = getComponentPullFilters( + { + components: { + folders: [{ id: "folder1" }], + }, + variants: [{ id: "variant1" }], + }, + { + variants: [{ id: "variant2" }], + } + ); + + expect(filters).toEqual({ + folders: [{ id: "folder1" }], + variants: [{ id: "variant2" }], + }); + }); + + it("should override both folders and variants when both are provided in output", () => { + const filters = getComponentPullFilters( + { + components: { + folders: [{ id: "folder1" }], + }, + variants: [{ id: "variant1" }], + }, + { + components: { + folders: [{ id: "folder2" }], + }, + variants: [{ id: "variant2" }], + } + ); + expect(filters).toEqual({ + folders: [{ id: "folder2" }], + variants: [{ id: "variant2" }], + }); + }); + + it("should handle undefined components in projectConfig", () => { + const filters = getComponentPullFilters({ + components: undefined, + variants: [{ id: "variant1" }], + }); + + expect(filters).toEqual({ + variants: [{ id: "variant1" }], + }); + expect(filters.folders).toBeUndefined(); + }); + }); + + /*********************************************************** + * generateQueryParams + ***********************************************************/ + + describe("generateQueryParams", () => { + it("should generate query params for provided text item filters", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + variants: [{ id: "variant1" }], + }); + const output = createMockOutput(); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const params = formatter.generateQueryParams( + formatter.generateTextItemPullFilter() + ); + + expect(params.filter).toBeDefined(); + expect(params.filter).toEqual(expect.any(String)); + const parsedFilter = JSON.parse(params.filter); + expect(parsedFilter).toEqual({ + projects: [{ id: "project1" }], + variants: [{ id: "variant1" }], + }); + expect(params.richText).toBeUndefined(); + }); + + it("should generate query params with provided component filters", () => { + const projectConfig = createMockProjectConfig({ + components: { + folders: [{ id: "folder1" }], + }, + variants: [{ id: "variant1" }], + }); + const output = createMockOutput(); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const params = formatter.generateQueryParams( + formatter.generateComponentPullFilter() + ); + + expect(params.filter).toBeDefined(); + const parsedFilter = JSON.parse(params.filter); + expect(parsedFilter).toEqual({ + folders: [{ id: "folder1" }], + variants: [{ id: "variant1" }], + }); + expect(params.richText).toBeUndefined(); + }); + + it("should include richText from projectConfig when set", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + richText: "html", + }); + const output = createMockOutput(); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const params = formatter.generateQueryParams( + formatter.generateTextItemPullFilter() + ); + + expect(params.richText).toBe("html"); + }); + + it("should override projectConfig richText with output richText when both are set", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + richText: false, + }); + const output = createMockOutput({ + richText: "html", + }); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const params = formatter.generateQueryParams(); + + expect(params.richText).toBe("html"); + }); + + it("should use output richText when only output has richText set", () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + }); + const output = createMockOutput({ + richText: "html", + }); + const formatter = new TestBaseFormatter( + output, + projectConfig, + createMockMeta() + ); + + const params = formatter.generateQueryParams(); + + expect(params.richText).toBe("html"); + }); + }); +}); + diff --git a/lib/src/formatters/shared/base.ts b/lib/src/formatters/shared/base.ts index 797ff0c..63a6846 100644 --- a/lib/src/formatters/shared/base.ts +++ b/lib/src/formatters/shared/base.ts @@ -5,16 +5,17 @@ import { ProjectConfigYAML } from "../../services/projectConfig"; import OutputFile from "./fileTypes/OutputFile"; import appContext from "../../utils/appContext"; import JSONOutputFile from "./fileTypes/JSONOutputFile"; -import { CommandMetaFlags } from "../../http/types"; +import { + CommandMetaFlags, + PullFilters, + PullQueryParams, +} from "../../http/types"; -export default class BaseFormatter { +export default class BaseFormatter { protected output: Output; protected projectConfig: ProjectConfigYAML; protected outDir: string; - protected outputJsonFiles: Record< - string, - JSONOutputFile<{ variantId: string }> - >; + protected outputFiles: Record; protected variablesOutputFile: JSONOutputFile; protected meta: CommandMetaFlags; @@ -26,7 +27,7 @@ export default class BaseFormatter { this.output = output; this.projectConfig = projectConfig; this.outDir = output.outDir ?? appContext.outDir; - this.outputJsonFiles = {}; + this.outputFiles = {}; this.variablesOutputFile = new JSONOutputFile({ filename: "variables", path: this.outDir, @@ -34,21 +35,86 @@ export default class BaseFormatter { this.meta = meta; } + protected generateTextItemPullFilter() { + let filters: PullFilters = { + projects: this.projectConfig.projects, + variants: this.projectConfig.variants, + statuses: this.projectConfig.statuses, + }; + + if (this.output.projects) { + filters.projects = this.output.projects; + } + + if (this.output.variants) { + filters.variants = this.output.variants; + } + + if (this.output.statuses) { + filters.statuses = this.output.statuses; + } + + return filters; + } + + protected generateComponentPullFilter() { + let filters: PullFilters = { + ...(this.projectConfig.components?.folders && { + folders: this.projectConfig.components.folders, + }), + variants: this.projectConfig.variants, + statuses: this.projectConfig.statuses, + }; + + if (this.output.components) { + filters.folders = this.output.components?.folders; + } + + if (this.output.variants) { + filters.variants = this.output.variants; + } + + if (this.output.statuses) { + filters.statuses = this.output.statuses; + } + + return filters; + } + + /** + * Returns the query parameters for the fetchText API request + */ + protected generateQueryParams(filters: PullFilters = {}): PullQueryParams { + let params: PullQueryParams = { + filter: JSON.stringify(filters), + }; + + if (this.projectConfig.richText) { + params.richText = this.projectConfig.richText; + } + + if (this.output.richText) { + params.richText = this.output.richText; + } + + return params; + } + protected async fetchAPIData(): Promise { return {} as APIDataType; } - protected async transformAPIData(data: APIDataType): Promise { + protected transformAPIData(data: APIDataType): OutputFile[] { return []; } - async format(): Promise { + public async format(): Promise { const data = await this.fetchAPIData(); const files = await this.transformAPIData(data); await this.writeFiles(files); } - private async writeFiles(files: OutputFile[]): Promise { + protected async writeFiles(files: OutputFile[]): Promise { await Promise.all( files.map((file) => writeFile(file.fullPath, file.formattedContent).then(() => { diff --git a/lib/src/formatters/shared/baseExport.test.ts b/lib/src/formatters/shared/baseExport.test.ts new file mode 100644 index 0000000..ddb7bfd --- /dev/null +++ b/lib/src/formatters/shared/baseExport.test.ts @@ -0,0 +1,456 @@ +import { Output } from "../../outputs"; +import { ProjectConfigYAML } from "../../services/projectConfig"; +import { CommandMetaFlags } from "../../http/types"; +import { + ExportTextItemsResponse, + ExportComponentsStringResponse, +} from "../../http/types"; +import { exportTextItems } from "../../http/textItems"; +import { exportComponents } from "../../http/components"; +import fetchProjects from "../../http/projects"; +import fetchVariants from "../../http/variants"; +import generateSwiftDriver from "../../http/cli"; +import BaseExportFormatter from "./baseExport"; + +jest.mock("../../http/textItems"); +jest.mock("../../http/components"); +jest.mock("../../http/projects"); +jest.mock("../../http/variants"); +jest.mock("../../http/cli"); +jest.mock("../../utils/appContext", () => ({ + __esModule: true, + default: { + outDir: "/mock/app/context/outDir", + }, +})); + +const mockExportTextItems = exportTextItems as jest.MockedFunction< + typeof exportTextItems +>; +const mockExportComponents = exportComponents as jest.MockedFunction< + typeof exportComponents +>; +const mockFetchProjects = fetchProjects as jest.MockedFunction< + typeof fetchProjects +>; +const mockFetchVariants = fetchVariants as jest.MockedFunction< + typeof fetchVariants +>; +const mockGenerateSwiftDriver = generateSwiftDriver as jest.MockedFunction< + typeof generateSwiftDriver +>; + +// fake test class to expose private methods +// @ts-ignore +class TestBaseExportFormatter extends BaseExportFormatter { + public createOutputFile( + fileName: string, + variantId: string, + content: string + ) {} + public async fetchAPIData() { + return super.fetchAPIData(); + } + + public transformAPIData( + data: Parameters["transformAPIData"]>[0] + ) { + return super.transformAPIData(data); + } + + public async fetchVariants() { + return super["fetchVariants"](); + } + + // Expose private methods for testing + public async fetchTextItemsMap() { + return super["fetchTextItemsMap"](); + } + + public async fetchComponentsMap() { + return super["fetchComponentsMap"](); + } +} + +describe("BaseExportFormatter", () => { + // @ts-ignore + const createMockOutput = (overrides: Partial = {}): Output => ({ + format: "ios-strings", + outDir: "/test/output", + ...overrides, + }); + + const createMockProjectConfig = ( + overrides: Partial = {} + ): ProjectConfigYAML => ({ + projects: [], + variants: [], + components: { + folders: [], + }, + outputs: [ + { + format: "ios-strings", + }, + ], + ...overrides, + }); + + const createMockMeta = (): CommandMetaFlags => ({}); + + const createMockIOSStringsContent = (): ExportTextItemsResponse => + ` + "this-is-a-ditto-text-item" = "No its not"; + + "this-is-a-text-layer-on-figma" = "This is a Ditto text item (LinkedNode)"; + + "update-preferences" = "Update preferences"; + `; + + const createMockComponentsContent = (): ExportComponentsStringResponse => + ` + "continue" = "Continue"; + + "email" = "Email"; + `; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + /*********************************************************** + * fetchTextItemsMap + ***********************************************************/ + + describe("fetchTextItemsMap", () => { + it("should fetch text items for projects and variants configured at root level", async () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }, { id: "project2" }], + variants: [{ id: "variant1" }, { id: "base" }], + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockContent = createMockIOSStringsContent(); + mockExportTextItems.mockResolvedValue(mockContent); + + await formatter.fetchVariants(); + const result = await formatter.fetchTextItemsMap(); + + expect(result).toEqual({ + project1: { + variant1: mockContent, + base: mockContent, + }, + project2: { + variant1: mockContent, + base: mockContent, + }, + }); + }); + + it("should fetch all projects from API when not configured", async () => { + const projectConfig = createMockProjectConfig({ + projects: [], + variants: [{ id: "base" }], + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockProjects = [ + { id: "project-1", name: "Project 1" }, + { id: "project-2", name: "Project 2" }, + { id: "project-3", name: "Project 3" }, + { id: "project-4", name: "Project 4" }, + ]; + const mockContent = createMockIOSStringsContent(); + + mockFetchProjects.mockResolvedValue(mockProjects); + mockExportTextItems.mockResolvedValue(mockContent); + + await formatter.fetchVariants(); + const result = await formatter.fetchTextItemsMap(); + + expect(mockFetchProjects).toHaveBeenCalled(); + expect(result).toEqual({ + "project-1": { + base: mockContent, + }, + "project-2": { + base: mockContent, + }, + "project-3": { + base: mockContent, + }, + "project-4": { + base: mockContent, + }, + }); + }); + + it("should fetch variants from API when 'all' is specified", async () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + variants: [{ id: "all" }], + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockVariants = [ + { id: "variant1", name: "Variant 1" }, + { id: "variant2", name: "Variant 2" }, + ]; + const mockContent = createMockIOSStringsContent(); + + mockFetchVariants.mockResolvedValue(mockVariants); + mockExportTextItems.mockResolvedValue(mockContent); + + await formatter.fetchVariants(); + const result = await formatter.fetchTextItemsMap(); + + expect(mockFetchVariants).toHaveBeenCalled(); + expect(result).toEqual({ + project1: { + variant1: mockContent, + variant2: mockContent, + }, + }); + }); + + it("should default to base variant when variants are empty", async () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + variants: [], + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockContent = createMockIOSStringsContent(); + mockExportTextItems.mockResolvedValue(mockContent); + + await formatter.fetchVariants(); + const result = await formatter.fetchTextItemsMap(); + + expect(result).toEqual({ + project1: { + base: mockContent, + }, + }); + }); + }); + + /*********************************************************** + * fetchComponentsMap + ***********************************************************/ + describe("fetchComponentsMap", () => { + it("should fetch components for variants configured at root level", async () => { + const projectConfig = createMockProjectConfig({ + variants: [{ id: "variant1" }, { id: "base" }], + components: { + folders: [], + }, + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockContent = createMockComponentsContent(); + mockExportComponents.mockResolvedValue(mockContent); + + await formatter.fetchVariants(); + const result = await formatter.fetchComponentsMap(); + + expect(result).toEqual({ + variant1: mockContent, + base: mockContent, + }); + + expect(mockExportComponents).toHaveBeenCalledTimes(2); + }); + + it("should fetch variants from API when 'all' is specified", async () => { + const projectConfig = createMockProjectConfig({ + variants: [{ id: "all" }], + components: { + folders: [], + }, + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockVariants = [ + { id: "variant1", name: "Variant 1" }, + { id: "variant2", name: "Variant 2" }, + ]; + const mockContent = createMockComponentsContent(); + + mockFetchVariants.mockResolvedValue(mockVariants); + mockExportComponents.mockResolvedValue(mockContent); + + await formatter.fetchVariants(); + const result = await formatter.fetchComponentsMap(); + + expect(mockFetchVariants).toHaveBeenCalled(); + expect(result).toEqual({ variant1: mockContent, variant2: mockContent }); + }); + + it("should default to base variant when variants are empty", async () => { + const projectConfig = createMockProjectConfig({ + variants: [], + components: { + folders: [], + }, + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockContent = createMockComponentsContent(); + mockExportComponents.mockResolvedValue(mockContent); + + await formatter.fetchVariants(); + const result = await formatter.fetchComponentsMap(); + + expect(result).toEqual({ + base: mockContent, + }); + }); + + it("should return empty object when components not configured", async () => { + const projectConfig = createMockProjectConfig({ + components: undefined, + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const result = await formatter.fetchComponentsMap(); + + expect(result).toEqual({}); + expect(mockExportComponents).not.toHaveBeenCalled(); + }); + }); + + /*********************************************************** + * fetchAPIData + ***********************************************************/ + describe("fetchAPIData", () => { + it("should fetchVariants and combine text items and components data", async () => { + const projectConfig = createMockProjectConfig({ + projects: [{ id: "project1" }], + variants: [{ id: "base" }], + components: { + folders: [], + }, + }); + const output = createMockOutput(); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const mockTextContent = createMockIOSStringsContent(); + const mockComponentsContent = createMockComponentsContent(); + + mockExportTextItems.mockResolvedValue(mockTextContent); + mockExportComponents.mockResolvedValue(mockComponentsContent); + + const fetchVariantsSpy = jest.spyOn(formatter, "fetchVariants"); + const result = await formatter.fetchAPIData(); + + expect(fetchVariantsSpy).toHaveBeenCalled(); + expect(result).toEqual({ + textItemsMap: { + project1: { + base: mockTextContent, + }, + }, + componentsMap: { + base: mockComponentsContent, + }, + }); + }); + }); + + /*********************************************************** + * transformAPIData + ***********************************************************/ + describe("transformAPIData", () => { + it("should invoke BaseExportFormatter.createOutputFiles for each text item", () => { + const projectConfig = createMockProjectConfig(); + const output = createMockOutput({ outDir: "/test/output" }); + // @ts-ignore + const formatter = new TestBaseExportFormatter( + output, + projectConfig, + createMockMeta() + ); + + const createOutputSpy = jest.spyOn(formatter, "createOutputFile"); + const mockTextContent = createMockIOSStringsContent(); + const data = { + textItemsMap: { + project1: { + base: mockTextContent, + variant1: mockTextContent, + }, + }, + componentsMap: {}, + }; + + formatter.transformAPIData(data); + expect(createOutputSpy).toHaveBeenCalledTimes(2); + expect(createOutputSpy).toHaveBeenCalledWith( + "project1", + `project1___base`, + "base", + mockTextContent + ); + expect(createOutputSpy).toHaveBeenCalledWith( + "project1", + `project1___variant1`, + "variant1", + mockTextContent + ); + }); + }); +}); diff --git a/lib/src/formatters/shared/baseExport.ts b/lib/src/formatters/shared/baseExport.ts new file mode 100644 index 0000000..9d8121e --- /dev/null +++ b/lib/src/formatters/shared/baseExport.ts @@ -0,0 +1,200 @@ +import { + PullQueryParams, + ExportTextItemsResponse, + ExportComponentsResponse, +} from "../../http/types"; +import { exportTextItems } from "../../http/textItems"; +import { exportComponents } from "../../http/components"; +import BaseFormatter from "./base"; +import fetchProjects from "../../http/projects"; +import fetchVariants from "../../http/variants"; +import OutputFile from "./fileTypes/OutputFile"; +import { BASE_VARIANT_ID } from "../../utils/constants"; + +interface ComponentsMap { + [variantId: string]: ExportComponentsResponse; +} +interface TextItemsMap { + [projectId: string]: { + [variantId: string]: ExportTextItemsResponse; + }; +} + +type ExportFormatAPIData = { + textItemsMap: TextItemsMap; + componentsMap: ComponentsMap; +}; + +type ExportOutputFile = OutputFile< + string | Record, + MetadataType +>; + +/** + * Base Class for File Formats That Leverage API /v2/components/export and /v2/textItems/export endpoints + * These file formats fetch their file data directly from the API and write to files, unlike in the case of + * default /v2/textItems + /v2/components JSON, we cannot perform any manipulation on the data itself + */ +export default abstract class BaseExportFormatter< + TOutputFile extends ExportOutputFile<{ variantId: string }> +> extends BaseFormatter { + protected abstract exportFormat: PullQueryParams["format"]; + private variants: { id: string }[] = []; + + protected abstract createOutputFile( + filePrefix: string, + fileName: string, + variantId: string, + content: string | Record + ): void; + + protected async fetchAPIData() { + await this.fetchVariants(); + const [textItemsMap, componentsMap] = await Promise.all([ + this.fetchTextItemsMap(), + this.fetchComponentsMap(), + ]); + + return { textItemsMap, componentsMap }; + } + + /** + * For each project/variant permutation and its fetched file data, + * create a new file with the expected project/variant name + * + * @returns {OutputFile[]} List of Output Files + */ + protected transformAPIData(data: ExportFormatAPIData): TOutputFile[] { + Object.entries(data.textItemsMap).forEach( + ([projectId, projectVariants]) => { + Object.entries(projectVariants).forEach( + ([variantId, textItemsFileContent]) => { + const fileName = `${projectId}___${variantId || BASE_VARIANT_ID}`; + this.createOutputFile( + projectId, + fileName, + variantId, + textItemsFileContent + ); + } + ); + } + ); + + Object.entries(data.componentsMap).forEach( + ([variantId, componentsFileContent]) => { + const filePrefix = "components"; + const fileName = `${filePrefix}___${variantId || BASE_VARIANT_ID}`; + this.createOutputFile( + filePrefix, + fileName, + variantId, + componentsFileContent + ); + } + ); + + return Object.values(this.outputFiles); + } + + /** + * Sets variants based on configuration + * - Fetches from API if "all" configured + * - Adds "base" variant by default if none configured + */ + private async fetchVariants(): Promise { + let variants: { id: string }[] = + this.output.variants ?? this.projectConfig.variants ?? []; + if (variants.some((variant) => variant.id === "all")) { + variants = await fetchVariants(this.meta); + } else if (variants.length === 0) { + variants = [{ id: BASE_VARIANT_ID }]; + } + + this.variants = variants; + } + + /** + * Fetches text item data via API for each configured project and variant + * in this output + * + * @returns text items mapped to their respective variant and project + */ + private async fetchTextItemsMap(): Promise { + if (!this.projectConfig.projects && !this.output.projects) return {}; + let projects: { id: string }[] = + this.output.projects ?? this.projectConfig.projects ?? []; + + const result: TextItemsMap = {}; + + if (projects.length === 0) { + projects = await fetchProjects(this.meta); + } + + const fetchFileContentRequests = []; + + for (const project of projects) { + result[project.id] = {}; + + for (const variant of this.variants) { + // map "base" to undefined, as by default export endpoint returns base variant + const variantId = + variant.id === BASE_VARIANT_ID ? undefined : variant.id; + const params: PullQueryParams = { + ...super.generateQueryParams({ + projects: [{ id: project.id }], + }), + variantId, + format: this.exportFormat, + }; + const addVariantToProjectMap = exportTextItems(params, this.meta).then( + (textItemsFileContent) => { + result[project.id][variant.id] = textItemsFileContent; + } + ); + fetchFileContentRequests.push(addVariantToProjectMap); + } + } + + await Promise.all(fetchFileContentRequests); + + return result; + } + + /** + * Fetches component data via API. + * If individual variants configured, fetch by each otherwise fetch for all + * Skips the fetch request if components field is not specified in config. + * + * @returns components data + */ + private async fetchComponentsMap(): Promise { + if (!this.projectConfig.components && !this.output.components) return {}; + const result: ComponentsMap = {}; + + const fetchFileContentRequests = []; + + for (const variant of this.variants) { + // map "base" to undefined, as by default export endpoint returns base variant + const variantId = variant.id === BASE_VARIANT_ID ? undefined : variant.id; + const folderFilters = super.generateComponentPullFilter().folders; + const params: PullQueryParams = { + // gets folders from base component pull filters, overwrites variants with just this iteration's variant + ...super.generateQueryParams({ + folders: folderFilters, + }), + variantId, + format: this.exportFormat, + }; + const addVariantToMap = exportComponents(params, this.meta).then( + (componentsFileContent) => { + result[variant.id] = componentsFileContent; + } + ); + fetchFileContentRequests.push(addVariantToMap); + } + + await Promise.all(fetchFileContentRequests); + return result; + } +} diff --git a/lib/src/formatters/shared/fileTypes/AndroidOutputFile.ts b/lib/src/formatters/shared/fileTypes/AndroidOutputFile.ts new file mode 100644 index 0000000..df3e5ac --- /dev/null +++ b/lib/src/formatters/shared/fileTypes/AndroidOutputFile.ts @@ -0,0 +1,25 @@ +import OutputFile from "./OutputFile"; + +export default class AndroidOutputFile extends OutputFile< + string, + MetadataType +> { + constructor(config: { + filename: string; + path: string; + content?: string; + metadata?: MetadataType; + }) { + super({ + filename: config.filename, + path: config.path, + extension: "xml", + content: config.content ?? "", + metadata: config.metadata ?? ({} as MetadataType), + }); + } + + get formattedContent(): string { + return this.content; + } +} diff --git a/lib/src/formatters/shared/fileTypes/ICUOutputFile.ts b/lib/src/formatters/shared/fileTypes/ICUOutputFile.ts new file mode 100644 index 0000000..860e897 --- /dev/null +++ b/lib/src/formatters/shared/fileTypes/ICUOutputFile.ts @@ -0,0 +1,25 @@ +import OutputFile from "./OutputFile"; + +export default class ICUOutputFile extends OutputFile< + Record, + MetadataType +> { + constructor(config: { + filename: string; + path: string; + content?: Record; + metadata?: MetadataType; + }) { + super({ + filename: config.filename, + path: config.path, + extension: "json", + content: config.content ?? {}, + metadata: config.metadata ?? ({} as MetadataType), + }); + } + + get formattedContent(): string { + return JSON.stringify(this.content, null, 2); + } +} diff --git a/lib/src/formatters/shared/fileTypes/IOSStringsDictOutputFile.ts b/lib/src/formatters/shared/fileTypes/IOSStringsDictOutputFile.ts new file mode 100644 index 0000000..6ad668e --- /dev/null +++ b/lib/src/formatters/shared/fileTypes/IOSStringsDictOutputFile.ts @@ -0,0 +1,25 @@ +import OutputFile from "./OutputFile"; + +export default class IOSStringsDictOutputFile extends OutputFile< + string, + MetadataType +> { + constructor(config: { + filename: string; + path: string; + content?: string; + metadata?: MetadataType; + }) { + super({ + filename: config.filename, + path: config.path, + extension: "stringsdict", + content: config.content ?? "", + metadata: config.metadata ?? ({} as MetadataType), + }); + } + + get formattedContent(): string { + return this.content; + } +} diff --git a/lib/src/formatters/shared/fileTypes/IOSStringsOutputFile.ts b/lib/src/formatters/shared/fileTypes/IOSStringsOutputFile.ts new file mode 100644 index 0000000..6c6dd9a --- /dev/null +++ b/lib/src/formatters/shared/fileTypes/IOSStringsOutputFile.ts @@ -0,0 +1,25 @@ +import OutputFile from "./OutputFile"; + +export default class IOSStringsOutputFile extends OutputFile< + string, + MetadataType +> { + constructor(config: { + filename: string; + path: string; + content?: string; + metadata?: MetadataType; + }) { + super({ + filename: config.filename, + path: config.path, + extension: "strings", + content: config.content ?? "", + metadata: config.metadata ?? ({} as MetadataType), + }); + } + + get formattedContent(): string { + return this.content; + } +} diff --git a/lib/src/formatters/shared/fileTypes/SwiftOutputFile.ts b/lib/src/formatters/shared/fileTypes/SwiftOutputFile.ts new file mode 100644 index 0000000..1e7bfc3 --- /dev/null +++ b/lib/src/formatters/shared/fileTypes/SwiftOutputFile.ts @@ -0,0 +1,16 @@ +import OutputFile from "./OutputFile"; + +export default class SwiftOutputFile extends OutputFile { + constructor(config: { filename?: string; path: string; content?: string }) { + super({ + filename: config.filename || "Ditto", + path: config.path, + extension: "swift", + content: config.content ?? "", + }); + } + + get formattedContent(): string { + return this.content; + } +} diff --git a/lib/src/http/cli.ts b/lib/src/http/cli.ts new file mode 100644 index 0000000..3c85439 --- /dev/null +++ b/lib/src/http/cli.ts @@ -0,0 +1,23 @@ +import { AxiosError } from "axios"; +import { CommandMetaFlags, IExportSwiftFileRequest } from "./types"; +import getHttpClient from "./client"; + +export default async function generateSwiftDriver( + params: IExportSwiftFileRequest, + meta: CommandMetaFlags +) { + try { + const httpClient = getHttpClient({ meta }); + const response = await httpClient.post("/v2/cli/swiftDriver", params); + + return response.data; + } catch (e) { + if (!(e instanceof AxiosError)) { + throw new Error( + "Sorry! We're having trouble reaching the Ditto API. Please try again later." + ); + } + + throw e; + } +} diff --git a/lib/src/http/components.test.ts b/lib/src/http/components.test.ts index 1521345..ee41bb9 100644 --- a/lib/src/http/components.test.ts +++ b/lib/src/http/components.test.ts @@ -1,79 +1,146 @@ import getHttpClient from "./client"; -import fetchComponents from "./components"; +import { fetchComponents, exportComponents } from "./components"; +import { AxiosError } from "axios"; jest.mock("./client"); describe("fetchComponents", () => { - // Create a mock client with a mock 'get' method const mockHttpClient = { get: jest.fn(), }; - // Make getHttpClient return the mock client - (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); - beforeEach(() => { jest.clearAllMocks(); + (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); }); - describe("richText parameter", () => { - it("should parse response with richText field correctly", async () => { - const mockResponse = { - data: [ - { - id: "text1", - text: "Plain text", - richText: "

Rich HTML text

", - status: "FINAL", - notes: "Test note", - tags: ["tag1"], - variableIds: ["var1"], - folderId: null, - variantId: "variant1", - }, - ], - }; - - mockHttpClient.get.mockResolvedValue(mockResponse); - - const result = await fetchComponents( + it("should throw error with response message", async () => { + const mockAxiosError = new AxiosError("Invalid format"); + mockAxiosError.response = { + status: 400, + data: { message: "Invalid filters" }, + } as any; + + mockHttpClient.get.mockRejectedValue(mockAxiosError); + + await expect( + fetchComponents( { - filter: "", - richText: "html", + filter: "asdfasdf", }, {} - ); - - expect(result).toEqual([...mockResponse.data]); - }); - - it("should handle response without richText field", async () => { - const mockResponse = { - data: [ - { - id: "text1", - text: "Plain text only", - status: "FINAL", - notes: "", - tags: [], - variableIds: [], - folderId: null, - variantId: null, - }, - ], - }; - - mockHttpClient.get.mockResolvedValue(mockResponse); - - const result = await fetchComponents( + ) + ).rejects.toThrow( + "Invalid filters. Please check your component filters and try again." + ); + }); + + it("should parse response with richText field correctly", async () => { + const mockResponse = { + status: 200, + data: [ + { + id: "text1", + text: "Plain text", + richText: "

Rich HTML text

", + status: "FINAL", + notes: "Test note", + tags: ["tag1"], + variableIds: ["var1"], + folderId: null, + variantId: "variant1", + }, + ], + }; + + mockHttpClient.get.mockResolvedValue(mockResponse); + + const result = await fetchComponents( + { + filter: "", + richText: "html", + }, + {} + ); + + expect(result).toEqual([...mockResponse.data]); + }); + + it("should handle response without richText field", async () => { + const mockResponse = { + data: [ + { + id: "text1", + text: "Plain text only", + status: "FINAL", + notes: "", + tags: [], + variableIds: [], + folderId: null, + variantId: null, + }, + ], + }; + + mockHttpClient.get.mockResolvedValue(mockResponse); + + const result = await fetchComponents( + { + filter: "", + richText: "html", + }, + {} + ); + + expect(result).toEqual([...mockResponse.data]); + }); +}); + +describe("exportComponents", () => { + const mockHttpClient = { + get: jest.fn(), + }; + + beforeEach(() => { + jest.clearAllMocks(); + (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); + }); + + it("should throw error with response message", async () => { + const mockAxiosError = new AxiosError("Invalid format"); + mockAxiosError.response = { + status: 400, + data: { message: "Invalid format parameter" }, + } as any; + + mockHttpClient.get.mockRejectedValue(mockAxiosError); + + await expect( + exportComponents( { filter: "", - richText: "html", + format: "invalid-format" as any, }, {} - ); + ) + ).rejects.toThrow( + "Invalid format parameter. Please check your params and try again." + ); + }); - expect(result).toEqual([...mockResponse.data]); - }); + it("should return response data", async () => { + const mockData = ` + "component-1": "Hello, world!", + "component-2": "Hello, world!", + }`; + mockHttpClient.get.mockResolvedValue({ status: 200, data: mockData }); + const result = await exportComponents( + { + filter: "", + format: "json_i18next" as any, + }, + {} + ); + expect(result).toEqual(mockData); }); }); diff --git a/lib/src/http/components.ts b/lib/src/http/components.ts index 70c26cf..535e689 100644 --- a/lib/src/http/components.ts +++ b/lib/src/http/components.ts @@ -3,41 +3,69 @@ import { ZComponentsResponse, PullQueryParams, CommandMetaFlags, + ZExportComponentsResponse, } from "./types"; import getHttpClient from "./client"; -export default async function fetchComponents( +const handleError = ( + e: unknown, + msgBase: string, + msgDescription: string +): Error => { + if (!(e instanceof AxiosError)) { + return new Error( + "Sorry! We're having trouble reaching the Ditto API. Please try again later." + ); + } + + // Handle invalid filters + if (e.response?.status === 400) { + let errorMsgBase = msgBase; + + if (e.response?.data?.message) errorMsgBase = e.response.data.message; + + return new Error(`${errorMsgBase}. ${msgDescription}`, { + cause: e.response?.data, + }); + } + + return e; +}; + +export async function fetchComponents( params: PullQueryParams, meta: CommandMetaFlags ) { try { const httpClient = getHttpClient({ meta }); - const response = await httpClient.get("/v2/components", { + const defaultResponse = await httpClient.get("/v2/components", { params, }); + return ZComponentsResponse.parse(defaultResponse.data); + } catch (e: unknown) { + throw handleError( + e, + "Invalid component filters", + "Please check your component filters and try again." + ); + } +} - return ZComponentsResponse.parse(response.data); - } catch (e) { - if (!(e instanceof AxiosError)) { - throw new Error( - "Sorry! We're having trouble reaching the Ditto API. Please try again later." - ); - } - - // Handle invalid filters - if (e.response?.status === 400) { - let errorMsgBase = "Invalid component filters"; - - if (e.response?.data?.message) errorMsgBase = e.response.data.message; - - throw new Error( - `${errorMsgBase}. Please check your component filters and try again.`, - { - cause: e.response?.data, - } - ); - } - - throw e; +export async function exportComponents( + params: PullQueryParams, + meta: CommandMetaFlags +) { + try { + const httpClient = getHttpClient({ meta }); + const exportResponse = await httpClient.get("/v2/components/export", { + params, + }); + return ZExportComponentsResponse.parse(exportResponse.data); + } catch (e: unknown) { + throw handleError( + e, + "Invalid params", + "Please check your params and try again." + ); } } diff --git a/lib/src/http/projects.test.ts b/lib/src/http/projects.test.ts new file mode 100644 index 0000000..0401f86 --- /dev/null +++ b/lib/src/http/projects.test.ts @@ -0,0 +1,51 @@ +import getHttpClient from "./client"; +import fetchProjects from "./projects"; + +jest.mock("./client"); + +describe("fetchProjects", () => { + const mockHttpClient = { + get: jest.fn(), + }; + + (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it("should parse response correctly", async () => { + const mockResponse = { + data: [ + { + id: "project1", + name: "Project One", + }, + { + id: "project2", + name: "Project Two", + }, + ], + }; + + mockHttpClient.get.mockResolvedValue(mockResponse); + const result = await fetchProjects({}); + expect(result).toEqual([...mockResponse.data]); + }); + + it("should handle empty response", async () => { + const mockResponse = { data: [] }; + mockHttpClient.get.mockResolvedValue(mockResponse); + const result = await fetchProjects({}); + expect(result).toEqual([]); + }); + + it("should have user-friendly error response if not instance of AxiosError", async () => { + const mockError = new Error("Request failed"); + mockHttpClient.get.mockRejectedValue(mockError); + + await expect(fetchProjects({})).rejects.toThrow( + "Sorry! We're having trouble reaching the Ditto API. Please try again later." + ); + }); +}); diff --git a/lib/src/http/projects.ts b/lib/src/http/projects.ts new file mode 100644 index 0000000..45c4d0b --- /dev/null +++ b/lib/src/http/projects.ts @@ -0,0 +1,20 @@ +import { AxiosError } from "axios"; +import { ZProjectsResponse, CommandMetaFlags } from "./types"; +import getHttpClient from "./client"; + +export default async function fetchProjects(meta: CommandMetaFlags) { + try { + const httpClient = getHttpClient({ meta }); + const response = await httpClient.get("/v2/projects"); + + return ZProjectsResponse.parse(response.data); + } catch (e) { + if (!(e instanceof AxiosError)) { + throw new Error( + "Sorry! We're having trouble reaching the Ditto API. Please try again later." + ); + } + + throw e; + } +} diff --git a/lib/src/http/textItems.test.ts b/lib/src/http/textItems.test.ts index f1054ee..b1c2fb4 100644 --- a/lib/src/http/textItems.test.ts +++ b/lib/src/http/textItems.test.ts @@ -1,50 +1,44 @@ -import fetchText from "./textItems"; import getHttpClient from "./client"; +import { fetchTextItems, exportTextItems } from "./textItems"; +import { AxiosError } from "axios"; jest.mock("./client"); -describe("fetchText", () => { - // Create a mock client with a mock 'get' method +describe("fetchTextItems", () => { const mockHttpClient = { get: jest.fn(), }; - // Make getHttpClient return the mock client - (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); - beforeEach(() => { jest.clearAllMocks(); + (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); }); - describe("richText parameter", () => { - it("should parse response with richText field correctly", async () => { - const mockResponse = { - data: [ - { - id: "text1", - text: "Plain text", - richText: "

Rich HTML text

", - status: "FINAL", - notes: "Test note", - tags: ["tag1"], - variableIds: ["var1"], - projectId: "project1", - variantId: "variant1", - }, - ], - }; - - mockHttpClient.get.mockResolvedValue(mockResponse); - - const result = await fetchText( + it("should throw error with response message", async () => { + const mockAxiosError = new AxiosError("Invalid format"); + mockAxiosError.response = { + status: 400, + data: { message: "Invalid project filters" }, + } as any; + + mockHttpClient.get.mockRejectedValue(mockAxiosError); + + await expect( + fetchTextItems( { - filter: "", - richText: "html", + filter: "asdfasdf", }, {} - ); + ) + ).rejects.toThrow( + "Invalid project filters. Please check your project filters and try again." + ); + }); - expect(result).toEqual([ + it("should parse response with richText field correctly", async () => { + const mockResponse = { + status: 200, + data: [ { id: "text1", text: "Plain text", @@ -56,36 +50,25 @@ describe("fetchText", () => { projectId: "project1", variantId: "variant1", }, - ]); - }); - - it("should handle response without richText field", async () => { - const mockResponse = { - data: [ - { - id: "text1", - text: "Plain text only", - status: "FINAL", - notes: "", - tags: [], - variableIds: [], - projectId: "project1", - variantId: null, - }, - ], - }; - - mockHttpClient.get.mockResolvedValue(mockResponse); - - const result = await fetchText( - { - filter: "", - richText: "html", - }, - {} - ); + ], + }; - expect(result).toEqual([ + mockHttpClient.get.mockResolvedValue(mockResponse); + + const result = await fetchTextItems( + { + filter: "", + richText: "html", + }, + {} + ); + + expect(result).toEqual([...mockResponse.data]); + }); + + it("should handle response without richText field", async () => { + const mockResponse = { + data: [ { id: "text1", text: "Plain text only", @@ -97,7 +80,68 @@ describe("fetchText", () => { projectId: "project1", variantId: null, }, - ]); - }); + ], + }; + + mockHttpClient.get.mockResolvedValue(mockResponse); + + const result = await fetchTextItems( + { + filter: "", + richText: "html", + }, + {} + ); + + expect(result).toEqual([...mockResponse.data]); + }); +}); + +describe("exportTextItems", () => { + const mockHttpClient = { + get: jest.fn(), + }; + + beforeEach(() => { + jest.clearAllMocks(); + (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); + }); + + it("should throw error with response message", async () => { + const mockAxiosError = new AxiosError("Invalid format"); + mockAxiosError.response = { + status: 400, + data: { message: "Invalid request parameters" }, + } as any; + + mockHttpClient.get.mockRejectedValue(mockAxiosError); + + await expect( + exportTextItems( + { + filter: "", + format: "invalid-format" as any, + }, + {} + ) + ).rejects.toThrow( + "Invalid request parameters. Please check your request parameters and try again." + ); + }); + + it("should return response data", async () => { + const mockData = ` + "component-1": "Hello, world!", + "component-2": "Hello, world!", + }`; + mockHttpClient.get.mockResolvedValue({ status: 200, data: mockData }); + const result = await exportTextItems( + { + filter: "", + format: "json_i18next" as any, + }, + {} + ); + expect(result).toEqual(mockData); }); }); diff --git a/lib/src/http/textItems.ts b/lib/src/http/textItems.ts index 57d4618..83c7c67 100644 --- a/lib/src/http/textItems.ts +++ b/lib/src/http/textItems.ts @@ -1,38 +1,71 @@ -import httpClient from "./client"; import { AxiosError } from "axios"; -import { CommandMetaFlags, PullQueryParams, ZTextItemsResponse } from "./types"; +import { + CommandMetaFlags, + PullQueryParams, + ZTextItemsResponse, + ZExportTextItemsResponse, +} from "./types"; import getHttpClient from "./client"; -export default async function fetchText( +const handleError = ( + e: unknown, + msgBase: string, + msgDescription: string +): Error => { + if (!(e instanceof AxiosError)) { + return new Error( + "Sorry! We're having trouble reaching the Ditto API. Please try again later." + ); + } + + // Handle invalid filters + if (e.response?.status === 400) { + let errorMsgBase = msgBase; + + if (e.response?.data?.message) errorMsgBase = e.response.data.message; + + return new Error(`${errorMsgBase}. ${msgDescription}`, { + cause: e.response?.data, + }); + } + + return e; +}; + +export async function fetchTextItems( params: PullQueryParams, meta: CommandMetaFlags ) { try { const httpClient = getHttpClient({ meta }); - const response = await httpClient.get("/v2/textItems", { params }); - - return ZTextItemsResponse.parse(response.data); + const defaultResponse = await httpClient.get("/v2/textItems", { + params, + }); + return ZTextItemsResponse.parse(defaultResponse.data); } catch (e: unknown) { - if (!(e instanceof AxiosError)) { - throw new Error( - "Sorry! We're having trouble reaching the Ditto API. Please try again later." - ); - } - - // Handle invalid filters - if (e.response?.status === 400) { - let errorMsgBase = "Invalid project filters"; - - if (e.response?.data?.message) errorMsgBase = e.response.data.message; - - throw new Error( - `${errorMsgBase}. Please check your project filters and try again.`, - { - cause: e.response?.data, - } - ); - } + throw handleError( + e, + "Invalid project filters", + "Please check your project filters and try again." + ); + } +} - throw e; +export async function exportTextItems( + params: PullQueryParams, + meta: CommandMetaFlags +) { + try { + const httpClient = getHttpClient({ meta }); + const exportResponse = await httpClient.get("/v2/textItems/export", { + params, + }); + return ZExportTextItemsResponse.parse(exportResponse.data); + } catch (e: unknown) { + throw handleError( + e, + "Invalid params", + "Please check your request parameters and try again." + ); } } diff --git a/lib/src/http/types.ts b/lib/src/http/types.ts index 218d600..b82429a 100644 --- a/lib/src/http/types.ts +++ b/lib/src/http/types.ts @@ -9,10 +9,16 @@ export interface PullFilters { variants?: { id: string }[]; statuses?: ITextStatus[]; } - export interface PullQueryParams { filter: string; // Stringified PullFilters richText?: "html"; + variantId?: string; // undefined for base + format?: + | "ios-strings" + | "ios-stringsdict" + | "android" + | "json_icu" + | undefined; } export const ZTextStatus = z.enum(["NONE", "WIP", "REVIEW", "FINAL"]); export type ITextStatus = z.infer; @@ -44,6 +50,22 @@ export type TextItem = z.infer; export const ZTextItemsResponse = z.array(ZTextItem); export type TextItemsResponse = z.infer; +const ZExportTextItemsStringResponse = z.string(); +export type ExportTextItemsStringResponse = z.infer< + typeof ZExportTextItemsStringResponse +>; + +const ZExportTextItemsJSONResponse = z.record(z.string(), z.string()); +export type ExportTextItemsJSONResponse = z.infer< + typeof ZExportTextItemsJSONResponse +>; + +export const ZExportTextItemsResponse = z.union([ + ZExportTextItemsStringResponse, + ZExportTextItemsJSONResponse, +]); +export type ExportTextItemsResponse = z.infer; + // MARK - Components const ZComponent = ZBaseTextEntity.extend({ @@ -58,6 +80,54 @@ export type Component = z.infer; export const ZComponentsResponse = z.array(ZComponent); export type ComponentsResponse = z.infer; +export const ZExportComponentsJSONResponse = z.record(z.string(), z.string()); +export type ExportComponentsJSONResponse = z.infer< + typeof ZExportComponentsJSONResponse +>; + +export const ZExportComponentsStringResponse = z.string(); +export type ExportComponentsStringResponse = z.infer< + typeof ZExportComponentsStringResponse +>; +export const ZExportComponentsResponse = z.union([ + ZExportComponentsStringResponse, + ZExportComponentsJSONResponse, +]); +export type ExportComponentsResponse = z.infer< + typeof ZExportComponentsResponse +>; + +// MARK - Projects + +const ZProject = z.object({ + id: z.string(), + name: z.string(), +}); + +/** + * Represents a single project, as returned from the /v2/projects endpoint + */ +export type Project = z.infer; + +export const ZProjectsResponse = z.array(ZProject); +export type ProjectsResponse = z.infer; + +// MARK - Variants + +const ZVariant = z.object({ + id: z.string(), + name: z.string(), + description: z.string().optional(), +}); + +/** + * Represents a single variant, as returned from the /v2/variants endpoint + */ +export type Variant = z.infer; + +export const ZVariantsResponse = z.array(ZVariant); +export type VariantsResponse = z.infer; + /** * Contains metadata attached to CLI commands via -m or --meta flag * Currently only used internally to identify requests from our GitHub Action @@ -66,3 +136,22 @@ export type CommandMetaFlags = { githubActionRequest?: string; // Set to "true" if the request is from our GitHub Action [key: string]: string | undefined; // Allow other arbitrary key-value pairs, but none of these values are used for anything at the moment }; + +// MARK - IOS + +const ZFolderParam = z.object({ + id: z.string(), + excludeNestedFolders: z.boolean().optional(), +}); + +export const ZExportSwiftFileRequest = z.object({ + projects: z.array(z.object({ id: z.string() })).optional(), + components: z + .object({ + folders: z.array(ZFolderParam).optional(), + }) + .optional(), + statuses: z.array(ZTextStatus).optional(), +}); + +export type IExportSwiftFileRequest = z.infer; diff --git a/lib/src/http/variants.test.ts b/lib/src/http/variants.test.ts new file mode 100644 index 0000000..14c3fbb --- /dev/null +++ b/lib/src/http/variants.test.ts @@ -0,0 +1,66 @@ +import getHttpClient from "./client"; +import fetchVariants from "./variants"; + +jest.mock("./client"); + +describe("fetchVariants", () => { + const mockHttpClient = { get: jest.fn() }; + + (getHttpClient as jest.Mock).mockReturnValue(mockHttpClient); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it("should parse response correctly", async () => { + const mockResponse = { + data: [ + { + id: "variant1", + name: "Variant One", + description: "This is variant one", + }, + { + id: "variant2", + name: "Variant Two", + description: "This is variant two", + }, + ], + }; + + mockHttpClient.get.mockResolvedValue(mockResponse); + const result = await fetchVariants({}); + expect(result).toEqual([...mockResponse.data]); + }); + + it("should handle response without description field", async () => { + const mockResponse = { + data: [ + { + id: "variant1", + name: "Variant One", + }, + ], + }; + + mockHttpClient.get.mockResolvedValue(mockResponse); + const result = await fetchVariants({}); + expect(result).toEqual([...mockResponse.data]); + }); + + it("should handle empty response", async () => { + const mockResponse = { data: [] }; + mockHttpClient.get.mockResolvedValue(mockResponse); + const result = await fetchVariants({}); + expect(result).toEqual([]); + }); + + it("should have user-friendly error response if not instance of AxiosError", async () => { + const mockError = new Error("Request failed"); + mockHttpClient.get.mockRejectedValue(mockError); + + await expect(fetchVariants({})).rejects.toThrow( + "Sorry! We're having trouble reaching the Ditto API. Please try again later." + ); + }); +}); diff --git a/lib/src/http/variants.ts b/lib/src/http/variants.ts new file mode 100644 index 0000000..16fd4dd --- /dev/null +++ b/lib/src/http/variants.ts @@ -0,0 +1,20 @@ +import { AxiosError } from "axios"; +import { ZVariantsResponse, CommandMetaFlags } from "./types"; +import getHttpClient from "./client"; + +export default async function fetchVariants(meta: CommandMetaFlags) { + try { + const httpClient = getHttpClient({ meta }); + const response = await httpClient.get("/v2/variants"); + + return ZVariantsResponse.parse(response.data); + } catch (e) { + if (!(e instanceof AxiosError)) { + throw new Error( + "Sorry! We're having trouble reaching the Ditto API. Please try again later." + ); + } + + throw e; + } +} diff --git a/lib/src/outputs/android.ts b/lib/src/outputs/android.ts new file mode 100644 index 0000000..f1acd7a --- /dev/null +++ b/lib/src/outputs/android.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; +import { ZBaseOutputFilters } from "./shared"; + +export const ZAndroidOutput = ZBaseOutputFilters.extend({ + format: z.literal("android"), + framework: z.undefined(), +}).strict(); diff --git a/lib/src/outputs/index.ts b/lib/src/outputs/index.ts index 303b95b..14d36d4 100644 --- a/lib/src/outputs/index.ts +++ b/lib/src/outputs/index.ts @@ -1,9 +1,19 @@ import { z } from "zod"; import { ZJSONOutput } from "./json"; +import { ZIOSStringsOutput } from "./iosStrings"; +import { ZIOSStringsDictOutput } from "./iosStringsDict"; +import { ZAndroidOutput } from "./android"; +import { ZJSONICUOutput } from "./jsonICU"; /** * The output config is a discriminated union of all the possible output formats. */ -export const ZOutput = z.union([...ZJSONOutput.options]); +export const ZOutput = z.union([ + ...ZJSONOutput.options, + ZAndroidOutput, + ZIOSStringsOutput, + ZIOSStringsDictOutput, + ZJSONICUOutput, +]); export type Output = z.infer; diff --git a/lib/src/outputs/iosStrings.ts b/lib/src/outputs/iosStrings.ts new file mode 100644 index 0000000..1dd64b4 --- /dev/null +++ b/lib/src/outputs/iosStrings.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; +import { ZBaseOutputFilters } from "./shared"; + +export const ZIOSStringsOutput = ZBaseOutputFilters.extend({ + format: z.literal("ios-strings"), + framework: z.undefined(), +}).strict(); diff --git a/lib/src/outputs/iosStringsDict.ts b/lib/src/outputs/iosStringsDict.ts new file mode 100644 index 0000000..0249382 --- /dev/null +++ b/lib/src/outputs/iosStringsDict.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; +import { ZBaseOutputFilters } from "./shared"; + +export const ZIOSStringsDictOutput = ZBaseOutputFilters.extend({ + format: z.literal("ios-stringsdict"), + framework: z.undefined(), +}).strict(); diff --git a/lib/src/outputs/jsonICU.ts b/lib/src/outputs/jsonICU.ts new file mode 100644 index 0000000..5b36bf2 --- /dev/null +++ b/lib/src/outputs/jsonICU.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; +import { ZBaseOutputFilters } from "./shared"; + +export const ZJSONICUOutput = ZBaseOutputFilters.extend({ + format: z.literal("json_icu"), + framework: z.undefined(), +}).strict(); diff --git a/lib/src/outputs/shared.ts b/lib/src/outputs/shared.ts index b43f89c..ef57c0d 100644 --- a/lib/src/outputs/shared.ts +++ b/lib/src/outputs/shared.ts @@ -23,4 +23,5 @@ export const ZBaseOutputFilters = z.object({ variants: z.array(z.object({ id: z.string() })).optional(), outDir: z.string().optional(), richText: z.union([z.literal("html"), z.literal(false)]).optional(), + iosLocales: z.array(z.record(z.string(), z.string())).optional(), }); diff --git a/lib/src/utils/constants.ts b/lib/src/utils/constants.ts new file mode 100644 index 0000000..271c381 --- /dev/null +++ b/lib/src/utils/constants.ts @@ -0,0 +1 @@ +export const BASE_VARIANT_ID = "base"; diff --git a/lib/src/utils/getSwiftDriverFile.test.ts b/lib/src/utils/getSwiftDriverFile.test.ts new file mode 100644 index 0000000..588c44b --- /dev/null +++ b/lib/src/utils/getSwiftDriverFile.test.ts @@ -0,0 +1,80 @@ +import SwiftOutputFile from "../formatters/shared/fileTypes/SwiftOutputFile"; +import { ProjectConfigYAML } from "../services/projectConfig"; +import generateSwiftDriver from "../http/cli"; +import getSwiftDriverFile from "./getSwiftDriverFile"; + +jest.mock("../http/cli"); +jest.mock("./appContext", () => ({ + __esModule: true, + default: { + outDir: "/mock/app/context/outDir", + }, +})); + +const mockGenerateSwiftDriver = generateSwiftDriver as jest.MockedFunction< + typeof generateSwiftDriver +>; + +/*********************************************************** + * getSwiftDriverFile + ***********************************************************/ +describe("getSwiftDriverFile", () => { + it("should return Swift driver output file", async () => { + const projectConfig = {}; + const meta = {}; + const result = await getSwiftDriverFile( + meta, + projectConfig as ProjectConfigYAML + ); + expect(result).toBeInstanceOf(SwiftOutputFile); + expect(result.filename).toBe("Ditto"); + expect(result.path).toBe("/mock/app/context/outDir"); + }); + + it("should return Swift driver output file with projects from projectConfig", async () => { + const projectConfig = { + projects: [{ id: "project1" }], + }; + const meta = {}; + const mockSwiftDriver = "import Foundation\nclass Ditto { }"; + mockGenerateSwiftDriver.mockResolvedValue(mockSwiftDriver); + + const result = await getSwiftDriverFile( + meta, + projectConfig as ProjectConfigYAML + ); + + expect(mockGenerateSwiftDriver).toHaveBeenCalledWith( + { projects: [{ id: "project1" }] }, + meta + ); + expect(result).toBeInstanceOf(SwiftOutputFile); + }); + + it("should return Swift driver output file with components folders from projectConfig", async () => { + const projectConfig = { + components: { + folders: [{ id: "folder1" }, { id: "folder2" }], + }, + }; + const meta = {}; + const mockSwiftDriver = "import Foundation\nclass Ditto { }"; + mockGenerateSwiftDriver.mockResolvedValue(mockSwiftDriver); + + const result = await getSwiftDriverFile( + meta, + projectConfig as ProjectConfigYAML + ); + + expect(mockGenerateSwiftDriver).toHaveBeenCalledWith( + { + components: { + folders: [{ id: "folder1" }, { id: "folder2" }], + }, + projects: [], + }, + meta + ); + expect(result).toBeInstanceOf(SwiftOutputFile); + }); +}); diff --git a/lib/src/utils/getSwiftDriverFile.ts b/lib/src/utils/getSwiftDriverFile.ts new file mode 100644 index 0000000..da614e9 --- /dev/null +++ b/lib/src/utils/getSwiftDriverFile.ts @@ -0,0 +1,23 @@ +import SwiftOutputFile from "../formatters/shared/fileTypes/SwiftOutputFile"; +import generateSwiftDriver from "../http/cli"; +import { CommandMetaFlags } from "../http/types"; +import { ProjectConfigYAML } from "../services/projectConfig"; +import appContext from "./appContext"; + +export default async function getSwiftDriverFile( + meta: CommandMetaFlags, + projectConfig: ProjectConfigYAML +): Promise { + const folders = projectConfig.components?.folders; + + const filters = { + ...(folders && { components: { folders } }), + projects: projectConfig.projects || [], + }; + + const swiftDriver = await generateSwiftDriver(filters, meta); + return new SwiftOutputFile({ + path: appContext.outDir, + content: swiftDriver, + }); +} diff --git a/package.json b/package.json index 86d06a9..f6b065b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@dittowords/cli", - "version": "5.2.0", + "version": "5.3.0", "description": "Command Line Interface for Ditto (dittowords.com).", "license": "MIT", "main": "bin/ditto.js",