import { SDTFEngine, createSDTFEngine } from '@specifyapp/specify-design-token-format'; import { SpecifyError, specifyErrors } from '../../../errors/index.js'; import type { DeriveBuiltInParserHandlerFromDefinition } from '../../internals/createBuiltInParserDefinition.js'; import type { ToJavascriptParserDefinition } from './definition.js'; import { FilesOutput } from '../../../parsersEngine/index.js'; import { tokensToAst } from '../../shared/to-javascript/tokensToAst.js'; import { matcher } from './matcher.js'; import { generateCode } from '../../shared/to-javascript/generateCode.js'; export const toJavascriptHandler: DeriveBuiltInParserHandlerFromDefinition< ToJavascriptParserDefinition > = 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 to-javascript parser.`, }); } } if (outputOptions?.type !== 'file') throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_INVALID_OUTPUT_TYPE.errorKey, publicMessage: `The output type ${outputOptions?.type} is not supported by the to-javascript parser.`, }); let output: FilesOutput['files'] = []; const tokens = sdtfEngine.query.getAllTokenStates(); if (tokens.length === 0) { toolbox.populateMessage({ type: 'warning', content: `No design tokens found in the input`, errorKey: specifyErrors.PARSERS_ENGINE_PARSER_EXECUTION_FAILED.errorKey, }); } else { const ast = tokensToAst(tokens, matcher); output.push({ path: outputOptions.filePath, content: { type: 'text', text: generateCode(ast, { isTypescript: parserOptions?.typescript ?? false, exportStyle: parserOptions?.moduleExport ?? 'es6', }), }, }); } toolbox.populateOutput({ type: 'files', files: output, }); return { type: 'SDTF Engine', engine: sdtfEngine, }; };