Skip to content

Commit

Permalink
Merge pull request #81 from ryoppippi/fix-for-bun
Browse files Browse the repository at this point in the history
feat(unplugin-typia): add typia mjs path resolution
  • Loading branch information
ryoppippi authored Jun 11, 2024
2 parents db59c65 + d832d82 commit 3b186a2
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
Binary file modified bun.lockb
Binary file not shown.
2 changes: 2 additions & 0 deletions packages/unplugin-typia/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@
},
"dependencies": {
"@rollup/pluginutils": "^5.1.0",
"@sxzz/ast-kit": "npm:@jsr/sxzz__ast-kit",
"@sxzz/magic-string-ast": "npm:@jsr/sxzz__magic-string-ast",
"pathe": "^1.1.2",
"typescript": "^5.3.2",
"unplugin": "^1.5.1"
Expand Down
39 changes: 37 additions & 2 deletions packages/unplugin-typia/src/bun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,48 @@

import type { BunPlugin } from 'bun';
import type { UnpluginContextMeta } from 'unplugin';
import { readPackageJSON, resolvePackageJSON } from 'pkg-types';
import { babelParse, getLang } from '@sxzz/ast-kit';
import { MagicStringAST } from '@sxzz/magic-string-ast';
import { dirname, join } from 'pathe';
import { type Options, resolveOptions, unplugin } from './api.js';
import { defaultOptions } from './core/options.js';

if (globalThis.Bun == null) {
throw new Error('You must use this plugin with bun');
}

/* cache typia mjs path */
let typiaMjsPath: string | undefined;
/**
* Read typia mjs path.
* TODO: delete after [this issue](https://github.com/oven-sh/bun/issues/11783) is resolved.
*/
async function resolveTypiaPath(id: string, code: string) {
if (typiaMjsPath == null) {
const typiaPackageJson = await readPackageJSON('typia');
const typiaDirName = dirname(await resolvePackageJSON('typia'));
typiaMjsPath = join(typiaDirName, typiaPackageJson?.module ?? '');
}

const ms = new MagicStringAST(code);

const program = babelParse(code, getLang(id), {});
for (const node of program.body) {
if (
node.type === 'ImportDeclaration'
&& node.importKind !== 'type'
&& ms.sliceNode(node.source) === 'typia'
) {
ms.overwriteNode(node.source, `${typiaMjsPath}"`);
}
}

const r = ms.toString();

return r;
}

/**
* bun plugin
*
Expand Down Expand Up @@ -79,7 +114,7 @@ function bunTypiaPlugin(

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

Expand All @@ -105,7 +140,7 @@ function bunTypiaPlugin(
case typeof result === 'string':
return { contents: source };
default:
return { contents: result.code };
return { contents: await resolveTypiaPath(path, result.code) };
}
});
},
Expand Down

0 comments on commit 3b186a2

Please sign in to comment.