-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
90 lines (78 loc) · 2.2 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import path from 'node:path';
import { $, type BunPlugin, Glob } from 'bun';
// @ts-expect-error no type
import _isGlob from 'is-glob';
import { oxcTransform } from 'unplugin-isolated-decl/api';
// eslint-disable-next-line ts/no-unsafe-assignment
const isGlob: (str: string) => boolean = _isGlob;
export type TransformResult = {
code: string;
errors: string[];
};
type Entry = {
id: string;
source: string;
};
/**
* Options for the plugin
*/
type Options = {
/** generate declaration files even though there are errors */
forceGenerate?: boolean;
};
function isolatedDecl(options: Options = {}): BunPlugin {
return {
name: 'bun-plugin-isolated-decl',
async setup(build): Promise<void> {
const entrypoints = [...build.config.entrypoints].sort();
const entriies: Entry[] = [];
const outdir = build.config?.outdir ?? './out';
const resolvedOptions = {
forceGenerate: false,
...options,
} satisfies Options;
await $`mkdir -p ${outdir}`;
for (const entry of entrypoints) {
if (isGlob(entry)) {
const globs = new Glob(entry);
for await (const entry of globs.scan()) {
const file = Bun.file(entry);
if (!(await file.exists())) {
console.error(`File ${entry} does not exist`);
continue;
}
const source = await file.text();
entriies.push({ id: entry, source });
}
}
else {
const file = Bun.file(entry);
if (!(await file.exists())) {
console.error(`File ${entry} does not exist`);
continue;
}
const source = await file.text();
entriies.push({ id: entry, source });
}
}
for (const { id, source } of entriies) {
const { code, errors } = await oxcTransform(id, source);
if (errors.length > 0) {
console.error(`Error in ${id}`);
for (const error of errors) {
console.error(error);
}
/* If there are errors, we don't want to generate declaration files */
if (!resolvedOptions.forceGenerate) {
continue;
}
}
const dtsID = id.replace(/^.*\//, '').replace(/\.[jtm]s$/, '.d.ts');
const _path = path.resolve(outdir, dtsID);
await $`touch ${_path}`;
await $`echo ${code} > ${_path}`;
}
},
};
}
export default isolatedDecl;