| 1 |
import { assertExpressionStatement } from "@babel/types"; |
| 2 |
import type * as t from "@babel/types"; |
| 3 |
|
| 4 |
export type Formatter<T> = { |
| 5 |
code: (source: string) => string; |
| 6 |
validate: (ast: t.File) => void; |
| 7 |
unwrap: (ast: t.File) => T; |
| 8 |
}; |
| 9 |
|
| 10 |
function makeStatementFormatter<T>( |
| 11 |
fn: (statements: Array<t.Statement>) => T, |
| 12 |
): Formatter<T> { |
| 13 |
return { |
| 14 |
// We need to prepend a ";" to force statement parsing so that |
| 15 |
// ExpressionStatement strings won't be parsed as directives. |
| 16 |
// Alongside that, we also prepend a comment so that when a syntax error |
| 17 |
// is encountered, the user will be less likely to get confused about |
| 18 |
// where the random semicolon came from. |
| 19 |
code: str => `/* @babel/template */;\n${str}`, |
| 20 |
validate: () => {}, |
| 21 |
unwrap: (ast: t.File): T => { |
| 22 |
return fn(ast.program.body.slice(1)); |
| 23 |
}, |
| 24 |
}; |
| 25 |
} |
| 26 |
|
| 27 |
export const smart = makeStatementFormatter(body => { |
| 28 |
if (body.length > 1) { |
| 29 |
return body; |
| 30 |
} else { |
| 31 |
return body[0]; |
| 32 |
} |
| 33 |
}); |
| 34 |
|
| 35 |
export const statements = makeStatementFormatter(body => body); |
| 36 |
|
| 37 |
export const statement = makeStatementFormatter(body => { |
| 38 |
// We do this validation when unwrapping since the replacement process |
| 39 |
// could have added or removed statements. |
| 40 |
if (body.length === 0) { |
| 41 |
throw new Error("Found nothing to return."); |
| 42 |
} |
| 43 |
if (body.length > 1) { |
| 44 |
throw new Error("Found multiple statements but wanted one"); |
| 45 |
} |
| 46 |
|
| 47 |
return body[0]; |
| 48 |
}); |
| 49 |
|
| 50 |
export const expression: Formatter<t.Expression> = { |
| 51 |
code: str => `(\n${str}\n)`, |
| 52 |
validate: ast => { |
| 53 |
if (ast.program.body.length > 1) { |
| 54 |
throw new Error("Found multiple statements but wanted one"); |
| 55 |
} |
| 56 |
if (expression.unwrap(ast).start === 0) { |
| 57 |
throw new Error("Parse result included parens."); |
| 58 |
} |
| 59 |
}, |
| 60 |
unwrap: ({ program }) => { |
| 61 |
const [stmt] = program.body; |
| 62 |
assertExpressionStatement(stmt); |
| 63 |
return stmt.expression; |
| 64 |
}, |
| 65 |
}; |
| 66 |
|
| 67 |
export const program: Formatter<t.Program> = { |
| 68 |
code: str => str, |
| 69 |
validate: () => {}, |
| 70 |
unwrap: ast => ast.program, |
| 71 |
}; |