{"version":3,"names":["assertExpressionStatement","makeStatementFormatter","fn","code","str","validate","unwrap","ast","program","body","slice","smart","length","statements","statement","Error","expression","start","stmt"],"sources":["../src/formatters.ts"],"sourcesContent":["import { assertExpressionStatement } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\nexport type Formatter<T> = {\n code: (source: string) => string;\n validate: (ast: t.File) => void;\n unwrap: (ast: t.File) => T;\n};\n\nfunction makeStatementFormatter<T>(\n fn: (statements: Array<t.Statement>) => T,\n): Formatter<T> {\n return {\n // We need to prepend a \";\" to force statement parsing so that\n // ExpressionStatement strings won't be parsed as directives.\n // Alongside that, we also prepend a comment so that when a syntax error\n // is encountered, the user will be less likely to get confused about\n // where the random semicolon came from.\n code: str => `/* @babel/template */;\\n${str}`,\n validate: () => {},\n unwrap: (ast: t.File): T => {\n return fn(ast.program.body.slice(1));\n },\n };\n}\n\nexport const smart = makeStatementFormatter(body => {\n if (body.length > 1) {\n return body;\n } else {\n return body[0];\n }\n});\n\nexport const statements = makeStatementFormatter(body => body);\n\nexport const statement = makeStatementFormatter(body => {\n // We do this validation when unwrapping since the replacement process\n // could have added or removed statements.\n if (body.length === 0) {\n throw new Error(\"Found nothing to return.\");\n }\n if (body.length > 1) {\n throw new Error(\"Found multiple statements but wanted one\");\n }\n\n return body[0];\n});\n\nexport const expression: Formatter<t.Expression> = {\n code: str => `(\\n${str}\\n)`,\n validate: ast => {\n if (ast.program.body.length > 1) {\n throw new Error(\"Found multiple statements but wanted one\");\n }\n if (expression.unwrap(ast).start === 0) {\n throw new Error(\"Parse result included parens.\");\n }\n },\n unwrap: ({ program }) => {\n const [stmt] = program.body;\n assertExpressionStatement(stmt);\n return stmt.expression;\n },\n};\n\nexport const program: Formatter<t.Program> = {\n code: str => str,\n validate: () => {},\n unwrap: ast => ast.program,\n};\n"],"mappings":";;;;;;AAAA;AAAyD;EAAhDA;AAAyB;AASlC,SAASC,sBAAsB,CAC7BC,EAAyC,EAC3B;EACd,OAAO;IAMLC,IAAI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