|
| 1 | +/** @import { TSESTree } from '@typescript-eslint/types' */ |
| 2 | +import * as acorn from 'acorn'; |
| 3 | +import { tsPlugin } from '@sveltejs/acorn-typescript'; |
| 4 | +import { walk } from 'zimmerframe'; |
| 5 | +import MagicString from 'magic-string'; |
| 6 | + |
| 7 | +const TSParser = acorn.Parser.extend(tsPlugin()); |
| 8 | + |
| 9 | +/** |
| 10 | + * @param {string} content |
| 11 | + * @returns {MagicString} |
| 12 | + */ |
| 13 | +export function stripTypes(content) { |
| 14 | + const ast = /** @type {unknown} */ ( |
| 15 | + TSParser.parse(content, { |
| 16 | + sourceType: 'module', |
| 17 | + ecmaVersion: 13, |
| 18 | + locations: true |
| 19 | + }) |
| 20 | + ); |
| 21 | + |
| 22 | + const s = new MagicString(content); |
| 23 | + |
| 24 | + walk(/** @type {TSESTree.Node & { start: number, end: number }} */ (ast), null, { |
| 25 | + _: (node, context) => { |
| 26 | + if ( |
| 27 | + node.type.startsWith('TS') && |
| 28 | + !['TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression'].includes(node.type) |
| 29 | + ) { |
| 30 | + const { start, end } = node; |
| 31 | + s.overwrite(start, end, ' '.repeat(end - start)); |
| 32 | + } else { |
| 33 | + context.next(); |
| 34 | + } |
| 35 | + }, |
| 36 | + TSAsExpression: (node) => { |
| 37 | + handle_type_expression(node, s); |
| 38 | + }, |
| 39 | + TSSatisfiesExpression: (node) => { |
| 40 | + handle_type_expression(node, s); |
| 41 | + }, |
| 42 | + TSNonNullExpression: (node, context) => { |
| 43 | + s.overwrite(node.end - 1, node.end, ' '); |
| 44 | + context.next(); |
| 45 | + }, |
| 46 | + ImportDeclaration: (node, context) => { |
| 47 | + if ( |
| 48 | + node.importKind === 'type' || |
| 49 | + node.specifiers.every( |
| 50 | + (specifier) => specifier.type === 'ImportSpecifier' && specifier.importKind === 'type' |
| 51 | + ) |
| 52 | + ) { |
| 53 | + const { start, end } = node; |
| 54 | + s.overwrite(start, end, ' '.repeat(end - start)); |
| 55 | + } else { |
| 56 | + context.next(); |
| 57 | + } |
| 58 | + }, |
| 59 | + ImportSpecifier: (node, context) => { |
| 60 | + if (node.importKind === 'type') { |
| 61 | + const { start, end } = node; |
| 62 | + s.overwrite(start, end, ' '.repeat(end - start)); |
| 63 | + } else { |
| 64 | + context.next(); |
| 65 | + } |
| 66 | + } |
| 67 | + }); |
| 68 | + |
| 69 | + return s; |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * @param {TSESTree.Node} node |
| 74 | + * @param {MagicString} s |
| 75 | + */ |
| 76 | +function handle_type_expression(node, s) { |
| 77 | + // @ts-ignore |
| 78 | + const start = node.expression.end; |
| 79 | + |
| 80 | + // @ts-ignore |
| 81 | + const end = node.typeAnnotation.end; |
| 82 | + |
| 83 | + s.overwrite(start, end, ' '.repeat(end - start)); |
| 84 | +} |
0 commit comments