This commit is contained in:
abearxiong 2025-02-27 00:38:36 +08:00
commit 5e29dd2a0d
42 changed files with 8517 additions and 0 deletions

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"workbench.editorAssociations": {
// "*.md": "vscode.markdown.preview.editor" //
"*.md": "default" //
}
}

5
README.md Normal file
View File

@ -0,0 +1,5 @@
## 微信登录
### 1. 获取微信登录二维码

14
app/.gitignore vendored Normal file
View File

@ -0,0 +1,14 @@
node_modules
dist
app.config.json5
apps.config.json
deploy.tar.gz
cache-file
/apps
logs

2
app/.npmrc Normal file
View File

@ -0,0 +1,2 @@
//npm.xiongxiao.me/:_authToken=${ME_NPM_TOKEN}
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

View File

@ -0,0 +1,3 @@
{
port: 3000,
}

68
app/package.json Normal file
View File

@ -0,0 +1,68 @@
{
"name": "demo-app",
"version": "0.0.1",
"description": "",
"main": "index.js",
"app": {
"key": "demo-app",
"entry": "dist/app.mjs",
"type": "system-app",
"files": [
"dist"
]
},
"scripts": {
"watch": "rollup -c rollup.config.mjs -w",
"dev": "cross-env NODE_ENV=development nodemon --delay 2.5 -e js,cjs,mjs --exec node dist/app.mjs",
"test": "tsx test/**/*.ts",
"dev:watch": "cross-env NODE_ENV=development concurrently -n \"Watch,Dev\" -c \"green,blue\" \"npm run watch\" \"sleep 1 && npm run dev\" ",
"clean": "rm -rf dist",
"prepub": "envision switch root",
"pub": "npm run build && envision pack -p -u"
},
"keywords": [],
"author": "abearxiong <xiongxiao@xiongxiao.me>",
"license": "MIT",
"type": "module",
"types": "types/index.d.ts",
"files": [
"types",
"dist",
"src"
],
"dependencies": {
"@kevisual/router": "^0.0.7",
"dayjs": "^1.11.13",
"formidable": "^3.5.2",
"json5": "^2.2.3",
"lodash-es": "^4.17.21",
"nanoid": "^5.1.2"
},
"devDependencies": {
"@kevisual/types": "^0.0.6",
"@kevisual/use-config": "^1.0.8",
"@rollup/plugin-alias": "^5.1.1",
"@rollup/plugin-commonjs": "^28.0.2",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.0",
"@rollup/plugin-replace": "^6.0.2",
"@rollup/plugin-typescript": "^12.1.2",
"@types/crypto-js": "^4.2.2",
"@types/formidable": "^3.4.5",
"@types/lodash-es": "^4.17.12",
"@types/node": "^22.13.5",
"concurrently": "^9.1.2",
"cross-env": "^7.0.3",
"nodemon": "^3.1.9",
"pm2": "^5.4.3",
"rimraf": "^6.0.1",
"rollup": "^4.34.8",
"rollup-plugin-copy": "^3.5.0",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-esbuild": "^6.2.0",
"tape": "^5.9.0",
"tsx": "^4.19.3",
"typescript": "^5.7.3"
},
"pnpm": {}
}

3788
app/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

75
app/rollup.config.mjs Normal file
View File

@ -0,0 +1,75 @@
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import path from 'path';
import esbuild from 'rollup-plugin-esbuild';
import alias from '@rollup/plugin-alias';
import replace from '@rollup/plugin-replace';
import pkgs from './package.json' with {type: 'json'};
const isDev = process.env.NODE_ENV === 'development';
const input = isDev ? './src/dev.ts' : './src/index.ts';
/**
* @type {import('rollup').RollupOptions}
*/
const config = {
input,
output: {
dir: './dist',
entryFileNames: 'app.mjs',
chunkFileNames: '[name]-[hash].mjs',
format: 'esm',
},
plugins: [
replace({
preventAssignment: true, // 防止意外赋值
DEV_SERVER: JSON.stringify(isDev), // 替换 process.env.NODE_ENV
VERSION: JSON.stringify(pkgs.version),
}),
alias({
// only esbuild needs to be configured
entries: [
{ find: '@', replacement: path.resolve('src') }, // 配置 @ 为 src 目录
{ find: 'http', replacement: 'node:http' },
{ find: 'https', replacement: 'node:https' },
{ find: 'fs', replacement: 'node:fs' },
{ find: 'path', replacement: 'node:path' },
{ find: 'crypto', replacement: 'node:crypto' },
{ find: 'zlib', replacement: 'node:zlib' },
{ find: 'stream', replacement: 'node:stream' },
{ find: 'net', replacement: 'node:net' },
{ find: 'tty', replacement: 'node:tty' },
{ find: 'tls', replacement: 'node:tls' },
{ find: 'buffer', replacement: 'node:buffer' },
{ find: 'timers', replacement: 'node:timers' },
// { find: 'string_decoder', replacement: 'node:string_decoder' },
{ find: 'dns', replacement: 'node:dns' },
{ find: 'domain', replacement: 'node:domain' },
{ find: 'os', replacement: 'node:os' },
{ find: 'events', replacement: 'node:events' },
{ find: 'url', replacement: 'node:url' },
{ find: 'assert', replacement: 'node:assert' },
{ find: 'util', replacement: 'node:util' },
],
}),
resolve({
preferBuiltins: true, // 强制优先使用内置模块
}),
commonjs(),
esbuild({
target: 'node22', //
minify: false, // 启用代码压缩
tsconfig: 'tsconfig.json',
}),
json(),
],
external: [
/@kevisual\/router(\/.*)?/, //, // 路由
/@kevisual\/use-config(\/.*)?/, //
// 'sequelize', // 数据库 orm
// 'ioredis', // redis
// 'pg', // pg
],
};
export default config;

8
app/src/app.ts Normal file
View File

@ -0,0 +1,8 @@
import { App } from '@kevisual/router';
import { useContextKey, useContext } from '@kevisual/use-config/context';
const init = () => {
return new App();
};
export const app = useContextKey('app', init);

16
app/src/demo-route.ts Normal file
View File

@ -0,0 +1,16 @@
import { app } from './app.ts';
import { useConfig } from '@kevisual/use-config';
app
.route({
path: 'demo',
key: 'demo',
})
.define(async (ctx) => {
ctx.body = '123';
})
.addTo(app);
const config = useConfig();
console.log('run demo: http://localhost:' + config.port + '/api/router?path=demo&key=demo');

8
app/src/dev.ts Normal file
View File

@ -0,0 +1,8 @@
import { useConfig } from '@kevisual/use-config';
import { app } from './index.ts';
const config = useConfig();
app.listen(config.port, () => {
console.log(`server is running at http://localhost:${config.port}`);
});

4
app/src/index.ts Normal file
View File

@ -0,0 +1,4 @@
import { app } from './app.ts';
import './demo-route.ts';
export { app };

108
app/src/modules/wx.ts Normal file
View File

@ -0,0 +1,108 @@
import { useConfig } from '@kevisual/use-config';
type WxConfig = {
appId: string;
appSecret: string;
};
const config = useConfig<{ wx: WxConfig }>();
export type WxTokenResponse = {
access_token: string;
expires_in: number;
refresh_token: string;
openid: string;
scope: string;
unionid: string;
};
export type WxToken = {
access_token: string;
expires_in: number;
refresh_token: string;
openid: string;
scope: string;
unionid: string;
};
export const fetchToken = async (code: string): Promise<WxToken> => {
const { appId, appSecret } = config.wx;
const wxUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${code}&grant_type=authorization_code`;
const res = await fetch(wxUrl);
const data = await res.json();
// console.log(data)
return data;
};
type UserInfo = {
openid: string;
nickname: string;
sex: number;
language: string;
province: string;
country: string;
headimgurl: string;
privilege: string[];
unionid: string;
};
/**
*
* @param token
* @param openid
* @returns
*/
export const getUserInfo = async (token: string, openid: string): Promise<UserInfo> => {
const phoneUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openid}`;
const res = await fetch(phoneUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const data = await res.json();
console.log(data);
return data;
};
// getUserInfo(token.access_token, token.openid)
type AuthRes = {
errcode: number;
errmsg: string;
};
/**
* errorcode 0: 正常
* @param token
* @param openid
* @returns
*/
export const getAuth = async (token: string, openid: string): Promise<AuthRes> => {
const authUrl = `https://api.weixin.qq.com/sns/auth?access_token=${token}&openid=${openid}`;
const res = await fetch(authUrl);
const data = await res.json();
// console.log(data)
return data;
};
// getAuth(token.access_token, token.openid)
type RefreshToken = {
access_token: string;
expires_in: number;
refresh_token: string;
openid: string;
scope: string;
};
export const refreshToken = async (refreshToken: string): Promise<RefreshToken> => {
const { appId } = config.wx;
const refreshUrl = `https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${appId}&grant_type=refresh_token&refresh_token=${refreshToken}`;
const res = await fetch(refreshUrl);
const data = await res.json();
console.log(data);
return data;
};
// refreshToken(token.refresh_token)

View File

@ -0,0 +1,36 @@
import { SimpleRouter } from '@kevisual/router/simple'
import { IncomingMessage, OutgoingMessage } from 'http'
export const simple = new SimpleRouter()
// gmt_create=2025-02-12+14%3A57%3A18&charset=utf-8&gmt_payment=2025-02-12+14%3A57%3A26&notify_time=2025-02-12+14%3A57%3A27&subject=test&sign=IcqgLJn6HzUpd6so2lPCWm%2FOn%2BEHa8pPLrQVfiOszWB1BjR0MkPommx5esva6nIktJGFU3d2s8%2B1Q%2FfKH8dQcdkjVOI63szQCYnvhFP0AVUKfRTDj8xlRo5rjBg5I3b5aOAOgA4ZgVJanJAIq98qK5CVfKSwdTQTpKHXVpV15%2Fu1EJyE14Ptj3H83J6hpeK9EFWKbZsEkZIb2pR3calk3HIeLkPo4FvWo6q38gUjk3wrLBTh%2B0RhxItCKF3%2B58R9rmzk4WX4S71cBb6w9kBuyA29flawzb6d4qqHzRzqlhid7I0QFgRKRHTnyajlahFCe3kOeWgYfQRpKLabaznQqA%3D%3D&buyer_id=2088722055631717&invoice_amount=1.00&version=1.0&notify_id=2025021201222145726131710505339992&fund_bill_list=%5B%7B%22amount%22%3A%221.00%22%2C%22fundChannel%22%3A%22ALIPAYACCOUNT%22%7D%5D&notify_type=trade_status_sync&out_trade_no=1739343435250&total_amount=1.00&trade_status=TRADE_SUCCESS&trade_no=2025021222001431710505292165&auth_app_id=9021000143661256&receipt_amount=1.00&point_amount=0.00&buyer_pay_amount=1.00&app_id=9021000143661256&sign_type=RSA2&seller_id=2088721055593715
export const getJsonUseFrom = (str: string) => {
const urlParams = new URLSearchParams(str)
const entries = urlParams.entries()
const result = {}
for (const [key, value] of entries) {
result[key] = value
}
return result
}
export const parseBody = async (req: IncomingMessage, res: OutgoingMessage) => {
let body = ''
req.on('data', (chunk: any) => {
body += chunk
})
return new Promise<any>((resolve, reject) => {
req.on('end', () => {
const contentType = req.headers['content-type']
try {
if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
resolve(getJsonUseFrom(body))
} else if (contentType && contentType.includes('application/json')) {
resolve(JSON.parse(body))
} else {
reject(new Error('Unsupported content type'))
}
} catch (error) {
reject(error)
}
})
})
}

View File

@ -0,0 +1,74 @@
import { WxServices } from '@/routes/wx/services.ts'
import { simple } from './simple.ts'
export const createLoginHtml = (wxService: WxServices) => {
const redirectUrl = wxService.isNew ? '/user/info' : '/'
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wx Login</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#loading {
font-size: 1.2rem;
color: #555;
}
</style>
</head>
<body>
<div>Login Success</div>
<div id="loading">Redirecting, please wait...</div>
<script>
(function() {
// Save the token to localStorage
localStorage.setItem('token', '${wxService.webToken}');
// Redirect after 2 seconds
setTimeout(() => {
window.location.href = '${redirectUrl}';
}, 2000);
})();
</script>
</body>
</html>
`
}
simple.get('/api/wx/login', async (req, res) => {
try {
const url = req.url
const query = new URLSearchParams(url.split('?')[1])
const code = query.get('code')
const state = query.get('state')
if (!code) {
res.end('code is required')
return
}
const wxService = new WxServices()
await wxService.login(code)
if (wxService.isNew) {
await wxService.getUserInfo()
}
res.setHeader('Content-Type', 'text/html')
res.end(createLoginHtml(wxService))
} catch (e) {
console.error(e)
res.end('error')
}
})
simple.get('/api/wx/on-ai/login', async (req, res) => {
const url = req.url
const query = new URLSearchParams(url.split('?')[1])
const code = query.get('code')
const state = query.get('state')
const onAIBaseUrl = 'https://note.on-ai.ai'
const newUrl = `${onAIBaseUrl}/api/wx/login?code=${code}&state=${state}`
res.setHeader('Content-Type', 'text/html')
res.end(`<script>window.location.href='${newUrl}'</script>`)
})

View File

@ -0,0 +1,81 @@
import { WxTokenResponse, fetchToken, getUserInfo } from '@/modules/wx.ts';
import { useContextKey } from '@kevisual/use-config/context';
import { Buffer } from 'buffer';
const User = useContextKey<typeof User>('user');
export class WxServices {
token: WxTokenResponse;
// 创建一个webToken用户登录
webToken: string;
isNew: boolean;
user: User;
constructor() {
//
}
async login(code: string) {
const token = await fetchToken(code);
this.token = token;
if (!token.unionid) {
throw new Error('unionid is required');
}
const unionid = token.unionid;
let user = await User.findOne({ where: { username: unionid } });
if (!user) {
user = await User.createUser(unionid, unionid.slice(0, 8));
this.isNew = true;
}
const tokenInfo = await user.createToken();
this.webToken = tokenInfo.token;
this.user = user;
}
async checkHasUser() {}
async getUserInfo() {
const userInfo = await getUserInfo(this.token.access_token, this.token.openid);
const { nickname, headimgurl } = userInfo;
this.user.nickname = nickname;
try {
const downloadImgUrl = await this.downloadImg(headimgurl);
this.user.avatar = downloadImgUrl;
} catch (error) {
console.error('Error downloading or converting image:', error);
}
await this.user.save();
}
/**
* base64
* @param url
*/
async downloadImg(url: string): Promise<string> {
try {
return await downloadImag(url);
} catch (error) {
console.error('Error downloading or converting image:', error);
throw error;
}
}
}
// https://thirdwx.qlogo.cn/mmopen/vi_32/WvOPpbDwUKEVJvSst8Z91Y68m7CsBeecMqRGlqey5HejByePD89boYGaVCM8vESsYmokk1jABUDsK08IrfI6JEkibZkDIC2zsb96DGBTEF7E/132
export const downloadImag = async (url: string) => {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
const arrayBufferToBase64 = (buffer: ArrayBuffer): string => {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return Buffer.from(binary, 'binary').toString('base64');
};
const buffer = await res.arrayBuffer();
return `data:image/jpeg;base64,${arrayBufferToBase64(buffer)}`;
} catch (error) {
console.error('Error downloading or converting image:', error);
throw error;
}
};

View File

@ -0,0 +1,15 @@
const testLink = 'http://note.silkyai.cn/user/login?code=011YxX000j1OhT1J1B100Ko9W82YxX0h&state=162';
const link = new URL(testLink);
const code = link.searchParams.get('code');
const state = link.searchParams.get('state');
const token = {
access_token: '87_QgDzd_v3uB0a-DWsZ3Ns_yN6AEpW3A5yIoXYuukJJwFEWnPtqHASUPFRvr5yqZlY9qzIM8YuXzeOamtOxmHAyptaZAYvsqLvzOxEitLx9GM',
expires_in: 7200, // 2 hours
refresh_token: '87_nXrgfcZwiOJRC_u27O00qJDBdGWrTgalpLqG0t8ccSuuaFyDmN1j2maSwk3bB4SgNN8QCPoH55JGcG5f9a1daTIV3ulvqLKnNiBTg-aB4fo',
openid: 'oKiTl6uB0UWw85NPj6rqc-m8cUEo',
scope: 'snsapi_login',
unionid: 'oMFgb6ZoIr7psVy39pYOOybDcyoM',
};
// fetchToken(code)

33
app/tsconfig.json Normal file
View File

@ -0,0 +1,33 @@
{
"compilerOptions": {
"module": "nodenext",
"target": "esnext",
"noImplicitAny": false,
"outDir": "./dist",
"sourceMap": false,
"allowJs": true,
"newLine": "LF",
"baseUrl": "./",
"typeRoots": [
"node_modules/@types",
"node_modules/@kevisual/types"
],
"declaration": true,
"noEmit": false,
"allowImportingTsExtensions": true,
"emitDeclarationOnly": true,
"moduleResolution": "NodeNext",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"paths": {
"@/*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts",
],
"exclude": [],
}

23
init.md Normal file
View File

@ -0,0 +1,23 @@
## 初始化项目
```bash
# 获取router-template的项目作为app模版
git clone git@git.xiongxiao.me:tailored/router-template.git app
# 获取vite-react-template的项目作为web模版
git clone git@git.xiongxiao.me:template/vite-react-template.git web
# 获取app-template的项目作为router-web模版
git clone git@git.xiongxiao.me:tailored/app-template.git router-web
# 删除模版中的git目录
rm -rf app/.git
rm -rf web/.git
rm -rf router-web/.git
```
## router-template
1. 修改package.json中的name

13
package.json Normal file
View File

@ -0,0 +1,13 @@
{
"name": "wx-login",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "abearxiong <xiongxiao@xiongxiao.me>",
"license": "MIT",
"type": "module"
}

View File

@ -0,0 +1,21 @@
{
"name": "Node.js 22 Development Environment",
"image": "mcr.microsoft.com/devcontainers/javascript-node:22",
"runArgs": [
"--env",
"TZ=Asia/Shanghai"
],
"settings": {
"terminal.integrated.defaultProfile.linux": "/bin/bash"
"terminal.integrated.env.linux": {
"TZ": "Asia/Shanghai"
}
},
"remoteEnv": {
"TZ": "Asia/Shanghai"
},
"extensions": [
"dbaeumer.vscode-eslint"
],
"postCreateCommand": "sudo ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo Asia/Shanghai | sudo tee /etc/timezone && pnpm install -g @kevisual/envision-cli@latest && npm install"
}

28
web/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# Logs
logs
*.log
.env
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
tsconfig.app.tsbuildinfo
tsconfig.node.tsbuildinfo

3
web/.npmrc Normal file
View File

@ -0,0 +1,3 @@
//npm.xiongxiao.me/:_authToken=${ME_NPM_TOKEN}
@abearxiong:registry=https://npm.pkg.github.com
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

1
web/README.md Normal file
View File

@ -0,0 +1 @@
# vite-react-template

31
web/eslint.config.js Normal file
View File

@ -0,0 +1,31 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
import react from 'eslint-plugin-react';
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
'@typescript-eslint/no-explicit-any': 'off',
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
'@typescript-eslint/no-unused-vars': 'off',
'no-debugger': 'off',
},
},
);

13
web/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

60
web/package.json Normal file
View File

@ -0,0 +1,60 @@
{
"name": "vite-react",
"private": true,
"version": "0.0.1",
"type": "module",
"basename": "/",
"scripts": {
"dev": "vite",
"dev:web": "cross-env WEB_DEV=true vite --mode web",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview",
"pub": "envision deploy ./dist -k vite-react -v 0.0.1",
"ev": "npm run build && npm run deploy"
},
"stackblitz": {
"startCommand": "npm dev:web"
},
"author": "abearxiong <xiongxiao@xiongxiao.me>",
"license": "MIT",
"dependencies": {
"@ant-design/icons": "^5.6.1",
"@kevisual/query": "0.0.7-alpha.3",
"@kevisual/router": "0.0.7",
"@kevisual/system-ui": "^0.0.3",
"@kevisual/ui": "^0.0.4-alpha-1",
"antd": "^5.24.2",
"clsx": "^2.1.1",
"dayjs": "^1.11.13",
"immer": "^10.1.1",
"lodash-es": "^4.17.21",
"nanoid": "^5.1.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router": "^7.2.0",
"react-router-dom": "^7.2.0",
"react-toastify": "^11.0.5",
"zustand": "^5.0.3"
},
"devDependencies": {
"@eslint/js": "^9.21.0",
"@kevisual/types": "^0.0.6",
"@tailwindcss/vite": "^4.0.9",
"@types/node": "^22.13.5",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
"@vitejs/plugin-basic-ssl": "^1.2.0",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.21.0",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^16.0.0",
"tailwind-merge": "^3.0.2",
"tailwindcss": "^4.0.9",
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.7.3",
"typescript-eslint": "^8.25.0",
"vite": "^6.2.0"
}
}

3586
web/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

9
web/src/App.tsx Normal file
View File

@ -0,0 +1,9 @@
import { WeChatLoginForm } from './pages/Login';
export const App = () => {
return (
<div className='bg-slate-200 w-full h-screen flex justify-center items-center'>
<WeChatLoginForm />
</div>
);
};

7
web/src/index.css Normal file
View File

@ -0,0 +1,7 @@
@import "tailwindcss";
@layer components {
.test-loading {
@apply w-20 h-20 bg-gray-300 rounded-full animate-spin;
}
}

6
web/src/main.tsx Normal file
View File

@ -0,0 +1,6 @@
import { createRoot } from 'react-dom/client';
import { App } from './App.tsx';
import './index.css';
createRoot(document.getElementById('root')!).render(<App />);

View File

@ -0,0 +1 @@
export const basename = DEV_SERVER ? '/' : BASE_NAME;

5
web/src/modules/query.ts Normal file
View File

@ -0,0 +1,5 @@
import { QueryClient } from '@kevisual/query';
export const query = new QueryClient({
io: true,
url: '/api/router',
});

View File

@ -0,0 +1,71 @@
// 定义回调函数
export function callback(res) {
// 第一个参数传入回调结果,结果如下:
// ret Int 验证结果0验证成功。2用户主动关闭验证码。
// ticket String 验证成功的票据,当且仅当 ret = 0 时 ticket 有值。
// CaptchaAppId String 验证码应用ID。
// bizState Any 自定义透传参数。
// randstr String 本次验证的随机串,后续票据校验时需传递该参数。
console.log('callback:', res)
// res用户主动关闭验证码= {ret: 2, ticket: null}
// res验证成功 = {ret: 0, ticket: "String", randstr: "String"}
// res请求验证码发生错误验证码自动返回terror_前缀的容灾票据 = {ret: 0, ticket: "String", randstr: "String", errorCode: Number, errorMessage: "String"}
// 此处代码仅为验证结果的展示示例真实业务接入建议基于ticket和errorCode情况做不同的业务处理
if (res.ret === 0) {
// 复制结果至剪切板
var str = '【randstr】->【' + res.randstr + '】 【ticket】->【' + res.ticket + '】'
var ipt = document.createElement('input')
ipt.value = str
document.body.appendChild(ipt)
ipt.select()
document.body.removeChild(ipt)
alert('1. 返回结果randstr、ticket已复制到剪切板ctrl+v 查看。 2. 打开浏览器控制台,查看完整返回结果。')
}
}
export type TencentCaptcha = {
actionDuration?: number
appid?: string
bizState?: any
randstr?: string
ret: number
sid?: string
ticket?: string
errorCode?: number
errorMessage?: string
verifyDuration?: number
}
// 定义验证码触发事件
export const checkCaptcha = (): Promise<TencentCaptcha> => {
return new Promise((resolve, reject) => {
const callback = (res: TencentCaptcha) => {
console.log('callback:', res)
if (res.ret === 0) {
resolve(res)
} else {
reject(res)
}
}
// @ts-ignore
const appid = CAPTCHA_APPID
try {
// 生成一个验证码对象
// CaptchaAppId登录验证码控制台从【验证管理】页面进行查看。如果未创建过验证请先新建验证。注意不可使用客户端类型为小程序的CaptchaAppId会导致数据统计错误。
//callback定义的回调函数
// @ts-ignore
var captcha = new TencentCaptcha(appid, callback, {})
// 调用方法,显示验证码
captcha.show()
} catch (error) {
// 加载异常调用验证码js加载错误处理函数
var ticket = 'terror_1001_' + appid + '_' + Math.floor(new Date().getTime() / 1000)
// 生成容灾票据或自行做其它处理
callback({
ret: 0,
randstr: '@' + Math.random().toString(36).substring(2),
ticket: ticket,
errorCode: 1001,
errorMessage: 'jsload_error'
})
}
})
}

View File

@ -0,0 +1,36 @@
export const createLogin = async () => {
// const redirect_uri = 'http://localhost:6024/user/login'
const url = new URL('/api/wx/login', window.location.origin);
let redirect_uri = url.toString();
if (DEV_SERVER) {
redirect_uri = 'https://note.silkyai.cn/user/login';
}
console.log('redirect_uri', redirect_uri);
// @ts-ignore
const obj = new WxLogin({
self_redirect: false,
id: 'weixinLogin', // 需要显示的容器id
appid: 'wxea912643e8747b44', // 微信开放平台appid wx*******
scope: 'snsapi_login', // 网页默认即可 snsapi_userinfo
redirect_uri: encodeURIComponent(redirect_uri), // 授权成功后回调的url
state: Math.ceil(Math.random() * 1000), // 可设置为简单的随机数加session用来校验
style: '', // 提供"black"、"white"可选。二维码的样式
href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7bWFyZ2luLXRvcDowO30KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30=', // 外部css文件url需要https
});
return obj;
};
export const wxId = 'weixinLogin';
export function setWxerwma() {
const s = document.createElement('script');
s.type = 'text/javascript';
s.src = '//res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
s.id = 'weixinLogin-js';
if (document.getElementById('weixinLogin-js')) {
createLogin();
return;
}
const wxElement = document.body.appendChild(s);
wxElement.onload = function () {
createLogin();
};
}

26
web/src/pages/Login.tsx Normal file
View File

@ -0,0 +1,26 @@
import React, { useEffect } from 'react';
import { setWxerwma, wxId } from '@/modules/wx-login';
const WeChatLogin: React.FC = () => {
useEffect(() => {
setWxerwma();
}, []);
return <div id={wxId} className='max-w-sm mx-auto bg-white rounded-lg text-center -mb-16'></div>;
};
export const WeChatLoginForm: React.FC = () => {
const serverCom = (
<p className='mt-6 text-xs text-center text-[#e69c36]'>
<span className='font-medium text-[#e69c36]'></span> <span className='font-medium text-[#e69c36]'></span>
</p>
);
return (
<div className='max-w-sm mx-auto p-6 bg-white rounded-lg'>
<div className='mt-6 w-[310px] flex flex-col justify-center text-center text-gray-500'>
<WeChatLogin />
{serverCom}
</div>
</div>
);
};

View File

@ -0,0 +1,101 @@
import { query } from '../../modules/query'
import { message } from 'antd'
import { create } from 'zustand'
import { TencentCaptcha } from '@/modules/tencent-captcha'
type UserStore = {
isAuthenticated: boolean
qrCodeUrl: string
checkAuthStatus: () => void
getCode: (phone: string, captcha: TencentCaptcha) => void
login: (phone: string, code: string) => void
updateUser: (data: any) => void
getUpdateUser: () => void
data: any
setData: (data: any) => void
}
export const useUserStore = create<UserStore>((set) => ({
isAuthenticated: false,
qrCodeUrl: '',
checkAuthStatus: () => {
//
},
getCode: async (phone, captcha) => {
const res = await query.post({
path: 'sms',
key: 'send',
data: {
phone,
captcha
}
})
if (res.code === 200) {
// do something
message.success('验证码发送成功')
} else {
message.error(res.message || '验证码发送失败')
}
},
login: async (phone, code) => {
const res = await query.post({
path: 'sms',
key: 'login',
data: {
phone,
code
}
})
console.log(res)
if (res.code === 200) {
message.success('登录成功')
const data = res.data
localStorage.setItem('token', data.token)
localStorage.setItem('expireTime', data.expireTime)
set({ isAuthenticated: true })
const href = location.href
const url = new URL(href)
const redirect = url.searchParams.get('redirect')
if (redirect) {
const href = decodeURIComponent(redirect)
window.open(href, '_self')
return
}
if (data.isNew) {
location.href = '/user/info'
} else {
location.href = '/workspace'
}
} else {
message.error(res.message || '登录失败')
}
},
updateUser: async (data) => {
const res = await query.post({
path: 'user',
key: 'updateInfo',
data
})
if (res.code === 200) {
message.success('更新成功')
setTimeout(() => {
location.href = '/workspace'
}, 1000)
} else {
message.error(res.message || '更新失败')
}
},
getUpdateUser: async () => {
const res = await query.post({
path: 'user',
key: 'getUpdateInfo'
})
if (res.code === 200) {
set({ data: res.data })
} else {
message.error(res.message || '获取用户信息失败')
}
},
data: {},
setData: (data) => set({ data })
}))

6
web/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
/// <reference types="vite/client" />
type SimpleObject = {
[key: string | number]: any;
};
declare let BASE_NAME: string;

43
web/tsconfig.app.json Normal file
View File

@ -0,0 +1,43 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
// "jsx": "react",
// "jsxFragmentFactory": "Fragment",
// "jsxFactory": "h",
"jsx": "react-jsx",
"baseUrl": "./",
"typeRoots": [
"node_modules/@types",
"node_modules/@kevisual/types",
],
"paths": {
"@/*": [
"src/*"
]
},
/* Linting */
"strict": true,
"noImplicitAny": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": [
"src",
"typings.d.ts"
]
}

7
web/tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

22
web/tsconfig.node.json Normal file
View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

54
web/vite.config.ts Normal file
View File

@ -0,0 +1,54 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import tailwindcss from '@tailwindcss/vite';
import pkgs from './package.json' with { type: 'json' };
import basicSsl from '@vitejs/plugin-basic-ssl';
const version = pkgs.version || '0.0.1';
const isDev = process.env.NODE_ENV === 'development';
const basename = isDev ? '/' : pkgs?.basename || '/';
const plugins = []
const isWeb = false;
if(isWeb) {
// 在bolt.new的页面没有ssl
plugins.push(basicSsl())
}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss(), ...plugins],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
base: basename,
define: {
DEV_SERVER: JSON.stringify(process.env.NODE_ENV === 'development'),
VERSION: JSON.stringify(version),
BASE_NAME: JSON.stringify(basename),
},
build: {
target: 'esnext',
},
server: {
port: 6004,
host: '0.0.0.0',
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '/api'),
},
'/api/router': {
target: 'ws://localhost:3000',
changeOrigin: true,
ws: true,
rewriteWsOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '/api'),
},
},
},
});