Skip to content

Commit 40d30ea

Browse files
committed
optimize packaging code
1 parent 9928bfb commit 40d30ea

8 files changed

+121
-63
lines changed

components/Graphviz.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,10 @@ const Graphviz = (props,ref) => {
121121

122122
useImperativeHandle(ref,()=>{
123123
return {
124-
renderSvg
124+
renderSvg,
125+
clear(){
126+
select(`#${eleRef.current.id}`).html("")
127+
}
125128
}
126129
})
127130

components/SelectEntryModal.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {generateSplicedCode} from "@/cg/common";
77
const SelectEntryModal = (props,ref)=>{
88
const {list = []} = props
99
const [searchText, setSearchText] = useState('');
10-
const {renderFiltedSvg,push, clear, setCode} = useContext(PageContext)
10+
const {renderFiltedSvg,push, clear, setCode, renderExpDot} = useContext(PageContext)
1111
const modalRef = useRef()
1212

1313
useImperativeHandle(ref,()=>{
@@ -55,6 +55,8 @@ const SelectEntryModal = (props,ref)=>{
5555
draft[key] = splicedCode[key]
5656
}
5757
})
58+
clear()
59+
renderExpDot()
5860
modalManager.closeAllModals()
5961
}
6062
}}>

components/Settings.js

+18-2
Original file line numberDiff line numberDiff line change
@@ -76,12 +76,28 @@ export default (props)=>{
7676
name,
7777
subPath
7878
}
79-
return fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${subPath}${name ? ('?ref=' + name) : ''}`).then(res=>res.json())
79+
try {
80+
const headers = process.env.NEXT_PUBLIC_GIT_TOKEN ? {Authorization: `token ${process.env.NEXT_PUBLIC_GIT_TOKEN}`} : {}
81+
return fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${subPath}${name ? ('?ref=' + name) : ''}`,{
82+
headers
83+
}).then(res=>res.json())
84+
} catch (err){
85+
if(err.message){
86+
setToast(draft => {
87+
draft.isOpen = true
88+
draft.message = err.message
89+
})
90+
}
91+
return Promise.reject(err)
92+
}
8093
}
8194

8295
const onSearchGh = ({language=[],keyword})=>{
8396
const lg = language.map(lan=> `language:${lan}`).join('+')
84-
return fetch(`https://api.github.com/search/repositories?q=${lg}+${keyword}`).then(res=>res.json()).then((res)=>{
97+
const headers = process.env.NEXT_PUBLIC_GIT_TOKEN ? {Authorization: `token ${process.env.NEXT_PUBLIC_GIT_TOKEN}`} : {}
98+
return fetch(`https://api.github.com/search/repositories?q=${lg}+${keyword}`,{
99+
headers
100+
}).then(res=>res.json()).then((res)=>{
85101
if(res.message){
86102
setToast(draft => {
87103
draft.isOpen = true

generate_recommend.js

+25-1
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,42 @@ const recommendRepo = [
1818
name:'',
1919
subPath:'src/core/index.ts'
2020
},
21+
{
22+
key:'1',
23+
owner:'vuejs',
24+
repo:'vue-loader',
25+
name:'',
26+
subPath:'src/index.ts'
27+
},
2128
{
2229
key:'1',
2330
owner:'axios',
2431
repo:'axios',
2532
name:'',
2633
subPath:'lib/axios.js'
34+
},
35+
{
36+
key:'1',
37+
owner:'babel',
38+
repo:'babel',
39+
name:'',
40+
subPath:'packages/babel-generator/src/index.ts'
41+
},
42+
{
43+
key:'1',
44+
owner:'babel',
45+
repo:'babel',
46+
name:'',
47+
subPath:'packages/babel-parser/src/index.ts'
2748
}
2849
]
50+
51+
2952
const userCollection = db.collection('users')
3053

3154

3255
async function start(){
33-
const recommendTasks = await userCollection.find({key:'1'}).toArray()
56+
let recommendTasks = await userCollection.find({key:'1'}).toArray()
3457
if(recommendTasks.length === 0){
3558
const docs = recommendRepo.map(task=>{
3659
return {
@@ -40,6 +63,7 @@ async function start(){
4063
}
4164
})
4265
await userCollection.insertMany(docs)
66+
recommendTasks = await userCollection.find({key:'1'}).toArray()
4367
}
4468
await Promise.all(
4569
recommendTasks.filter(task=> [TASKSTATUS.BUNDLEDERROR, TASKSTATUS.REPOCLONEDENDERROR].includes(task.status)).map(task=>{

pages/index.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,10 @@ export default function Home(props) {
142142
}
143143
return renderSvg(dot).then(() => ({dot, nodes}))
144144
}
145-
145+
const renderExpDot = ()=> {
146+
const {clear} = graphvizRef.current
147+
clear()
148+
}
146149
const popperRef = useRef()
147150
const chatRef = useRef()
148151
return (
@@ -152,7 +155,8 @@ export default function Home(props) {
152155
getBatchConfigByCode,
153156
push,
154157
clear,
155-
setCode
158+
setCode,
159+
renderExpDot
156160
}}>
157161
<Graphviz
158162
className={'codeSvg'}

plugins.js

+40-31
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const t = require('@babel/types')
77
const ts = require("typescript");
88
const {minimatch} = require('minimatch');
99

10-
function tsCompile(source, options = null) {
10+
function tsCompile({source, options = null}) {
1111
// 默认选项,您也可以合并或使用项目的tsconfig.json文件
1212
if (null === options) {
1313
options = {
@@ -22,10 +22,13 @@ function tsCompile(source, options = null) {
2222
let result = ts.transpileModule(source, options);
2323

2424
// 返回JavaScript代码
25-
return result.outputText;
25+
return {
26+
code: result.outputText,
27+
map: result.sourceMapText
28+
}
2629
}
2730

28-
function tsconfigAlias({baseUrl,paths = []}) {
31+
function tsPlugin({baseUrl,paths = []}){
2932
// 定义一个空数组,用于存储转换后的别名对象
3033
const entries = [];
3134

@@ -34,37 +37,57 @@ function tsconfigAlias({baseUrl,paths = []}) {
3437
// 获取别名的路径数组,对每个元素,去掉开头和末尾的星号(如果有),并转换为绝对路径
3538
const find = value.map((v) => path.join(baseUrl, v.replace(/^\*|\*$/g, '')));
3639

40+
const name = key.endsWith('*') ? key + '*' : key
41+
3742
// 创建一个别名对象,包含name和find属性,并添加到数组中
38-
entries.push({ name: key, find });
43+
entries.push({ name, find });
3944
}
4045
const extensions = ['.js', '.ts', '.jsx', '.tsx', '.json'];
41-
42-
// 返回一个Rollup插件对象,包含resolveId方法
4346
return {
44-
name: 'tsconfig-alias',
47+
name:'ts-plugin',
48+
transform(code,id){
49+
if(/\.d\.ts$/.test(id)) return
50+
51+
return tsCompile({
52+
source: code,
53+
options:{
54+
compilerOptions: {
55+
module: ts.ModuleKind.ESNext,
56+
target: ts.ScriptTarget.ES2020
57+
},
58+
// transformers: { before: [transformImportEqualsRequire] }
59+
}
60+
})
61+
},
4562
resolveId(importee,importer) {
4663
if (!importer || !entries.length) {
4764
return this.resolve(importee, importer, { skipSelf: true });
4865
}
4966
// 对每个模块路径,检查是否匹配某个别名对象的名称,如果是,就遍历该别名对象的路径数组,尝试读取文件内容并返回
5067
for (const entry of entries) {
5168
if (minimatch(importee,entry.name)) {
52-
const relativePath = entry.name.endsWith('*') ? importee.slice(entry.name.length -1) : '.';
69+
const relativePath = entry.name.endsWith('**') ? importee.slice(entry.name.length -2) : '.';
5370

5471
for (const find of entry.find) {
55-
const potentialPaths = extensions.map(ext => path.join(find, relativePath + ext));
72+
const potentialPaths = extensions.map(ext => {
73+
if(relativePath === '.'){
74+
return find + ext
75+
}
76+
return path.join(find, relativePath + ext)
77+
});
5678

5779
for (const potentialPath of potentialPaths) {
5880
if (fs.existsSync(potentialPath)) {
5981
return { id: potentialPath, moduleSideEffects: false };
6082
}
6183
}
84+
if(relativePath !== '.'){
85+
for (const ext of extensions) {
86+
const indexPath = path.join(find, relativePath,`index${ext}`);
6287

63-
for (const ext of extensions) {
64-
const indexPath = path.join(find, relativePath,`index${ext}`);
65-
66-
if (fs.existsSync(indexPath)) {
67-
return { id: indexPath, moduleSideEffects: false };
88+
if (fs.existsSync(indexPath)) {
89+
return { id: indexPath, moduleSideEffects: false };
90+
}
6891
}
6992
}
7093
}
@@ -74,30 +97,16 @@ function tsconfigAlias({baseUrl,paths = []}) {
7497
}
7598
return null;
7699
},
77-
};
78-
}
79-
80-
function transformPublicClassFields(){
81-
return {
82-
name:'public-class-fields-plugin',
83-
visitor:{
84-
ClassDeclaration(path){
85-
const code = generator(path.node).code;
86-
const compiledCode = tsCompile(code)
87-
const ast = parser.parse(compiledCode);
88-
path.replaceWith(ast);
89-
path.skip();
90-
}
91-
}
92100
}
93101
}
94102

95103

104+
96105
module.exports = {
97106
rollup:{
98-
tsconfigAlias
107+
tsPlugin
99108
},
100109
babel:{
101-
transformPublicClassFields
110+
102111
}
103112
}

rollup.js

+21-23
Original file line numberDiff line numberDiff line change
@@ -35,23 +35,24 @@ const rollupBuild = ({entry, output, repoPath})=>{
3535
return rollup({
3636
input: entry,
3737
plugins: [
38-
json(),
39-
commonjs({
40-
strictRequires: true
41-
}),
4238
resolve({
4339
extensions:['.js','.ts','.json']
44-
}),// 解析 node_modules 中的模块
45-
rollupPlugins.tsconfigAlias({
40+
}),
41+
json(),
42+
rollupPlugins.tsPlugin({
4643
baseUrl: finalBaseUrl,
4744
paths: tsConfigPathDir ? parsedConfig.options.paths :undefined
4845
}),
49-
babel({
50-
plugins:[
51-
["@babel/plugin-transform-typescript",{allowDeclareFields: true}],
52-
],
53-
extensions:['.js', '.jsx', '.es6', '.es', '.mjs','.ts']
54-
})
46+
// typescriptPaths({
47+
// tsConfigPath: path.join(tsConfigPathDir,'tsconfig.json')
48+
// }),
49+
commonjs()
50+
// babel({
51+
// plugins:[
52+
// ["@babel/plugin-transform-typescript",{allowDeclareFields: true}]
53+
// ],
54+
// extensions:['.js', '.jsx', '.es6', '.es', '.mjs','.ts']
55+
// })
5556
],
5657
external: external()
5758

@@ -63,17 +64,14 @@ const rollupBuild = ({entry, output, repoPath})=>{
6364
// sourcemap: true
6465
}).then(async res=>{
6566
const {code} = res.output[0]
66-
const ast = parse(code,{
67-
sourceType:'unambiguous'
68-
})
69-
traverse(
70-
ast,
71-
babelPlugins.transformPublicClassFields().visitor
72-
)
73-
return Buffer.from(
74-
generateCode(ast).code,
75-
'utf8'
76-
)
67+
// const ast = parse(code,{
68+
// sourceType:'unambiguous'
69+
// })
70+
// traverse(
71+
// ast,
72+
// babelPlugins.transformPublicClassFields().visitor
73+
// )
74+
return Buffer.from(code)
7775
.toString('base64')
7876
})
7977
})

task.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,12 @@ class BundleManager {
7979
)
8080
await rimraf(gitDir)
8181
}).catch(async e=>{
82-
logger.error(`clone error ${repoPath}`,e)
8382
await this.usersCollection.updateOne(
8483
{_id},
8584
{ $set: {status: TASKSTATUS.REPOCLONEDENDERROR} }
8685
)
86+
logger.error(`clone error ${repoPath}`,e)
87+
return Promise.reject(e)
8788
})
8889
}
8990
async generateBundle(user){
@@ -104,11 +105,12 @@ class BundleManager {
104105
)
105106
await rimraf(repoPath)
106107
}).catch(async e=>{
107-
logger.error(`bundle error ${repoPath} ${subPath}`,e)
108108
await this.usersCollection.updateOne(
109109
{_id},
110110
{ $set: {status: TASKSTATUS.BUNDLEDERROR} }
111111
)
112+
logger.error(`bundle error ${repoPath} ${subPath}`,e)
113+
return Promise.reject(e)
112114
})
113115
}
114116
}

0 commit comments

Comments
 (0)