import type * as babelTypes from '@babel/types'
import {parse, type TransformOptions} from '@babel/core'
// helper function to parse a source file
export function parseSourceFile(
_source: string,
_filename: string,
babelOptions: TransformOptions,
): babelTypes.File {
let source = _source
let filename = _filename
if (filename.endsWith('.astro')) {
// append .ts to the filename so babel will parse it as typescript
filename += '.ts'
source = parseAstro(source)
} else if (filename.endsWith('.vue')) {
// append .ts to the filename so babel will parse it as typescript
filename += '.ts'
source = parseVue(source)
} else if (filename.endsWith('.svelte')) {
// append .ts to the filename so babel will parse it as typescript
filename += '.ts'
source = parseSvelte(source)
}
const result = parse(source, {
...babelOptions,
filename,
})
if (!result) {
throw new Error(`Failed to parse ${filename}`)
}
return result
}
function parseAstro(source: string): string {
// find all code fences, the js code is between --- and ---
// Handle both Unix (\n) and Windows (\r\n) line endings
const codeFences = source.match(/---\r?\n([\s\S]*?)\r?\n---/g)
if (!codeFences) {
return ''
}
return codeFences
.map((codeFence) => {
// Split on either \n or \r\n
return codeFence.split(/\r?\n/).slice(1, -1).join('\n')
})
.join('\n')
}
function parseVue(source: string): string {
// find all script tags, the js code is between
const scriptRegex = /
const scriptRegex = /