Skip to content

Commit

Permalink
feat: axios set proxy https agent, timeout tip (#10853)
Browse files Browse the repository at this point in the history
* feat: use system proxy, timeout log

* fix: files add compiled, deps lock

* feat: socks proxy

* feat: basic prompt for umi command
  • Loading branch information
xyuanbuilds authored Apr 6, 2023
1 parent fc122e7 commit aa16d22
Show file tree
Hide file tree
Showing 16 changed files with 214 additions and 17 deletions.
1 change: 1 addition & 0 deletions copilot/compiled/https-proxy-agent/index.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions copilot/compiled/https-proxy-agent/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"https-proxy-agent","version":"5.0.1","author":"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)","license":"MIT","types":"dist/index"}
1 change: 1 addition & 0 deletions copilot/compiled/socks-proxy-agent/index.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions copilot/compiled/socks-proxy-agent/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"socks-proxy-agent","version":"7.0.0","author":{"email":"nathan@tootallnate.net","name":"Nathan Rajlich","url":"http://n8.io/"},"license":"MIT","typings":"dist/index.d.ts"}
20 changes: 18 additions & 2 deletions copilot/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
},
"files": [
"bin",
"dist"
"dist",
"compiled"
],
"scripts": {
"build": "father build",
"build:deps": "umi-scripts bundleDeps",
"dev": "father dev",
"doctor": "father doctor",
"prebundle": "father prebundle",
Expand All @@ -26,10 +28,24 @@
"@umijs/utils": "workspace:*",
"zx": "^7.2.1"
},
"devDependencies": {
"https-proxy-agent": "5.0.1",
"socks-proxy-agent": "7.0.0"
},
"publishConfig": {
"access": "public"
},
"authors": [
"chencheng <sorrycc@gmail.com> (https://github.com/sorrycc)"
]
],
"compiledConfig": {
"deps": [
"https-proxy-agent",
"socks-proxy-agent"
],
"excludeDtsDeps": [
"https-proxy-agent",
"socks-proxy-agent"
]
}
}
37 changes: 35 additions & 2 deletions copilot/src/chatgpt.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,26 @@
import { axios } from '@umijs/utils';
import { axios, chalk, logger } from '@umijs/utils';
// @ts-ignore
import HttpsProxyAgent from '../compiled/https-proxy-agent';
// @ts-ignore
import { SocksProxyAgent } from '../compiled/socks-proxy-agent';

// for system proxy
const httpProxyUri = process.env.HTTPS_PROXY || process.env.HTTP_PROXY;
const socksProxyUri = process.env.ALL_PROXY;

let axiosProxy: ReturnType<typeof axios.create> | null = null;

if (socksProxyUri) {
axiosProxy = axios.create({
proxy: false,
httpsAgent: new SocksProxyAgent(socksProxyUri),
});
} else if (httpProxyUri) {
axiosProxy = axios.create({
proxy: false,
httpsAgent: new HttpsProxyAgent(httpProxyUri),
});
}

interface IMessage {
role: 'system' | 'user' | 'assistant';
Expand Down Expand Up @@ -47,9 +69,11 @@ export async function sendMessage(opts: {
timeout?: number;
}) {
const apiUrl = getApiUrl(opts.proxyUrl);
const axiosInstance = axiosProxy || axios;

let res: any = null;
try {
res = await axios.post<IChatGPTResponse>(
res = await axiosInstance.post<IChatGPTResponse>(
apiUrl,
{
...requestParamsBase,
Expand All @@ -70,6 +94,15 @@ export async function sendMessage(opts: {
if (opts.controller?.signal.aborted === true) {
// 用户手动取消了请求
} else {
if (e.message.includes('timeout')) {
logger.fatal(e.message);
logger.warn('Request is too slow or cannot be requested');
logger.warn(
`Recommended to use a proxy host by passing ${chalk.yellow(
'--proxy-url',
)}`,
);
}
throw new Error('Network Error');
}
}
Expand Down
44 changes: 37 additions & 7 deletions copilot/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { chalk, clackPrompts, logger, resolve, yParser } from '@umijs/utils';
import { sendMessage } from './chatgpt';
import { SYSTEM_PROMPT } from './constants';
import { printHelp } from './printHelp';
import prompts from './prompts';
const { confirm, spinner } = clackPrompts;

export async function main() {
Expand All @@ -27,23 +27,53 @@ export async function main() {
const message = args._.join(' ');
const s = spinner();
s.start('🕖 Hold on, asking OpenAI...');
const res = await sendMessage({

const commonParams = {
token,
proxyUrl: args.proxyUrl,
};

const commandRes = await sendMessage({
messages: [
{
role: 'system',
content: SYSTEM_PROMPT,
content: prompts.commands,
},
{
role: 'user',
content: message,
},
],
token,
// --proxy-url
proxyUrl: args.proxyUrl,
...commonParams,
});
const willUseCommand: string = commandRes.data.choices[0].message.content;

if (!prompts[willUseCommand]) {
logger.warn(willUseCommand);
throw new Error('No matching command');
}

const questionRes = await sendMessage({
messages: [
{
role: 'system',
content: `${prompts[willUseCommand]}.无法根据要求返回命令时,给出提示`,
},
{
role: 'user',
content: message,
},
],
...commonParams,
});
s.stop();
const command = res.data.choices[0].message.content;
const command = questionRes.data.choices[0].message.content;

if (!/^[\w\s=\-'"{}:.]+$/.test(command)) {
logger.warn(command);
return;
}

logger.info('The suggested command is:');
logger.info(chalk.green(command));

Expand Down
10 changes: 10 additions & 0 deletions copilot/src/prompts/build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const BUILD_PROMPT = `
umi build 命令用于构建项目.有以下功能:
- 通过COMPRESS环境变量值为 none,让构建不进行压缩。
环境变量需要在命令前传递,如:COMPRESS=none umi build
基于以上知识,根据我的要求,返回我应该使用的命令,只需返回这条命令,不包括任何其他信息,不做任何提示
`;

export default BUILD_PROMPT;
10 changes: 10 additions & 0 deletions copilot/src/prompts/commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const COMMAND_PROMPT = `
umi 命令行有以下功能:
- dev 启动本地开发服务器,进行项目的开发与调试
- build 构建项目
- generate 创建或生成文件,以使某些功能生效,可用于生效ts
- config 查看所有或某个配置,或修改删除某个配置
基于以上知识,根据我的要求,返回我应该使用的命令,只返回命令名称,如:dev,不清楚用哪个命令时统一用config,不需要任何其他信息
`;

export default COMMAND_PROMPT;
40 changes: 40 additions & 0 deletions copilot/src/prompts/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const CONFIG_PROMPT = `
umi config 命令用于查看或修改配置,有以下功能:
- 传递 list 参数,列举当前项目所有配置
- 传递 get,配置名,两个参数查看该配置的具体值
- 传递 set,配置名,配置值,三个参数修改配置
- 传递 remove,配置名,配置值,三个参数去除配置
配置的ts类型如下,类型属性对应配置名:
\`
interface IConfig {
alias?: Record<string, string>;
autoCSSModules?: boolean;
base?: string;
/** copy file to dist */
copy?: { from: string; to: string; }[] | string[];
cssLoader?: { [key: string]: any };
cssMinifier?: "esbuild" | "none" | "cssnano" | "pacelCSS";
define?: { [key: string]: any };
depTranspiler?: "babel" | "swc" | "esbuild" | "none";
/** change source-map type */
devtool: 'eval'|'eval-cheap-source-map'|'eval-cheap-module-source-map'|'eval-source-map'|'cheap-source-map'|'cheap-module-source-map'|'source-map'|'inline-cheap-source-map'|'inline-cheap-module-source-map'|'inline-source-map';
hash?: boolean;
ignoreMomentLocale?: boolean;
jsMinifier?: "swc" | "esbuild" | "none" | "terser" | "uglifyJs";
jsMinifierOptions?: { [key: string]: any };
lessLoader?: { lessOptions: any };
mfsu?: {} | false;
outputPath?: string;
polyfill?: any;
publicPath?: string;
sassLoader?: { [key: string]: any };
targets?: { [key: string]: any };
writeToDisk?: boolean;
babelLoaderCustomize?: string;
esbuildMinifyIIFE?: boolean;
}
\`
基于以上知识,根据我的要求,返回我应该使用的命令,只需返回这条命令,不包括任何其他信息,不做任何提示
`;
export default CONFIG_PROMPT;
13 changes: 13 additions & 0 deletions copilot/src/prompts/dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const DEV_PROMPT = `
umi dev 命令用于启动本地开发服务器.有以下功能:
- 通过PORT 环境变量指定开发服务器启动指定端口
- 通过MOCK 环境变量为none,来去除mock
环境变量的使用方法是在命令之前加入环境变量,如:
PORT=10 umi dev
MOCK=none umi dev
基于以上知识,根据我的要求,返回我应该使用的命令,只需返回这条命令,不包括任何其他信息,不做任何提示
`;

export default DEV_PROMPT;
9 changes: 9 additions & 0 deletions copilot/src/prompts/generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const GEN_PROMPT = `
umi g 用于增量生成文件或启用功能,有以下功能:
- 不加任何参数,直接执行选择
- 通过参数tsconfig,启用typescript
基于以上知识,根据我的要求,返回我应该使用的命令,只需返回这条命令,不包括任何其他信息,不做任何提示
`;

export default GEN_PROMPT;
15 changes: 15 additions & 0 deletions copilot/src/prompts/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import build from './build';
import commands from './commands';
import config from './config';
import dev from './dev';
import generate from './generate';

const prompts: Record<string, string> = {
commands,
dev,
build,
generate,
config,
};

export default prompts;
17 changes: 12 additions & 5 deletions packages/plugins/libs/qiankun/master/MicroApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,17 @@ export type Props = {
className?: string;
} & Record<string, any>;

function unmountMicroApp(microApp?: MicroAppType, updatingPromise?: Promise<void>) {
function unmountMicroApp(
microApp?: MicroAppType,
updatingPromise?: Promise<void>,
) {
if (microApp) {
microApp.mountPromise.then(() => {
switch (microApp.getStatus()) {
case "MOUNTED":
case 'MOUNTED':
microApp.unmount();
break;
case "UPDATING":
case 'UPDATING':
// UPDATING 阶段 updatingPromise 一定存在
updatingPromise!.then(() => microApp.unmount());
break;
Expand Down Expand Up @@ -156,7 +159,10 @@ export const MicroApp = forwardRef(
const stateForSlave = (useModel || noop)(
qiankunStateForSlaveModelNamespace,
);
const { entry, props: { settings: settingsFromConfig = {}, ...propsFromConfig } = {} } = appConfig || {};
const {
entry,
props: { settings: settingsFromConfig = {}, ...propsFromConfig } = {},
} = appConfig || {};

useEffect(() => {
setComponentError(null);
Expand Down Expand Up @@ -225,7 +231,8 @@ export const MicroApp = forwardRef(
},
);

return () => unmountMicroApp(microAppRef.current, updatingPromise.current);
return () =>
unmountMicroApp(microAppRef.current, updatingPromise.current);
}, [name]);

useEffect(() => {
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion scripts/bundleDeps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,9 @@ Object.keys(exported).forEach(function (key) {
code.includes('"node:') &&
opts.pkgName && // skip local file bundle like babel/bundle.js
opts.pkgName !== 'stylelint-declaration-block-no-ignored-properties' &&
opts.pkgName !== 'vite'
opts.pkgName !== 'vite' &&
opts.pkgName !== 'https-proxy-agent' &&
opts.pkgName !== 'socks-proxy-agent'
) {
throw new Error(`${opts.pkgName} has "node:"`);
}
Expand Down

0 comments on commit aa16d22

Please sign in to comment.