Skip to content

Commit

Permalink
feat: Refactor bunTypiaPlugin to use unplugin
Browse files Browse the repository at this point in the history
This commit refactors the `bunTypiaPlugin` function to use the `unplugin`
module instead of the previous `transformTypia` function. The `transform`
function from `unplugin.raw` is now used to transform the source code.

The return type of the `transform` function is also handled differently.
If the result is `null` or a string, the original source is returned.
Otherwise, the transformed code from the result is returned.

This change improves the flexibility and maintainability of the code by
leveraging the `unplugin` module.
  • Loading branch information
ryoppippi committed Jun 8, 2024
1 parent 96b1c68 commit fa48046
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions packages/unplugin-typia/src/bun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
*/

import type { BunPlugin } from 'bun';
import { type Options, resolveOptions, transformTypia } from './api.js';
import type { UnpluginContextMeta } from 'unplugin';
import { type Options, resolveOptions, unplugin } from './api.js';
import { defaultOptions } from './core/options.js';

if (globalThis.Bun == null) {
Expand Down Expand Up @@ -52,11 +53,23 @@ if (globalThis.Bun == null) {
function bunTypiaPlugin(
options?: Options,
): BunPlugin {
const unpluginRaw = unplugin.raw(
options,
{} as UnpluginContextMeta,
);

const { transform } = unpluginRaw;

if (transform == null) {
throw new Error('transform is not defined');
}

const bunPlugin = ({
name: 'unplugin-typia',
setup(build) {
const resolvedOptions = resolveOptions(options ?? {});
const { include } = resolvedOptions;

const filter = include instanceof RegExp
? include
: typeof include === 'string'
Expand All @@ -70,16 +83,17 @@ function bunTypiaPlugin(

const source = await Bun.file(path).text();

const code = await transformTypia(
path,
source,
{ warn: console.warn } as Parameters<typeof transformTypia>[2],
resolvedOptions,
);
// @ts-expect-error type of this function is not correct
const result = await transform(source, path);

return {
contents: code ?? source,
};
switch (true) {
case result == null:
return { contents: source };
case typeof result === 'string':
return { contents: source };
default:
return { contents: result.code };
}
});
},
}) as const satisfies BunPlugin;
Expand Down

0 comments on commit fa48046

Please sign in to comment.