import { SDTFEngine, createSDTFEngine } from '@specifyapp/specify-design-token-format'; import type { ToStyleDictionaryParserDefinition } from './definition.js'; import { SpecifyError, specifyErrors } from '../../../errors/index.js'; import type { DeriveBuiltInParserHandlerFromDefinition } from '../../internals/createBuiltInParserDefinition.js'; import type { FilesOutput } from '../../../parsersEngine/index.js'; import { sortedTokensToFiles } from './sortedTokensToFiles.js'; import { sortTokenStatesToStyleDictionary } from './sortTokensToStyleDictionary.js'; export const toStyleDictionaryHandler: DeriveBuiltInParserHandlerFromDefinition< ToStyleDictionaryParserDefinition > = async (previousDataBox, toolbox, _parserOptions, outputOptions, _context) => { let sdtfEngine: SDTFEngine; switch (previousDataBox.type) { case 'SDTF': { sdtfEngine = createSDTFEngine(previousDataBox.graph, previousDataBox.metadata); break; } case 'SDTF Engine': { sdtfEngine = previousDataBox.engine; break; } default: { throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_INVALID_PARSER_INPUT.errorKey, publicMessage: `${ (previousDataBox as any).type } is not a valid input for the style-dictionary parser.`, }); } } if (outputOptions?.type !== 'directory') throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_INVALID_OUTPUT_TYPE.errorKey, publicMessage: `The output type ${outputOptions?.type} is not supported by the to-style-dictionary parser.`, }); const { directoryPath } = outputOptions; const tokenStates = sdtfEngine.query.getAllTokenStates(); let output: FilesOutput['files'] = []; if (tokenStates.length === 0) { toolbox.populateMessage({ type: 'warning', content: `No design tokens found in the input`, errorKey: specifyErrors.PARSERS_ENGINE_PARSER_EXECUTION_FAILED.errorKey, }); output = []; } else { output = sortedTokensToFiles(sortTokenStatesToStyleDictionary(tokenStates), directoryPath); } toolbox.populateOutput({ type: 'files', files: output, }); const { tokenTree, metadata } = sdtfEngine.exportEngineState(); return { type: 'SDTF Engine', engine: sdtfEngine, }; };