Commit 0346e090 by liimin

feat(request): 统一 api-core 请求门面并收敛各端装配点

- api-core 抽出 RequestStrategy / SignatureStrategy 双注册表,新增客户端工厂
  (createRopClient / createWebHostClient / createRpcGatewayClient / createRestClient),
  消费层只传环境参数,装配点不再出现 new Request / strategies.* / register
- 四个小程序 ROP 壳、web 主壳 (platform-core/http.ts)、points 适配层统一走工厂装配;
  老系统 RPC 网关收进 rpcGateway 策略,rpcCall 收敛为一行 request.post(method, params, { gateway })
- usedcar 配套修复会话闸门 (openSessionGate / waitSessionId) 与登录态 / 请求失败兜底,
  消除启动瞬间 sessionId 未落地导致的「缺少 sessionId 参数」红字
- 新增 mp 小程序「构建 npm」一键链路:根 pnpm build:npm (= pnpm mp),
  单 lane 用 pnpm build:npm --lane <name> 或进目录 pnpm build:npm;
  .gitignore 忽略 api-core 的 miniprogram_dist
- 附带:.env.example 内网调试 IP 更新、usedcar libVersion 3.13.1→3.14.3
1 parent cc10242c
Pipeline #382 for 0346e090 failed in 0 seconds
Showing 61 changed files with 1350 additions and 605 deletions
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
# 内网调试:固定后端地址(浏览器直连,需后端对当前来源开放 CORS)。 # 内网调试:固定后端地址(浏览器直连,需后端对当前来源开放 CORS)。
# 留空 → 同源:生产访问什么域名就打什么域名(如 http://ujia.glsx.com.cn/youjia/...),无需改配置。 # 留空 → 同源:生产访问什么域名就打什么域名(如 http://ujia.glsx.com.cn/youjia/...),无需改配置。
VITE_API_TARGET=http://192.168.3.197:8788 VITE_API_TARGET=http://192.168.21.54:8788
# 后端 context-path,会同时出现在实际请求路径与签名 canonical 第 2 行,必须与后端严格一致 # 后端 context-path,会同时出现在实际请求路径与签名 canonical 第 2 行,必须与后端严格一致
VITE_API_CONTEXT_PATH=/youjia VITE_API_CONTEXT_PATH=/youjia
......
node_modules/ node_modules/
dist/ dist/
# api-core 的小程序产物目录(微信「构建 npm」的输入,由 tsup 二次构建生成)
miniprogram_dist/
.turbo/ .turbo/
.tmp/ .tmp/
coverage/ coverage/
......
...@@ -88,6 +88,65 @@ scripts/ ...@@ -88,6 +88,65 @@ scripts/
dev.mjs 一条命令起全站 dev.mjs 一条命令起全站
``` ```
## 小程序(apps/mp)
`apps/mp` 下四个原生小程序(points / sales / store / usedcar)同仓,但它们**不进 pnpm 的构建链**(没有 build 任务),在微信开发者工具里编译,第三方依赖靠「构建 npm」落到 `miniprogram_npm/`。
先跑一次工作区安装(只认 pnpm,不要用 npm install):
```bash
pnpm install
```
### 只做你改的那个小程序
每个小程序根目录都有自己的入口 `mp-npm.mjs`,**只管自己**,不会碰其他三个:
```bash
pnpm --filter @uj/mp-store run build:npm # 准备 + 构建(端口开着时全自动)+ 体检
pnpm --filter @uj/mp-store run check:npm # 只体检,不改任何文件
cd apps/mp/store && node mp-npm.mjs --check # 同样效果
```
(`mp-npm.mjs` 已写进各 lane 的 `packOptions.ignore`,不会被打进小程序包体。)
它做三步,用不上的步骤不会出现(非 usedcar 不会打印子包依赖那一段):
1. `pnpm --filter @uj/api-core build` → `miniprogram_dist/`——「构建 npm」的唯一输入,gitignore 的产物,漏了就是白屏;
2. 本 lane 有内嵌子包时(目前只有 usedcar 的 `packageUsedCar`)缺依赖就跑 `setup:deps`(内部 `npm install`);
3. 服务端口 9420 可达时调 `cli.bat build-npm` 自动构建;然后按工具自己的判定规则校验 `miniprogram_npm/`,缺哪个包点哪个名。
### 一次准备全仓(新环境 / CI)
```bash
pnpm mp # 遍历 apps/mp/manifest.json 里所有 lane
pnpm mp:check # 只体检
pnpm mp --lane usedcar,store # 指定几个(等价于分别进目录跑)
```
退出码:全绿 0,有缺口 1,可直接挂钩子。
想让第 3 步免人工:开发者工具 → **设置 → 安全设置 → 打开「服务端口」**,之后脚本会自己调 cli 构建;没开会打印精确到项目目录的人工清单。
脚本坏了才需要的手工等价步骤:
```bash
pnpm --filter @uj/api-core build # api-core 产物
pnpm --filter @uj/mp-usedcar run setup:deps # 仅 usedcar
# 然后在开发者工具里打开 apps/mp/<lane> → 工具 → 构建 npm
```
自检一条命令,`miniprogram_npm/@uj/api-core/index.js` 必须存在:
```bash
ls apps/mp/<lane>/miniprogram_npm/@uj/api-core/index.js
```
**包管理器边界:除了 `apps/mp/usedcar/packageUsedCar` 用 npm,其余一律 pnpm。** 那个目录是微信「构建 npm」的输入、依赖来自 glsx 私有源,一旦成为 workspace 成员会让整仓 `pnpm install` 解析失败(原因写在 `pnpm-workspace.yaml` 的注释里),所以 `setup:deps` 只是把 `npm install` 封装了一层。
`packages/api-core` 有两套产物,别混:`dist/`(cjs+esm+dts,给 node / web)和 `miniprogram_dist/`(单文件 cjs,给「构建 npm」)。`package.json` 的 `miniprogram` 字段必须指向**目录**,指到文件会被开发者工具静默跳过——细节见 `packages/api-core/tsup.config.ts` 注释。
## 常用命令 ## 常用命令
| 命令 | 说明 | | 命令 | 说明 |
......
import { createSha1Signer } from '@uj/api-core' /**
* points 请求层:@uj/api-core 的客户端工厂。
*
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL 拼装 / 签名 /
* 拦截器(业务码归一 / 登录跳转 / loading / toast)由 api-core 负责。
*
* public API 与旧壳一致:get/post/request(RequestMethods, params, returnAll)、
* fetch(method, data, returnAll=true)、reportTrack(params)、wx_request({...})。
* 另外补上 common.js 调用了但旧壳从未定义的 getMock()(配置中心拉取)。
*
* 与另外三个 app 的差异用「语义化参数」表达:
* · SHA1 不摊平 params → 内置签名策略 'rop-sha1'(与旧 getData 逐字节一致)
* · 单一域名 / merchantId 头三级回退 → hosts、getMerchantId
* · 业务失败 / 登录失效后 Promise 挂起 → loginReplay
* · sentry 上报 → events.error + onTransportError
*/
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core'
import { import {
defaultMerchantId, defaultMerchantId,
secretKey, secretKey,
pathEnum, pathEnum,
domain, domain,
env,
} from '../env/index' } from '../env/index'
// 签名统一收口到 @uj/api-core 的 SHA1 预设(与老 sign.js 字节级一致,迁移时脚本验证过)。 const DEFAULT_CRED = {
// 业务编排(登录态跳转 / toast / sentry)仍保留在下方 Request 类,不动。 appKey: '48e5e13229b82c1b4e6e8c96151f0637',
const pointsSigner = createSha1Signer({ id: 'points-sha1' }) secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
}
/**接口 */ const client = createRopClient({
class Request { hosts: { scrm: domain },
get(params, returnAll = false) { pathEnum,
return this.request('GET', params, returnAll) secretKey,
} defaultCredential: DEFAULT_CRED,
post(params, returnAll = false) { signature: 'rop-sha1',
return this.request('POST', params, returnAll) session: {
} sessionId: () => (wx.p.storage.get() || {}).sessionId || '',
fetch(method, data, returnAll = true) { },
return this.post({ getMerchantId: () => {
method, const info = wx.p.storage.get('merchant_info') || {}
...data, return wx.$merchant_id || info.merchantId || defaultMerchantId
},
loginReplay: true,
onLoginRequired: () => {
// 旧壳:hideLoading → 清会话 → redirectTo 登录页。
wx.hideLoading?.()
wx.p.storage.rm('sessionId')
wx.p.isLogin = false
wx.p.storage.rm('userInfo')
wx.p.router.redirectTo('/pages/Login/Login')
}, },
returnAll // 业务异常:toast 由门面负责,这里只补旧壳的 sentry 上报。
); events: {
} error: (err) => {
const params = err?.config?.data
wx.p?.sentry?.reportError?.(`接口异常:${err?.message}`, {
code: err?.code, message: err?.message, params,
})
},
},
// 传输失败:改写提示文案 + sentry 上报(旧壳 fail 分支)。
onTransportError: (error) => {
// 旧壳 fail 分支会先关掉 loading。
wx.hideLoading?.()
const message = typeof error === 'string'
? error
: (error && (error.errMsg || error.message)) || JSON.stringify(error) || '系统异常'
console.error('[request fail]', error)
wx.p?.sentry?.reportError?.(`接口异常:${message}`, { error })
return { message }
},
})
const call = (params, returnAll = false, httpMethod = 'POST') =>
client.request({
url: params.method,
method: httpMethod,
data: params,
returnAll,
// projectName 覆盖项目名、noSignAttr 从签名原文排除,旧壳都是从 params 里摘出来用的。
projectName: params.projectName,
noSignAttr: params.noSignAttr,
headers: httpMethod === 'GET' ? { 'Cache-Control': 'no-cache' } : undefined,
})
const api = {
get: (params, returnAll = false) => call(params, returnAll, 'GET'),
post: (params, returnAll = false) => call(params, returnAll, 'POST'),
request: (httpMethod, params, returnAll = false) => call(params, returnAll, httpMethod),
// 注意:旧壳 fetch 的 returnAll 默认 true,返回完整信封 { code, data, message }。
fetch: (method, data = {}, returnAll = true) => call({ method, ...data }, returnAll, 'POST'),
reportTrack: (params) => call(params, true, 'POST'),
// 裸 wx.request:配置中心 / 非 ROP 接口,原样保留(不进签名、不进业务码归一)。
wx_request({ wx_request({
url, url,
method = 'GET', method = 'GET',
data = {}, data = {},
header = {}, header = {},
dataType = 'json', dataType = 'json',
responseType = "text" responseType = 'text',
}) { }) {
return new Promise((resolve) => { return new Promise((resolve) => {
wx.request({ wx.request({
url, url, data, method, header, dataType, responseType,
data, success(response) { resolve(response.data) },
method,
header,
dataType,
responseType,
success(response) {
resolve(response.data)
}
}) })
}) })
}
reportTrack(params) {
return this.request('POST', params, true)
}
async request(RequestMethods, params, returnAll) {
wx.showNavigationBarLoading()
let header = RequestMethods === 'POST' ? {
'content-type': 'application/x-www-form-urlencoded'
} : {
'Cache-Control': 'no-cache'
}
let {
merchantId
} = wx.p.storage.get('merchant_info')
header.merchantId = wx.$merchant_id || merchantId || defaultMerchantId
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
const path = pathEnum[projectName]
params = await this.getData(params)
return new Promise((resolve, reject) => {
wx.request({
url: `${domain}${path}router?method=${params.method}`,
data: params,
method: RequestMethods,
header,
dataType: 'json',
responseType: 'text',
success(response) {
/**业务代码 */
let {
data: {
code,
message
}, },
data // 兼容 common.js 的 http.getMock():旧壳缺此方法(调用会 TypeError),
} = response // 这里与 system.js 的 getConfigData 同源,走同一份配置中心数据。
if (returnAll) { getMock() {
resolve(data) const configModule = 'mini-points-mall'
return const configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`
} return api.wx_request({ url: configUrl })
if (code == 20 || code == 21) {
wx.hideLoading()
const thisPage = wx.p.router.getPageInstance(),
options = Object.keys(thisPage.options)
let currentRoute = thisPage.route,
query = []
if (options.length) {
options.map(key => {
query.push(`${key}=${thisPage.options[key]}`)
})
}
if (query.length) currentRoute += `?${query.join('&')}`
wx.p.storage.rm('sessionId')
wx.p.isLogin = false
wx.p.storage.rm('userInfo')
return wx.p.router.redirectTo('/pages/Login/Login')
} else {
if (code == '0') {
resolve(data.data)
} else {
wx.showToast({
title: message || '系统异常',
icon: 'none'
})
wx.p.sentry.reportError(`接口异常:${message}`, {code,message,params})
}
}
},
fail(error) {
wx.hideLoading()
wx.showToast({
title: typeof error == 'string' ? error : JSON.stringify(error) || '系统异常',
icon: 'error'
})
console.error(`接口异常:`, error)
wx.p.sentry.reportError(`接口异常:${error.message}`, {error,params})
reject(error)
}, },
complete() {
wx.stopPullDownRefresh()
wx.hideNavigationBarLoading()
}
})
})
}
async getData(params) {
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
else delete params.projectName
let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
if (secretKey[projectName]) {
appKey = secretKey[projectName].appKey
secret = secretKey[projectName].secret
}
let {
sessionId
} = wx.p.storage.get()
let noSignAttr = []
if (!params.sessionId && sessionId) params.sessionId = sessionId
if (params.delSessionId) {
delete params.sessionId
delete params.delSessionId
}
if (params.noSignAttr) {
noSignAttr = params.noSignAttr
delete params.noSignAttr
}
params.v = '1.0.0'
params.format = 'json'
params.locale = 'zh_CN'
params.source = 'dj-wechat'
params.appKey = appKey
// 签名统一收口到 @uj/api-core(与老 sign.js 逐字节一致,迁移时脚本验证过)。
// params 此时尚不含 sign;signer 仅取其 .sign 并入,不动业务参数。
const signed = await pointsSigner.fields({
method: params.method,
appKey,
secret,
version: params.v,
format: params.format,
params,
exclude: noSignAttr,
})
params.sign = signed.sign
return params
}
getRopProject(method) {
const projectName = method.split('.')[2]
return projectName
}
} }
export default new Request()
\ No newline at end of file \ No newline at end of file
export default api
#!/usr/bin/env node
/**
* points 的「构建 npm」入口:只管本小程序。
*
* 做的事:api-core 小程序产物 → 调开发者工具构建 npm(服务端口开着才自动)
* → 体检 miniprogram_npm。
*
* 用法:
* pnpm --filter @uj/mp-points run build:npm
* node mp-npm.mjs # 在 apps/mp/points 下直接跑
* node mp-npm.mjs --check # 只体检,不改任何文件
*
* 全量(四个小程序一起)请用仓库根的 `pnpm mp`。
*/
import { runLaneCli } from '../../../scripts/mp-npm-core.mjs';
runLaneCli('points');
...@@ -4,7 +4,9 @@ ...@@ -4,7 +4,9 @@
"private": true, "private": true,
"scripts": { "scripts": {
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"lint": "eslint src" "lint": "eslint src",
"build:npm": "node mp-npm.mjs",
"check:npm": "node mp-npm.mjs --check"
}, },
"dependencies": { "dependencies": {
"@uj/api-core": "workspace:*", "@uj/api-core": "workspace:*",
......
...@@ -52,6 +52,10 @@ ...@@ -52,6 +52,10 @@
"packOptions": { "packOptions": {
"ignore": [ "ignore": [
{ {
"value": "mp-npm.mjs",
"type": "file"
},
{
"value": ".md", "value": ".md",
"type": "file" "type": "file"
} }
......
#!/usr/bin/env node
/**
* sales 的「构建 npm」入口:只管本小程序。
*
* 做的事:api-core 小程序产物 → 调开发者工具构建 npm(服务端口开着才自动)
* → 体检 miniprogram_npm。
*
* 用法:
* pnpm --filter @uj/mp-sales run build:npm
* node mp-npm.mjs # 在 apps/mp/sales 下直接跑
* node mp-npm.mjs --check # 只体检,不改任何文件
*
* 全量(四个小程序一起)请用仓库根的 `pnpm mp`。
*/
import { runLaneCli } from '../../../scripts/mp-npm-core.mjs';
runLaneCli('sales');
...@@ -4,7 +4,9 @@ ...@@ -4,7 +4,9 @@
"private": true, "private": true,
"scripts": { "scripts": {
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"lint": "eslint src" "lint": "eslint src",
"build:npm": "node mp-npm.mjs",
"check:npm": "node mp-npm.mjs --check"
}, },
"dependencies": { "dependencies": {
"@uj/api-core": "workspace:*", "@uj/api-core": "workspace:*",
......
...@@ -90,7 +90,12 @@ ...@@ -90,7 +90,12 @@
} }
}, },
"packOptions": { "packOptions": {
"ignore": [], "ignore": [
{
"value": "mp-npm.mjs",
"type": "file"
}
],
"include": [] "include": []
}, },
"appid": "wxe10067a63c1856ac", "appid": "wxe10067a63c1856ac",
......
import { /**
* sales 请求层:@uj/api-core 的客户端工厂。
*
* 一个 createRopClient({配置}) 直接拿到 client;平台(wx)、URL 拼装、签名、
* 拦截器(业务码归一 / 登录重放 / loading / toast)全在 api-core 里,本文件只传环境参数。
* public API 与旧壳逐签名一致:get/post/request(params, returnAll, isShowLoading, hostType)、
* reportTrack(params)、getMock(),453 处调用点零改动。
*/
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core'
import { sign, domain, djDomain, merchantDomain, pathEnum, secretKey, djSecretKey, index } from './http.js'
import { login } from '~/utils/appFn/index'
const client = createRopClient({
hosts: { scrm: domain, dj: djDomain, merchant: merchantDomain },
pathEnum,
secretKey, secretKey,
djSecretKey, djSecretKey,
pathEnum, // 本 app 的 qs 摊平版 SHA1(字节级对齐旧壳):直接传函数,工厂内部包成签名策略。
domain, signature: sign,
djDomain, defaultCredential: {
merchantDomain, appKey: '48e5e13229b82c1b4e6e8c96151f0637',
index, secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
sign
} from './http.js'
import util from '~/utils/util.js'
import {
login
} from '~/utils/appFn/index'
const HOST = {
scrm: domain,
dj: djDomain,
merchant:merchantDomain
}
let requestTimes = 0
/**接口 */
class Request {
get(params, returnAll = false, isShowLoading = false, hostType = 'scrm') {
return this.request('GET', params, returnAll, isShowLoading, hostType)
}
post(params, returnAll = false, isShowLoading = false, hostType = 'scrm') {
return this.request('POST', params, returnAll, isShowLoading, hostType)
}
async request(RequestMethods, params, returnAll, isShowLoading, hostType = 'scrm') {
wx.showNavigationBarLoading()
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
const path = pathEnum[projectName]
params = await this.getData(params, hostType)
return new Promise((resolve, reject) => {
let header =
RequestMethods === 'POST' ? {
'content-type': 'application/x-www-form-urlencoded'
} : {}
const merchantId = wx.$storage.get('srcm_shopmall_merchant_id')
if (merchantId) header.merchantId = merchantId
if (isShowLoading) {
requestTimes++
wx.showLoading({
title: '加载中'
})
}
wx.request({
url: `${HOST[hostType]}${path}router?method=${params.method}`,
data: params,
method: RequestMethods,
header,
dataType: 'json',
responseType: 'text',
success(response) {
/**业务代码 */
let {
data: {
code,
message
}, },
data session: {
} = response sessionId: () => {
if (returnAll) { const s = wx.$storage.get()
resolve(data) return (s && s.sessionId) || wx.$storage.get('scrm_shopmall_sessionId') || ''
return },
} },
if (code == 20 || code == 21) { getMerchantId: () => wx.$storage.get('srcm_shopmall_merchant_id') || undefined,
wx.hideLoading() // 语义化开关:20/21 登录后由页面重发,Promise 挂起(旧壳语义)。
loginReplay: true,
onLoginRequired: () => {
// 登录态失效(code 20/21):重跑当前页生命周期拉起登录。逻辑原样来自旧壳。
if (wx.$loginFlag) return if (wx.$loginFlag) return
if (!wx.$authStatus) { if (!wx.$authStatus) {
wx.$loginFlag = true wx.$loginFlag = true
...@@ -78,107 +44,36 @@ class Request { ...@@ -78,107 +44,36 @@ class Request {
thisPage.onLoad() thisPage.onLoad()
thisPage.onShow() thisPage.onShow()
wx.$loginFlag = false wx.$loginFlag = false
}).catch(() => wx.$loginFlag = false) }).catch(() => (wx.$loginFlag = false))
}
} else {
if (code == '0') {
resolve(data.data)
} else {
console.log(data)
wx.showToast({
title: typeof message == 'string' ? message : JSON.stringify(message) || '系统异常',
icon: 'none'
})
reject()
}
} }
}, },
fail(error) { })
wx.hideLoading()
console.error(`接口异常:`, error) const call = (params, returnAll = false, isShowLoading = false, hostType = 'scrm') =>
wx.showToast({ client.post(params.method, params, { hostType, returnAll, showLoading: isShowLoading })
title: typeof error == 'string' ? error : JSON.stringify(error) || '系统异常',
icon: 'error' const api = {
}) get: (params, returnAll = false, isShowLoading = false, hostType = 'scrm') =>
reject(error) call(params, returnAll, isShowLoading, hostType),
}, post: (params, returnAll = false, isShowLoading = false, hostType = 'scrm') =>
complete() { call(params, returnAll, isShowLoading, hostType),
if (isShowLoading) { // 兼容个别直接调用 request(RequestMethods, params, ...) 的形态:忽略首参 HTTP method。
requestTimes--; request: (_httpMethod, params, returnAll = false, isShowLoading = false, hostType = 'scrm') =>
if (requestTimes == 0) { call(params, returnAll, isShowLoading, hostType),
wx.hideLoading() reportTrack: (params) => client.post(params.method, params, { returnAll: true }),
} // 配置中心拉取,与 ROP 无关,原样保留。
}
wx.stopPullDownRefresh()
wx.hideNavigationBarLoading()
}
})
})
}
reportTrack(params) {
return this.request('POST', params, true)
}
async getData(params, hostType = 'scrm') {
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
else delete params.projectName
let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
if (secretKey[projectName]) {
appKey = secretKey[projectName].appKey
secret = secretKey[projectName].secret
}
if (hostType == 'dj') {
appKey = djSecretKey.appKey
secret = djSecretKey.secret
}
let {
sessionId
} = wx.$storage.get()
if (!sessionId) sessionId = wx.$storage.get('scrm_shopmall_sessionId')
let noSignAttr = []
if (!params.sessionId && sessionId) params.sessionId = sessionId
if (params.delSessionId) {
delete params.sessionId
delete params.delSessionId
}
if (params.noSignAttr) {
noSignAttr = params.noSignAttr
delete params.noSignAttr
}
params.v = '1.0.0'
params.format = 'json'
params.locale = 'zh_CN'
params.source = 'dj-wechat'
params.appKey = appKey
return sign(params, secret, noSignAttr)
}
getRopProject(method) {
const projectName = method.split('.')[2]
return projectName
}
getMock() { getMock() {
const configModule = 'scrm-shopmall', const configModule = 'scrm-shopmall'
env = { const env = { '1': 'develop', '2': 'test', '3': 'production', '4': 'beta' }[index]
'1': 'develop', const configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`
'2': 'test', return new Promise((resolve) => {
'3': 'production',
'4': 'beta'
} [index],
configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`
return new Promise(resolve => {
wx.request({ wx.request({
url: configUrl, url: configUrl, data: {}, method: 'GET', header: {},
data: {}, dataType: 'json', responseType: 'text',
method: 'GET', success(response) { resolve(response.data) },
header: {},
dataType: 'json',
responseType: 'text',
success(response) {
resolve(response.data)
}
}) })
}) })
} },
} }
export default new Request()
\ No newline at end of file \ No newline at end of file
export default api
#!/usr/bin/env node
/**
* store 的「构建 npm」入口:只管本小程序。
*
* 做的事:api-core 小程序产物 → 调开发者工具构建 npm(服务端口开着才自动)
* → 体检 miniprogram_npm。
*
* 用法:
* pnpm --filter @uj/mp-store run build:npm
* node mp-npm.mjs # 在 apps/mp/store 下直接跑
* node mp-npm.mjs --check # 只体检,不改任何文件
*
* 全量(四个小程序一起)请用仓库根的 `pnpm mp`。
*/
import { runLaneCli } from '../../../scripts/mp-npm-core.mjs';
runLaneCli('store');
...@@ -4,7 +4,9 @@ ...@@ -4,7 +4,9 @@
"private": true, "private": true,
"scripts": { "scripts": {
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"lint": "eslint src" "lint": "eslint src",
"build:npm": "node mp-npm.mjs",
"check:npm": "node mp-npm.mjs --check"
}, },
"dependencies": { "dependencies": {
"@uj/api-core": "workspace:*", "@uj/api-core": "workspace:*",
......
import { secretKey, djSecretKey, pathEnum, domain, sign } from './http.js' /**
* store 请求层:@uj/api-core 的客户端工厂。
*
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责,
* 本文件只传域名、凭据、会话与登录回调。
* public API 与旧壳一致:get/post/request(params, returnAll, requestPath),
* params 含 method,requestPath 对应 hostType(scrm/dj,缺省 scrm)。
*/
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core'
import { sign, domain, djSecretKey, pathEnum, secretKey } from './http.js'
import { getSessionId } from '~/utils/cache/storageApi' import { getSessionId } from '~/utils/cache/storageApi'
import network from '~/utils/network' import network from '~/utils/network'
/**接口 */
class Request { const client = createRopClient({
get(params, returnAll = false, requestPath) { hosts: { scrm: domain.scrm, dj: domain.dj, merchant: domain.merchant },
return this.request('GET', params, returnAll, requestPath) pathEnum,
} secretKey,
post(params, returnAll = false, requestPath) { djSecretKey,
return this.request('POST', params, returnAll, requestPath) // 本 app 的签名实现(字节级对齐旧壳):直接传函数,工厂内部包成签名策略。
} signature: sign,
async request(RequestMethods, params, returnAll, requestPath = 'scrm') { defaultCredential: {
appKey: '48e5e13229b82c1b4e6e8c96151f0637',
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
},
session: { sessionId: () => getSessionId() || '' },
loginReplay: true,
// 网络不可用:与旧壳一致——静默返回(不 reject、不 toast),由调用方自行兜底。
beforeRequest: async () => {
const type = await network.getNetworkType() const type = await network.getNetworkType()
if (type == 'none') return if (type == 'none') return { abort: true, value: undefined }
wx.showNavigationBarLoading() },
// 加签走 @uj/api-core 的 Signer 契约(允许异步),故在进 Promise 前把 params 备齐。 onLoginRequired: (_code, { body }) => {
params = await this.getData(params, requestPath)
return new Promise((resolve, reject) => {
let header =
RequestMethods === 'POST'
? {
'content-type': 'application/x-www-form-urlencoded'
}
: {}
let projectName = params.apiProjectName || this.getRopProject(params.method)
if (!projectName) projectName = this.getRopProject(params.method)
let path = pathEnum[projectName]
if (!path) {
path = requestPath == 'dj' ? `/rop-dj-${projectName}/` : `/rop-scrm-${projectName}/`
}
wx.request({
url: `${domain[requestPath]}${path}router?method=${params.method}`,
data: params,
method: RequestMethods,
header,
dataType: 'json',
responseType: 'text',
success(response) {
/**业务代码 */
let {
data: { code, message },
data
} = response
if (code == 20 || code == 21) {
wx.$storage.rm('sessionId') wx.$storage.rm('sessionId')
wx.$storage.rm('userInfo') wx.$storage.rm('userInfo')
wx.$storage.rm('subMerchant') wx.$storage.rm('subMerchant')
const thisPage = wx.$router.getPageInstance(), const thisPage = wx.$router.getPageInstance()
autoLoginObject = wx.$storage.get('auto_login_object') const autoLoginObject = wx.$storage.get('auto_login_object')
if (thisPage.route == 'login/loading/loading') { // 旧壳特例:已在登录 loading 页时,直接 resolve 完整信封,不再跳转。
resolve(data) if (thisPage.route == 'login/loading/loading') return { resolve: body }
return
} else {
if (autoLoginObject) wx.$router.reLaunch('login.loading') if (autoLoginObject) wx.$router.reLaunch('login.loading')
else wx.$router.reLaunch('login.index') else wx.$router.reLaunch('login.index')
}
} else {
if (returnAll) {
resolve(data)
return
}
if (code == '0') {
resolve(data.data)
} else {
wx.showToast({
title: message || '网络请求失败',
icon: 'none'
})
}
}
}, },
fail(error) { })
wx.hideLoading()
console.log(`接口异常:`, error) const call = (params, returnAll = false, requestPath = 'scrm') =>
wx.showToast({ client.post(params.method, params, {
title: '网络请求失败', hostType: requestPath,
icon: 'error' returnAll,
}) // apiProjectName 是旧壳用来覆盖项目名的参数(api/index.js、output.js、login 用到)。
reject(error) projectName: params.apiProjectName,
},
complete() {
wx.stopPullDownRefresh()
wx.hideNavigationBarLoading()
}
})
}) })
}
async getData(params, requestPath) { const api = {
let projectName = params.projectName get: (params, returnAll = false, requestPath = 'scrm') => call(params, returnAll, requestPath),
if (!projectName) projectName = this.getRopProject(params.method) post: (params, returnAll = false, requestPath = 'scrm') => call(params, returnAll, requestPath),
else delete params.projectName request: (params, returnAll = false, requestPath = 'scrm') => call(params, returnAll, requestPath),
let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
if (requestPath == 'scrm' && secretKey[projectName]) {
appKey = secretKey[projectName].appKey
secret = secretKey[projectName].secret
}
if (requestPath == 'dj') {
appKey = djSecretKey.appKey
secret = djSecretKey.secret
}
const sessionId = getSessionId()
let noSignAttr = []
if (!params.sessionId && sessionId) params.sessionId = sessionId
if (params.noSignAttr) {
noSignAttr = params.noSignAttr
delete params.noSignAttr
}
params.v = '1.0.0'
params.format = 'json'
params.locale = 'zh_CN'
params.source = 'dj-wechat'
params.appKey = appKey
return sign(params, secret, noSignAttr)
}
getRopProject(method) {
const projectName = method.split('.')[2]
return projectName
}
} }
export default new Request()
export default api
...@@ -27,18 +27,29 @@ npm run test:affected ...@@ -27,18 +27,29 @@ npm run test:affected
# 环境初始化(SAAS+V5.8.3 等含二手车分包的分支) # 环境初始化(SAAS+V5.8.3 等含二手车分包的分支)
克隆或切换分支并 `git pull` 后,在项目根目录执行: 本 lane 已随大仓迁入 `apps/mp/usedcar`,依赖有两层,必须分开装:
```bash ```bash
npm install # 1) 工作区依赖(大仓根目录):@uj/api-core、@vant/weapp、dayjs、测试工具链
pnpm install
# 2) 二手车分包的 node_modules(npm 单独装,不是 pnpm)
pnpm --filter @uj/mp-usedcar run setup:deps
``` ```
根目录 `npm install` 会自动通过 `postinstall` 安装 `packageUsedCar` 依赖(含 `glsk-map-jssdk`)。也可执行 `npm run setup`,效果相同。 `packageUsedCar` 在 `pnpm-workspace.yaml` 里被 `!apps/mp/usedcar/packageUsedCar` 显式排除,根 `pnpm install` **不会**给它生成 `node_modules`。缺这一步,开发者工具编译时直接报:
```
The related node_modules of ...\packageUsedCar\package.json is not found,
please run `npm install` at ...\packageUsedCar
```
(历史原因:独立仓时期靠 `postinstall` 跑 `scripts/setup-package-used-car.mjs`,迁入大仓、该包成为 workspace 成员后这个钩子没有跟过来,`setup:deps` 就是它的显式替代,效果等同在该目录下执行 `npm install`。)
可选校验: 可选校验:
```bash ```bash
npm run verify:npm-config # 检查 project.config 引用的 package.json 是否存在 pnpm --filter @uj/mp-usedcar run verify:npm-config # 检查 project.config 引用的 package.json 是否存在
``` ```
微信开发者工具:**工具 → 构建 npm**(主包与 `packageUsedCar` 分包均需构建)。`npm install` 只安装 `node_modules`,不会生成 `miniprogram_npm`。 微信开发者工具:**工具 → 构建 npm**(主包与 `packageUsedCar` 分包均需构建)。`npm install` 只安装 `node_modules`,不会生成 `miniprogram_npm`。
...@@ -60,12 +71,23 @@ git checkout HEAD -- project.config.json packageUsedCar/package.json packageUsed ...@@ -60,12 +71,23 @@ git checkout HEAD -- project.config.json packageUsedCar/package.json packageUsed
npm install npm install
``` ```
若报错 `node_modules of ... packageUsedCar/package.json is not found`: 若报错 `node_modules of ... packageUsedCar/package.json is not found`(即本次迁入后遇到的这条):
```bash ```bash
npm install pnpm --filter @uj/mp-usedcar run setup:deps
``` ```
若报错 `Error: module 'utils/request/@uj/api-core.js' is not defined, require args is '@//uj/api-core'`(首屏白屏):
说明 `miniprogram_npm/` 里没有 `@uj/api-core`。先确认产物存在再构建 npm:
```bash
pnpm --filter @uj/api-core build # 产出 dist/ 与 miniprogram_dist/
ls miniprogram_npm/@uj/api-core/index.js # 构建 npm 之后应存在
```
根因不是漏装依赖,而是 `packages/api-core/package.json` 的 `"miniprogram"` 字段必须指向**目录**:开发者工具 `checkIsMiniprogramPack()` 只对目录做整目录拷贝,指到文件(曾经是 `./dist/index.cjs`)会掉进 `packJs()` 兜底分支并静默跳过,`miniprogram_npm` 里就永远没有这个包。见 `packages/api-core/tsup.config.ts` 的注释。
然后在开发者工具中重新「构建 npm」;仍异常可 **清缓存 → 全部清除** 后重开项目。 然后在开发者工具中重新「构建 npm」;仍异常可 **清缓存 → 全部清除** 后重开项目。
# 账号登录可以使用以下(验证码 开发和测试环境任意输入即可): # 账号登录可以使用以下(验证码 开发和测试环境任意输入即可):
......
...@@ -90,6 +90,8 @@ App({ ...@@ -90,6 +90,8 @@ App({
wx.$router = router; wx.$router = router;
wx.$modal = this.showModal; wx.$modal = this.showModal;
wx.$util = util; wx.$util = util;
// 启动打开会话闸门:sessionId 尚未落地时,首个请求先等一会儿再发(见 util.openSessionGate)
util.openSessionGate();
wx.$api = wxApi; wx.$api = wxApi;
wx.$eventbus = eventbus; wx.$eventbus = eventbus;
wx.$track = $Track wx.$track = $Track
...@@ -167,7 +169,9 @@ App({ ...@@ -167,7 +169,9 @@ App({
} else { } else {
let thisPage = wx.$router.getPageInstance() let thisPage = wx.$router.getPageInstance()
// 启动页loading中的埋点接口 在触发登录超时后 ios端wx.showModal会被页面跳转截断,导致无弹窗,将loading页面这个埋点接口的登录超时不做弹窗处理 // 启动页loading中的埋点接口 在触发登录超时后 ios端wx.showModal会被页面跳转截断,导致无弹窗,将loading页面这个埋点接口的登录超时不做弹窗处理
if (thisPage?.route == 'pages/loading/loading' && RequestMethods.includes('dj.api.smartcarlife.staff.login.record.save')) return // 调用方(请求层 / newRequest)可能不带第三参,这里必须容错:
// 直接 RequestMethods.includes 会在 undefined 上抛错,弹窗逻辑整段跑不到。
if (thisPage?.route == 'pages/loading/loading' && RequestMethods?.includes?.('dj.api.smartcarlife.staff.login.record.save')) return
// 标志位 解决安卓查复弹框问题 // 标志位 解决安卓查复弹框问题
if (wx.__HAS_NOTLOGIN_MODAL) return false; if (wx.__HAS_NOTLOGIN_MODAL) return false;
wx.__HAS_NOTLOGIN_MODAL = true; wx.__HAS_NOTLOGIN_MODAL = true;
......
#!/usr/bin/env node
/**
* usedcar 的「构建 npm」入口:只管本小程序。
*
* 做的事:api-core 小程序产物 → packageUsedCar 内嵌依赖(npm,不进 workspace)
* → 调开发者工具构建 npm(服务端口开着才自动)→ 体检 miniprogram_npm。
*
* 用法:
* pnpm --filter @uj/mp-usedcar run build:npm
* node mp-npm.mjs # 在 apps/mp/usedcar 下直接跑
* node mp-npm.mjs --check # 只体检,不改任何文件
*
* 全量(四个小程序一起)请用仓库根的 `pnpm mp`。
*/
import { runLaneCli } from '../../../scripts/mp-npm-core.mjs';
runLaneCli('usedcar');
...@@ -3,6 +3,9 @@ ...@@ -3,6 +3,9 @@
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"scripts": { "scripts": {
"build:npm": "node mp-npm.mjs",
"check:npm": "node mp-npm.mjs --check",
"setup:deps": "node scripts/setup-package-used-car.mjs",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"lint": "eslint src", "lint": "eslint src",
"test": "node scripts/run-tests.mjs", "test": "node scripts/run-tests.mjs",
......
...@@ -18,7 +18,8 @@ const request = createGscClient({ ...@@ -18,7 +18,8 @@ const request = createGscClient({
session: { session: {
requiresSession: true, requiresSession: true,
sessionParamName: 'sessionId', sessionParamName: 'sessionId',
sessionId: () => util.getSessionId() || '', // 与 ROP 侧共用同一个会话闸门:sessionId 落地前先等,避免服务端判「缺少 sessionId」
sessionId: () => util.waitSessionId(),
}, },
response: { response: {
codeKey: 'code', codeKey: 'code',
......
{
"name": "packageUsedCar",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"glsk-map-jssdk": "^0.1.1"
}
},
"node_modules/glsk-map-jssdk": {
"version": "0.1.1",
"resolved": "https://registry.npmmirror.com/glsk-map-jssdk/-/glsk-map-jssdk-0.1.1.tgz",
"integrity": "sha512-kwCyU8A1t7Q7V2hlzC03nc9VNNW9HPXQ5YhHsGGnrEtPxykGDG7AEyT5O7LY1zZk/8adkkk6FHgCM53r6p/4yw==",
"license": "ISC"
}
}
}
...@@ -214,6 +214,10 @@ Page({ ...@@ -214,6 +214,10 @@ Page({
flag: true flag: true
}) })
}) })
// 登录失效 / 网络失败时兜住,否则是未处理的 Promise 拒绝,且 loading 会一直转
.catch(() => {
wx.$util.hideLoading()
})
}, },
chooseAccount(e) { chooseAccount(e) {
let { item } = e.currentTarget.dataset let { item } = e.currentTarget.dataset
......
...@@ -168,7 +168,9 @@ Page({ ...@@ -168,7 +168,9 @@ Page({
this.setData({ this.setData({
jumpPageFlag: true jumpPageFlag: true
}) })
getYQList() // 这里原来有一句 getYQList():它在登录接口之前发出,此时还没有 sessionId,
// 服务端必然返回登录失效码,调用方又没 catch,于是变成一条「缺少sessionId参数」的红字。
// 三个登录分支(短信 / 账密 / 免登)都已经在 setSessionId 之后调用,这一句是多余的。
// console.log(smsLogin,'smsLogin'); // console.log(smsLogin,'smsLogin');
if (loginType == 1) { if (loginType == 1) {
// 手机号登录 // 手机号登录
...@@ -676,8 +678,10 @@ Page({ ...@@ -676,8 +678,10 @@ Page({
code, code,
appId: wx.getAccountInfoSync().miniProgram.appId appId: wx.getAccountInfoSync().miniProgram.appId
}).then(res => { }).then(res => {
wx.$util.setOpenId(res.data.openId) wx.$util.setOpenId(res?.data?.openId)
}) })
// openId 只是辅助信息,拿不到不影响登录;不 catch 会变成未处理的 Promise 拒绝
.catch(() => { })
} }
}, },
}) })
......
{ {
"projectname": "%E7%B2%BE%E5%93%81%E5%8D%87%E7%BA%A7", "projectname": "%E7%B2%BE%E5%93%81%E5%8D%87%E7%BA%A7",
"compileType": "miniprogram", "compileType": "miniprogram",
"libVersion": "3.13.1", "libVersion": "3.14.3",
"packOptions": { "packOptions": {
"ignore": [ "ignore": [
{ {
"value": "mp-npm.mjs",
"type": "file"
},
{
"value": ".vscode", "value": ".vscode",
"type": "folder" "type": "folder"
}, },
......
...@@ -691,7 +691,8 @@ Page({ ...@@ -691,7 +691,8 @@ Page({
totalTableSum, totalTableSum,
tableWidth, tableWidth,
tableObj, tableObj,
pages: data?.page?.pages // 服务端没返回分页信息时不能置 undefined:setData 会告警,且 pages == pageNum 判断会失真
pages: data?.page?.pages || 0
}) })
} else { } else {
this.showToast(message) this.showToast(message)
...@@ -731,21 +732,16 @@ Page({ ...@@ -731,21 +732,16 @@ Page({
.then(result => { .then(result => {
let { code, data } = result let { code, data } = result
if (code == 0) { if (code == 0) {
let rateValue = NP.divide( // 目标值为 0 时 NP.divide(0, 0) 会得到 NaN,页面上就会显示 "NaN%";这里统一按 0 处理
data?.totalOutputValue || 0, const calcRate = (value, target) => {
data?.totalTargetOutputValue || 0 if (!target) return 0
) return NP.round(NP.times(NP.divide(value || 0, target), 100), 2)
rateValue = NP.times(rateValue, 100) }
rateValue = NP.round(rateValue, 2) let rateValue = calcRate(data?.totalOutputValue, data?.totalTargetOutputValue)
console.log(rateValue, 'rateValue') console.log(rateValue, 'rateValue')
if (data.areaSupervisionList && data.areaSupervisionList.length) { if (data.areaSupervisionList && data.areaSupervisionList.length) {
data.areaSupervisionList.forEach(item => { data.areaSupervisionList.forEach(item => {
let rateValue = NP.divide( let rateValue = calcRate(item?.outputValue, item?.targetOutputValue)
item?.outputValue || 0,
item?.targetOutputValue || 0
)
rateValue = NP.times(rateValue, 100)
rateValue = NP.round(rateValue, 2)
item.rateValue = rateValue item.rateValue = rateValue
// 百分比 // 百分比
item.rateValuePercent = rateValue + '%' item.rateValuePercent = rateValue + '%'
...@@ -753,12 +749,7 @@ Page({ ...@@ -753,12 +749,7 @@ Page({
} }
if (data.outoutValueList && data.outoutValueList.length) { if (data.outoutValueList && data.outoutValueList.length) {
data.outoutValueList.forEach(item => { data.outoutValueList.forEach(item => {
let rateValue = NP.divide( let rateValue = calcRate(item?.outputValue, item?.targetOutputValue)
item?.outputValue || 0,
item?.targetOutputValue || 0
)
rateValue = NP.times(rateValue, 100)
rateValue = NP.round(rateValue, 2)
item.rateValue = rateValue item.rateValue = rateValue
item.rateValuePercent = rateValue + '%' item.rateValuePercent = rateValue + '%'
}) })
......
...@@ -44,7 +44,10 @@ export default function fixWxShowToast() { ...@@ -44,7 +44,10 @@ export default function fixWxShowToast() {
setTimeout(() => { setTimeout(() => {
isShowToast = false isShowToast = false
}, 2000) }, 2000)
console.error('--------showToast--------') // 只打分隔线排查时看不出是哪条提示,把文案一起打出来
const toastOption = param[0]
const toastTitle = typeof toastOption === 'string' ? toastOption : toastOption?.title
console.error('--------showToast--------', toastTitle || '')
return showToast.apply(this, param) // 原样移交函数参数和this return showToast.apply(this, param) // 原样移交函数参数和this
} }
}) })
......
...@@ -112,8 +112,48 @@ const getSessionId = () => { ...@@ -112,8 +112,48 @@ const getSessionId = () => {
return wx.getStorageSync('dj_boutique_sessionId') return wx.getStorageSync('dj_boutique_sessionId')
} }
/**
* 会话闸门:启动瞬间 storage 里可能还没有 sessionId(换票 / 登录流程未完成),
* 这时发出去的请求会被服务端判成「缺少 sessionId 参数」。
* 让请求等一次 setSessionId,拿到就立刻放行;等不到(没登录 / 超时)按空值放行,
* 不改变原来的失败路径,也不拖慢启动。
*/
const SESSION_GATE_TIMEOUT = 1200
const closedGate = () => ({ settled: true, promise: null, settle: () => {} })
let sessionGate = closedGate()
const openSessionGate = () => {
if (!sessionGate.settled) return
let settleFn
const gate = { settled: false, promise: null, settle: (value) => settleFn?.(value) }
gate.promise = new Promise((resolve) => {
const timer = setTimeout(() => settleFn(getSessionId() || ''), SESSION_GATE_TIMEOUT)
settleFn = (value) => {
clearTimeout(timer)
gate.settled = true
resolve(value)
}
})
sessionGate = gate
}
/** 显式放行:确定这次不会再有 sessionId(跳登录页 / 登出),别让请求干等。 */
const closeSessionGate = (value) => {
if (!sessionGate.settled) sessionGate.settle(value ?? '')
sessionGate = closedGate()
}
/** 请求层用:有 sessionId 直接给;没有则等闸门(最多 SESSION_GATE_TIMEOUT 毫秒)。 */
const waitSessionId = () => {
const sessionId = getSessionId()
if (sessionId) return Promise.resolve(sessionId)
if (sessionGate.settled) return Promise.resolve('')
return sessionGate.promise
}
const setSessionId = sessionId => { const setSessionId = sessionId => {
wx.setStorageSync('dj_boutique_sessionId', sessionId) wx.setStorageSync('dj_boutique_sessionId', sessionId)
closeSessionGate(sessionId)
} }
const setOpenId = openId => { const setOpenId = openId => {
wx.setStorageSync('dj_boutique_openId', openId) wx.setStorageSync('dj_boutique_openId', openId)
...@@ -128,6 +168,8 @@ const removeStorage = () => { ...@@ -128,6 +168,8 @@ const removeStorage = () => {
wx.removeStorageSync('dateStaffPop') wx.removeStorageSync('dateStaffPop')
wx.removeStorageSync('abnormalOrderPop') wx.removeStorageSync('abnormalOrderPop')
wx.removeStorageSync('dj_boutique_webview_h5_tokens') wx.removeStorageSync('dj_boutique_webview_h5_tokens')
// 会话已清掉,后续请求不必再等闸门
closeSessionGate('')
} }
const showNoAccess = () => { const showNoAccess = () => {
...@@ -311,6 +353,9 @@ const util = { ...@@ -311,6 +353,9 @@ const util = {
setOpenId, setOpenId,
getOpenId, getOpenId,
setSessionId, setSessionId,
openSessionGate,
closeSessionGate,
waitSessionId,
removeStorage, removeStorage,
showNoAccess, showNoAccess,
setStorageSync, setStorageSync,
......
...@@ -7,7 +7,10 @@ import { themeConfig } from '@/theme/themeConfig'; ...@@ -7,7 +7,10 @@ import { themeConfig } from '@/theme/themeConfig';
* 主壳 -> 子应用的显式契约(唯一构造点)。 * 主壳 -> 子应用的显式契约(唯一构造点)。
* *
* request 只有一行 `http.request(req)`:把子应用传来的完整 axios config 原样交给 * request 只有一行 `http.request(req)`:把子应用传来的完整 axios config 原样交给
* 主壳那份挂了 RSA 加签 / 响应验签 / context-path / 401 统一登出拦截器的实例。 * 主壳那份请求引擎——它现在是 @uj/api-core 统一 Request 门面的装配点
* (选 strategies.webHost 方案、注入 axios 作 transport、把 RSA 注册成具名签名策略),
* 加签 / 验签 / context-path / 401 统一登出 / 业务码归一全部由方案策略与门面负责,
* 与四个原生小程序同一套机制。
* 于是全项目只有一份签名状态(_signInitPromise、setServerPublicKey、PEM、VITE_*)。 * 于是全项目只有一份签名状态(_signInitPromise、setServerPublicKey、PEM、VITE_*)。
* *
* 为什么能传函数:wujie 的 iframe 是同源 srcdoc,props 是**引用传递**而非 * 为什么能传函数:wujie 的 iframe 是同源 srcdoc,props 是**引用传递**而非
......
...@@ -25,8 +25,26 @@ const UJ_UNAUTHORIZED_CODE = 10002; ...@@ -25,8 +25,26 @@ const UJ_UNAUTHORIZED_CODE = 10002;
*/ */
export const glxsrMd5Signer: Signer = createMd5Signer({ id: 'glsx-md5' }); export const glxsrMd5Signer: Signer = createMd5Signer({ id: 'glsx-md5' });
/** 返回值映射:把老响应包归一成主壳拦截器认得的形状。 */ /** 主壳 transport 为验签保留原始响应串,所以字符串响应要先解析成对象。 */
export function normalizeGlsxEnvelope(body: unknown): NormalizedEnvelope { function parseRawBody(raw: unknown): unknown {
if (typeof raw !== 'string') return raw;
try {
return JSON.parse(raw) as unknown;
} catch {
// 非 JSON(导出文件流等)原样交回,由调用方按二进制处理。
return raw;
}
}
/**
* 老网关信封 → 主壳信封:code:'0' → { data },'21' → 10002 走统一登出。
*
* 唯一挂载点是 GatewayStrategy.normalize:host sender 把它挂在 transformResponse 上,
* 在主壳响应拦截器之前执行(函数随 props 引用传递,不序列化),于是 401 登出、
* 错误提示、ApiResult 取值仍只有一套规则。小程序侧则由 wx/fetch sender 在收到响应后调用。
*/
export function normalizeGlsxEnvelope(raw: unknown): NormalizedEnvelope {
const body = parseRawBody(raw);
if (!body || typeof body !== 'object') return { data: body }; if (!body || typeof body !== 'object') return { data: body };
const envelope = body as Record<string, unknown>; const envelope = body as Record<string, unknown>;
const code = envelope['code']; const code = envelope['code'];
...@@ -43,41 +61,17 @@ export function normalizeGlsxEnvelope(body: unknown): NormalizedEnvelope { ...@@ -43,41 +61,17 @@ export function normalizeGlsxEnvelope(body: unknown): NormalizedEnvelope {
}; };
} }
/**
* 请求归一:老网关的 code 语义在 axios 响应拦截器之前完成转换,
* 所以映射挂在 transformResponse 上(函数随 props 引用传递,不序列化)。
*/
export function toHostEnvelope(raw: unknown): unknown {
if (typeof raw !== 'string') return normalizeGlsxEnvelope(raw);
try {
return normalizeGlsxEnvelope(JSON.parse(raw) as unknown);
} catch {
// 非 JSON(导出文件流等)原样交回,由调用方按二进制处理
return raw;
}
}
interface GlsxGatewayDef { interface GlsxGatewayDef {
id: GatewayId; id: GatewayId;
router: string; router: string;
tokenHeader: string; tokenHeader: string;
} }
/**
* 请求归一:对方信封的 code 语义在主机响应拦截器之前完成转换(见 createHostSender),
* 所以映射挂在 RawRequest.normalize 上。字符串(未预解析的响应体)先 JSON.parse。
*/
export function normalizeGlsxEnvelopeRaw(raw: unknown): NormalizedEnvelope {
const env = toHostEnvelope(raw);
if (typeof env === 'string') return { data: env };
return env as NormalizedEnvelope;
}
export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy { export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy {
return { return {
...def, ...def,
signer: glxsrMd5Signer, signer: glxsrMd5Signer,
normalize: normalizeGlsxEnvelopeRaw, normalize: normalizeGlsxEnvelope,
}; };
} }
......
...@@ -3,15 +3,12 @@ export type { ...@@ -3,15 +3,12 @@ export type {
GatewayCredential, GatewayCredential,
GatewayStrategy, GatewayStrategy,
NormalizedEnvelope, NormalizedEnvelope,
RawRequest,
RawResponse,
RequestSender,
RpcCall, RpcCall,
Signer, Signer,
SignInput,
} from './types'; } from './types';
export { rpcCall } from './rpc'; export { rpcCall, request } from './rpc';
// 登记与解析已经抽到 @uj/api-core(packages/api-core),本域只重新导出,保持 `@/adapter` 的引用面不变 // 登记表在 @uj/api-core;本域的 ./gateways 负责把三个老网关登记进去(由 ./rpc 显式 import),
// 这里重新导出以保持 `@/adapter` 的引用面不变。
export { registerGateway, resolveGateway } from '@uj/api-core'; export { registerGateway, resolveGateway } from '@uj/api-core';
export { export {
createGlsxGateway, createGlsxGateway,
...@@ -27,5 +24,4 @@ export { ...@@ -27,5 +24,4 @@ export {
setGatewayCredential, setGatewayCredential,
setGatewayTokenProvider, setGatewayTokenProvider,
} from './credentials'; } from './credentials';
export { matchPermission, legacyAliases } from './perms'; export { matchPermission } from './perms';
export type { PermissionAliases } from './perms';
...@@ -53,11 +53,3 @@ export function matchPermission( ...@@ -53,11 +53,3 @@ export function matchPermission(
} }
return aliases.some((code) => granted.has(code)); return aliases.some((code) => granted.has(code));
} }
/**
* 老系统的菜单路径码 -> 现系统扁平码。
* 双写期后端若仍按老码下发,这里补一次映射即可,页面代码不需要知道。
*/
export function legacyAliases(...codes: string[]): PermissionAliases {
return codes.filter(Boolean);
}
import { createHostSender, createRpcDispatcher } from '@uj/api-core'; import { createRpcGatewayClient } from '@uj/api-core/Request';
import { requestViaHost } from '@uj/platform-sdk'; import { requestViaHost } from '@uj/platform-sdk';
// 显式 import(而非依赖 barrel 的 re-export 副作用):保证任何调用路径下网关策略都已登记,
// 否则 resolveGateway 会抛「网关尚未接入」。
import './gateways';
import { getGatewayCredential, getGatewayToken } from './credentials'; import { getGatewayCredential, getGatewayToken } from './credentials';
import type { GatewayId, RpcCall } from './types'; import type { GatewayId, RpcCall } from './types';
...@@ -7,20 +10,37 @@ import type { GatewayId, RpcCall } from './types'; ...@@ -7,20 +10,37 @@ import type { GatewayId, RpcCall } from './types';
const LEGACY_TIMEOUT = 180000; const LEGACY_TIMEOUT = 180000;
/** /**
* 把一次「业务语义」的 RPC 调用组装并交主壳发出。 * web 侧与四个原生小程序共用同一个 `@uj/api-core` 门面。
* *
* 组装逻辑(落点 / 加签字段 / 信封归一)在 @uj/api-core 的 createRpcDispatcher 里, * 一个 createRpcGatewayClient({配置}) 拿到 client;方案(rpcGateway)、fixedParams 合并、
* 本文件只负责把积分域的凭据与「主壳请求发送器」注入进去 —— * 加签、router 落点、令牌头、信封归一全部由 registerGateway 登记的 GatewayStrategy 决定,
* 包不持有 transport,「请求层绝不下放」的约束仍然成立(见 ARCHITECTURE.md §2)。 * 与小程序 createRpcDispatcher 共用 prepareRpcCall,字节同源。
* 平台差异只由 transport 一处表达:web 子应用走主壳注入的 axios(hostSend),
* 门面不打包 axios,请求仍交回主壳那唯一一份实例。
*
* 装配层只给环境参数:
* · gatewayCredential / gatewayToken —— 本域 .env 凭据与会话令牌,包内不留密钥字面量;
* · contentType:false —— 不预置 Content-Type,否则会改变主壳加签的 canonical 原文;
* · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等),
* 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。
*/ */
const dispatch = createRpcDispatcher({ export const request = createRpcGatewayClient({
sender: createHostSender(requestViaHost()), transport: 'host',
// 积分域只认自己的 GatewayId;调度器是通用 string,在边界处收窄。 hostSend: requestViaHost(),
resolveCredential: (id) => getGatewayCredential(id as GatewayId),
resolveToken: getGatewayToken,
timeout: LEGACY_TIMEOUT, timeout: LEGACY_TIMEOUT,
contentType: false,
gatewayCredential: (id) => getGatewayCredential(id as GatewayId),
gatewayToken: getGatewayToken,
errorHandler: (err) => {
throw err.cause ?? err;
},
}); });
/** 业务语义调用 → 门面只传参;rpcCall 的公开签名不变,业务模块零改动。 */
export function rpcCall<T = unknown>(call: RpcCall): Promise<T> { export function rpcCall<T = unknown>(call: RpcCall): Promise<T> {
return dispatch(call) as Promise<T>; return request.post<T>(call.method, call.params, {
gateway: call.gateway,
signed: call.signed,
unsignedKeys: call.unsignedKeys,
});
} }
...@@ -2,18 +2,15 @@ ...@@ -2,18 +2,15 @@
* 积分域适配层对外的类型表面。 * 积分域适配层对外的类型表面。
* *
* 通用的「外部网关接入契约」已抽到 @uj/api-core(传输无关、可被小程序复用); * 通用的「外部网关接入契约」已抽到 @uj/api-core(传输无关、可被小程序复用);
* 这里只补积分域特有的网关标识,并重新导出通用类型,让老的 import 路径 `@/adapter` 不变。 * 这里只补积分域特有的网关标识,并重新导出本域实际用到的类型,
* 让老的 import 路径 `@/adapter` 不变。传输层类型请直接从 @uj/api-core 取。
*/ */
export type { export type {
GatewayCredential, GatewayCredential,
GatewayStrategy, GatewayStrategy,
NormalizedEnvelope, NormalizedEnvelope,
RawRequest,
RawResponse,
RequestSender,
RpcCall, RpcCall,
Signer, Signer,
SignInput,
} from '@uj/api-core'; } from '@uj/api-core';
/** 积分域已接入的外部网关标识。值即老项目 api 模块里的 url 前缀,便于对账。 */ /** 积分域已接入的外部网关标识。值即老项目 api 模块里的 url 前缀,便于对账。 */
......
/**
* 业务模块写的是 `import { ApiClient } from '../core/client'`(相对路径),
* 所以子应用必须有一份同名桥接文件。继承目标换成 RemoteApiClient 后,
* 调用面完全一致,实际请求由主壳 props.request 代理。
*/
export { RemoteApiClient as ApiClient } from '@uj/platform-sdk';
export type { BlobResponse } from '@uj/platform-sdk';
import { ApiClient } from './client';
import { rpcCall } from '@/adapter'; import { rpcCall } from '@/adapter';
import type { GatewayId } from '@/adapter'; import type { GatewayId } from '@/adapter';
...@@ -6,10 +5,11 @@ import type { GatewayId } from '@/adapter'; ...@@ -6,10 +5,11 @@ import type { GatewayId } from '@/adapter';
* 积分域的接口不是 REST:一个 RPC 方法名 + 一层平铺参数。 * 积分域的接口不是 REST:一个 RPC 方法名 + 一层平铺参数。
* 业务模块因此只描述这两件事,落点、加签、返回码语义全部交给适配层的网关策略。 * 业务模块因此只描述这两件事,落点、加签、返回码语义全部交给适配层的网关策略。
* *
* 继承 ApiClient 而不是另起一套:请求出口仍只有主壳 props.request 那一份, * 不再继承 RemoteApiClient:points 的所有接口都走 rpc(),父类的 get/post/getBlob/http
* 这条边界由 scripts/check-boundaries.mjs 静态复查。 * 一个也没用到,留着只会让人误以为还有第二条请求出口。唯一出口始终是
* @/adapter/rpc.ts 的 Request → 主壳 props.request,边界由 check-boundaries.mjs 复查。
*/ */
export class RpcApiClient extends ApiClient { export class RpcApiClient {
protected rpc<T>( protected rpc<T>(
gateway: GatewayId, gateway: GatewayId,
method: string, method: string,
......
...@@ -20,13 +20,13 @@ ...@@ -20,13 +20,13 @@
.uj-points-detail-grid { .uj-points-detail-grid {
display: grid; display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 4px 24px; gap: 4px 16px;
} }
.uj-points-detail-item { .uj-points-detail-item {
display: flex; display: flex;
gap: 8px; gap: 8px;
min-width: 0; min-width: 0;
padding: 6px 0; padding: 4px 0;
font-size: 13px; font-size: 13px;
} }
.uj-points-detail-item dt { .uj-points-detail-item dt {
...@@ -40,6 +40,8 @@ ...@@ -40,6 +40,8 @@
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
} }
/* 累计结算金额条:一排等宽浅灰平铺块,对齐老系统的 .statistics / .content-item。
老系统是 flex:1 的平铺灰块、无描边、无圆角,这里用 #f7f9fa 一致底色。 */
.uj-points-statistics { .uj-points-statistics {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
...@@ -49,23 +51,24 @@ ...@@ -49,23 +51,24 @@
} }
.uj-points-statistics-item { .uj-points-statistics-item {
flex: 1 1 200px; flex: 1 1 200px;
border: 1px solid var(--uj-border); min-width: 200px;
border-radius: 10px; background: #f7f9fa;
padding: 12px 16px; border-radius: 8px;
background: var(--uj-surface); padding: 16px;
} }
.uj-points-statistics-label { .uj-points-statistics-label {
color: var(--uj-text-3); color: var(--uj-text-3);
font-size: 12px; font-size: 14px;
margin-bottom: 12px;
} }
.uj-points-statistics-value { .uj-points-statistics-value {
margin-top: 6px; font-size: 26px;
font-size: 20px; font-weight: 700;
font-weight: 600; color: var(--uj-text-1);
} }
.uj-points-statistics-value span { .uj-points-statistics-value span {
margin-left: 4px; margin-left: 4px;
font-size: 12px; font-size: 14px;
font-weight: 400; font-weight: 400;
color: var(--uj-text-3); color: var(--uj-text-3);
} }
...@@ -80,9 +83,10 @@ ...@@ -80,9 +83,10 @@
} }
} }
/* 统计条卡片的标题行:左标签、右「查看更多」。 */ /* 统计条容器与标题行:对齐老系统 .statistics(无外框)与 .title(16px 粗体)。 */
.uj-points-statistics-card { .uj-points-statistics-card {
flex: none; flex: none;
margin-bottom: 12px;
} }
.uj-points-statistics-head { .uj-points-statistics-head {
display: flex; display: flex;
...@@ -90,18 +94,19 @@ ...@@ -90,18 +94,19 @@
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 12px;
margin-bottom: 12px; margin-bottom: 12px;
font-size: 13px; font-size: 16px;
font-weight: 600; font-weight: 700;
color: var(--uj-text-1);
} }
/* 弹窗里的分组小标题与提示:统一比正文小一号、取第三级文字色。 */ /* 弹窗里的分组小标题与提示:统一比正文小一号、取第三级文字色。 */
.uj-points-dialog-label { .uj-points-dialog-label {
display: block; display: block;
margin-bottom: 8px; margin-bottom: 6px;
font-size: 13px; font-size: 13px;
} }
.uj-points-dialog-hint { .uj-points-dialog-hint {
display: block; display: block;
margin-top: 8px; margin-top: 6px;
font-size: 12px; font-size: 12px;
line-height: 1.7; line-height: 1.7;
} }
...@@ -128,7 +133,7 @@ ...@@ -128,7 +133,7 @@
} }
.uj-points-idcard { .uj-points-idcard {
display: flex; display: flex;
gap: 16px; gap: 12px;
flex-wrap: wrap; flex-wrap: wrap;
} }
.uj-points-idcard-item { .uj-points-idcard-item {
...@@ -150,7 +155,7 @@ ...@@ -150,7 +155,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
height: 120px; height: 96px;
border: 1px dashed var(--uj-border); border: 1px dashed var(--uj-border);
border-radius: 8px; border-radius: 8px;
color: var(--uj-text-3); color: var(--uj-text-3);
...@@ -165,15 +170,15 @@ ...@@ -165,15 +170,15 @@
background: var(--uj-surface); background: var(--uj-surface);
} }
.uj-points-detail > .uj-points-detail-grid { .uj-points-detail > .uj-points-detail-grid {
margin: 0 0 16px; margin: 0 0 12px;
} }
/* 失败原因单独一行:整段可读、可复制,不像其他字段那样截断。 */ /* 失败原因单独一行:整段可读、可复制,不像其他字段那样截断。 */
.uj-points-error-row { .uj-points-error-row {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
margin-bottom: 16px; margin-bottom: 12px;
padding: 8px 12px; padding: 6px 10px;
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: 8px; border-radius: 8px;
background: var(--uj-surface-2, var(--uj-surface)); background: var(--uj-surface-2, var(--uj-surface));
...@@ -238,3 +243,66 @@ ...@@ -238,3 +243,66 @@
padding: 12px 0; padding: 12px 0;
font-size: 12px; font-size: 12px;
} }
/* ============ 紧凑化:仅作用于 points 子应用,不改 @uj/ui / @uj/biz ============
子应用跑在 shadow root,以下用 .uj-points-app 作用域覆盖共享层的默认间距,
把页面整体收一档。共享令牌(圆角档、阴影、字号档、配色)保持不变。
改动只落在 points 目录的 page.css,packages 一行没动。 */
/* 页面骨架:整页与各区块之间的 gap,16 → 12。 */
.uj-points-app .uj-page {
gap: 12px;
}
/* 页头:标题块与右上角动作之间的 gap,20 → 12;标题降一档字号、收窄下边距。 */
.uj-points-app .uj-page__header {
gap: 12px;
}
.uj-points-app .uj-page__title {
margin-bottom: 4px;
font-size: 18px;
}
.uj-points-app .uj-page__desc {
line-height: 1.5;
}
/* 筛选卡:body padding 12/16 → 8/12;栅格列/行 gap 16/12 → 12/8;第二排分隔线间距 12 → 8。 */
.uj-points-app .uj-filter-card > .ant-card-body {
padding: 8px 12px;
}
.uj-points-app .uj-filter-grid {
column-gap: 12px;
row-gap: 8px;
}
.uj-points-app .uj-filter-more {
padding-top: 8px;
margin-top: 8px;
}
/* 表格:单元格内边距收到 8/12,字号降到 13px,整表更密更精致。
DataTable 默认 size=middle(antd 默认档比设计令牌高一档),这里用 CSS 收口,不碰共享组件。 */
.uj-points-app .ant-table {
font-size: 13px;
}
.uj-points-app .ant-table-thead > tr > th.ant-table-cell,
.uj-points-app .ant-table-tbody > tr > td.ant-table-cell {
padding: 8px 12px;
}
/* 工具条与分页:padding 12/20 → 8/16,内部 gap 12 → 8。 */
.uj-points-app .uj-table-toolbar {
gap: 8px;
padding: 8px 16px;
}
.uj-points-app .uj-table .ant-table-pagination.ant-pagination {
padding: 8px 16px;
}
/* 卡片圆角 12 → 8:在密集数据页里更利落、更精致(仅 points)。 */
.uj-points-app .uj-card {
border-radius: 8px;
}
/* 弹窗/抽屉里的表单项默认 24px,收到 16px;页面筛选区已内联 marginBottom:0 不受影响。 */
.uj-points-app .ant-form-item {
margin-bottom: 16px;
}
...@@ -4,6 +4,9 @@ import { BrowserRouter } from 'react-router-dom'; ...@@ -4,6 +4,9 @@ import { BrowserRouter } from 'react-router-dom';
import { App } from './App'; import { App } from './App';
import '@uj/design-tokens/tokens.css'; import '@uj/design-tokens/tokens.css';
import './index.css'; import './index.css';
// 本域特有样式(统计条 / 详情网格 / 标签树 / 身份证 / 协议 iframe / 失败原因行)。
// 之前漏引入,导致这些组件运行时完全无样式 —— 累计结算金额面板"乱的"根因在此。
import './features/shared/page.css';
let root: Root | null = null; let root: Root | null = null;
......
import { UButton, UCard, UModal } from '@uj/ui'; import { UButton, UModal } from '@uj/ui';
import type { SettleAmountMap } from '@/api'; import type { SettleAmountMap } from '@/api';
import { SETTLE_STATISTICS, SETTLE_STATISTICS_PREVIEW } from '@/features/shared/dictionaries'; import { SETTLE_STATISTICS, SETTLE_STATISTICS_PREVIEW } from '@/features/shared/dictionaries';
import { EMPTY } from '@/features/shared/format'; import { EMPTY } from '@/features/shared/format';
...@@ -29,7 +29,7 @@ export interface SettleAmountStripProps { ...@@ -29,7 +29,7 @@ export interface SettleAmountStripProps {
export function SettleAmountStrip({ amounts, onOpenAll }: SettleAmountStripProps) { export function SettleAmountStrip({ amounts, onOpenAll }: SettleAmountStripProps) {
const preview = itemsOf(amounts).slice(0, SETTLE_STATISTICS_PREVIEW); const preview = itemsOf(amounts).slice(0, SETTLE_STATISTICS_PREVIEW);
return ( return (
<UCard className="uj-points-statistics-card" size="small"> <div className="uj-points-statistics-card">
<div className="uj-points-statistics-head"> <div className="uj-points-statistics-head">
<span>累计结算金额</span> <span>累计结算金额</span>
<UButton type="link" onClick={onOpenAll}> <UButton type="link" onClick={onOpenAll}>
...@@ -47,7 +47,7 @@ export function SettleAmountStrip({ amounts, onOpenAll }: SettleAmountStripProps ...@@ -47,7 +47,7 @@ export function SettleAmountStrip({ amounts, onOpenAll }: SettleAmountStripProps
</div> </div>
))} ))}
</div> </div>
</UCard> </div>
); );
} }
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
"build:shell": "pnpm --filter @uj/web-shell build", "build:shell": "pnpm --filter @uj/web-shell build",
"build:system": "pnpm --filter @uj/web-system build", "build:system": "pnpm --filter @uj/web-system build",
"build:store": "pnpm --filter @uj/web-store build", "build:store": "pnpm --filter @uj/web-store build",
"build:npm": "pnpm mp",
"lint": "turbo run lint", "lint": "turbo run lint",
"lint:all": "eslint . --max-warnings=0", "lint:all": "eslint . --max-warnings=0",
"typecheck": "turbo run typecheck", "typecheck": "turbo run typecheck",
...@@ -40,6 +41,8 @@ ...@@ -40,6 +41,8 @@
"sync": "node scripts/sync-from-uj-store.mjs", "sync": "node scripts/sync-from-uj-store.mjs",
"gen:tsconfig": "node scripts/gen-tsconfig.mjs", "gen:tsconfig": "node scripts/gen-tsconfig.mjs",
"mp:sync": "node scripts/sync-mp-apps.mjs", "mp:sync": "node scripts/sync-mp-apps.mjs",
"mp": "node scripts/mp-npm.mjs",
"mp:check": "node scripts/mp-npm.mjs --check",
"verify": "node scripts/check-boundaries.mjs && node scripts/check-tokens.mjs && node scripts/reconcile.mjs && pnpm typecheck && pnpm test && pnpm lint && pnpm lint:all && pnpm format:check", "verify": "node scripts/check-boundaries.mjs && node scripts/check-tokens.mjs && node scripts/reconcile.mjs && pnpm typecheck && pnpm test && pnpm lint && pnpm lint:all && pnpm format:check",
"ci": "pnpm verify && pnpm build" "ci": "pnpm verify && pnpm build"
}, },
......
...@@ -6,23 +6,30 @@ ...@@ -6,23 +6,30 @@
"main": "./dist/index.cjs", "main": "./dist/index.cjs",
"module": "./dist/index.js", "module": "./dist/index.js",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"miniprogram": "./dist/index.cjs", "miniprogram": "miniprogram_dist",
"exports": { "exports": {
".": { ".": {
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"import": "./dist/index.js", "import": "./dist/index.js",
"require": "./dist/index.cjs", "require": "./dist/index.cjs",
"default": "./dist/index.cjs" "default": "./dist/index.cjs"
},
"./Request": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"default": "./dist/index.cjs"
} }
}, },
"files": [ "files": [
"dist" "dist",
"miniprogram_dist"
], ],
"scripts": { "scripts": {
"build": "tsup", "build": "tsup",
"dev": "tsup --watch", "dev": "tsup --watch",
"lint": "eslint . --max-warnings=0", "lint": "eslint . --max-warnings=0",
"test": "pnpm build && node --test test/sdkSign.test.mjs test/gsc.test.mjs", "test": "pnpm build && node --test test/sdkSign.test.mjs test/gsc.test.mjs test/rop.test.mjs test/request.test.mjs test/strategy.test.mjs test/clients.test.mjs",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"devDependencies": { "devDependencies": {
......
/**
* 子路径入口:`import Request from '@uj/api-core/Request'`。
*
* 注意:本文件只作为源码层面的可读入口 / 类型锚点;package.json 的 exports 把
* `"./Request"` 别名到与主入口**同一个 dist bundle**,因此 `Request` 类只有一份实例,
* 不会出现「两个入口拿到的类不相等」的坑(web 子应用若混用两种 import 也安全)。
*
* 与 `import { Request } from '@uj/api-core'` 完全等价。
*
* 适用范围:web(Vite)/ Node 支持 package.json exports 子路径;
* 原生微信小程序的「构建 npm」不保证解析 exports,四个 mp app 统一走主入口具名导出
* `import { createRopClient } from '@uj/api-core'`,拿到的是同一个门面、同一份策略表。
*/
export {
Request,
createRequest,
Defaults,
InterceptorManager,
RequestError,
strategies,
ropPreset,
gscPreset,
webHostPreset,
restPreset,
createRopClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
Request as default,
} from './index';
export type {
RequestConfig,
RequestTransport,
RequestProfile,
SignaturePreset,
BodySignFn,
SessionOptions,
ResponseOptions,
RequestEvents,
UiAdapter,
RetryOptions,
ErrorHandler,
Interceptor,
} from './index';
import { Request } from './facade';
import {
ropPreset,
gscPreset,
webHostPreset,
restPreset,
rpcGatewayPreset,
} from './strategies';
import type { RopPresetOptions, RpcGatewayPresetOptions } from './strategies';
import type { RequestConfig } from './facade';
/**
* 客户端工厂:消费层的默认入口,与 `createGscClient` 同构 ——
* 一个函数 + 一份配置,直接拿到可用的 client,不需要 `new`、不需要选策略、
* 不需要注册签名,也不用知道底下是 wx.request 还是 axios。
*
* ```js
* import { createRopClient } from '@uj/api-core'
* const api = createRopClient({
* hosts, pathEnum, secretKey,
* signature: sign, // 直接给函数,或给内置名 / 已注册的业务名
* session: { sessionId },
* loginReplay: true,
* })
* api.post('scrm.api.shopmall.order.list', { pageNo: 1 })
* ```
*
* 这里**不是另一套请求实现**:每个工厂只做 `new Request(<对应 preset>(options))`,
* 平台差异、URL 拼装、签名、拦截器仍然全部来自 `Request` 门面与
* 注册表里的 `RequestStrategy` / `SignatureStrategy`。`strategies.*` 与
* `createRequest(config)` 保留给「注册自定义策略 / 覆盖内置实现」这类高级用法。
*/
// 配置类型直接复用 strategies / facade 的既有定义(不再另起别名,避免与
// 第一代 rop.ts 的 RopClientOptions 同名),调用方拿到的类型提示完全一样。
/** ROP-router 网关:四个原生小程序共用的方案。 */
export function createRopClient(options: RopPresetOptions = {}): Request {
return new Request(ropPreset(options));
}
/** web 主壳:全项目唯一一份 HTTP 引擎,axios 只是 transport。 */
export function createWebHostClient(options: RequestConfig = {}): Request {
return new Request(webHostPreset(options));
}
/** 老系统 RPC 网关:业务侧只写 `request.post(method, params, { gateway })`。 */
export function createRpcGatewayClient(options: RpcGatewayPresetOptions): Request {
return new Request(rpcGatewayPreset(options));
}
/** 普通 REST:不带任何网关方案假设。 */
export function createRestClient(options: RequestConfig = {}): Request {
return new Request(restPreset(options));
}
/** GSC / glsk REST 网关(走统一门面;与老 `createGscClient` 适配器形态不同)。 */
export function createGscRestClient(options: RequestConfig = {}): Request {
return new Request(gscPreset(options));
}
import type { import type {
GatewayCredential, GatewayCredential,
NormalizedEnvelope, NormalizedEnvelope,
RawRequest,
RpcCall, RpcCall,
RequestSender, RequestSender,
} from './types'; } from './types';
...@@ -22,34 +23,32 @@ export function unwrapEnvelope(envelope: NormalizedEnvelope): unknown { ...@@ -22,34 +23,32 @@ export function unwrapEnvelope(envelope: NormalizedEnvelope): unknown {
throw new RpcError(envelope.code, envelope.message); throw new RpcError(envelope.code, envelope.message);
} }
export interface RpcDispatcherDeps { export interface RpcPrepareDeps {
/** 传输层:web 用主壳 axios(createHostSender),小程序用 wx.request,node 用 fetch。 */
sender: RequestSender;
/** 运行时凭据注入点:把密钥 / 域名留在本域,包不持有任何字面量。 */ /** 运行时凭据注入点:把密钥 / 域名留在本域,包不持有任何字面量。 */
resolveCredential: (id: string) => GatewayCredential; resolveCredential: (id: string) => GatewayCredential;
/** 会话令牌提供器(主壳登录态 / 网关侧令牌)。 */ /** 会话令牌提供器(主壳登录态 / 网关侧令牌);不传则不带令牌头。 */
resolveToken: () => string; resolveToken?: () => string;
/** 默认超时(毫秒);老系统 RPC 网关一般 180000。 */ /** 默认超时(毫秒);老系统 RPC 网关一般 180000。 */
timeout?: number; timeout?: number;
} }
export interface RpcDispatcherDeps extends Omit<RpcPrepareDeps, 'resolveToken'> {
/** 传输层:web 用主壳 axios(createHostSender),小程序用 wx.request,node 用 fetch。 */
sender: RequestSender;
/** 会话令牌提供器(主壳登录态 / 网关侧令牌)。 */
resolveToken: () => string;
}
/** /**
* 构造一个「业务语义」RPC 调用器。 * 把一次「业务语义」调用组装成原始传输请求(只组装,不发送)。
*
* 只决定三件事,绝不持有 transport:
* 1. 落点:绝对 URL(网关 origin + router);
* 2. 请求体:method 名与业务参数平铺,再并进该网关的加签字段;
* 3. 返回:策略的 normalize 把对方信封归一成 { data } / { code, message },再拆成业务数据。
* *
* 主壳那份唯一的签名 / 验签 / 401 登出链路不被触动:web 的 sender 把请求交回主壳 axios, * `createRpcDispatcher`(小程序直连)与 `strategies.rpcGateway`(统一 Request 门面)
* 原生小程序则自带 wx.request —— 同一套契约,传输层可换,且「请求层绝不下放」的约束仍然成立。 * 共用这一份实现:落点、fixedParams 合并、加签、令牌头、信封归一因此永远同源,
* 不再出现 web 与小程序各写一遍组装逻辑的情况。
*/ */
export function createRpcDispatcher(deps: RpcDispatcherDeps) { export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promise<RawRequest> {
const { sender, resolveCredential, resolveToken, timeout } = deps;
return async function rpcCall<T = unknown>(call: RpcCall): Promise<T> {
const strategy = resolveGateway(call.gateway); const strategy = resolveGateway(call.gateway);
const credential = resolveCredential(call.gateway); const credential = deps.resolveCredential(call.gateway);
const needsSign = call.signed !== false; const needsSign = call.signed !== false;
// 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;签名与请求体都基于这份有效参数。 // 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;签名与请求体都基于这份有效参数。
...@@ -60,11 +59,11 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) { ...@@ -60,11 +59,11 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) {
const body: Record<string, unknown> = { ...effectiveParams, method: call.method }; const body: Record<string, unknown> = { ...effectiveParams, method: call.method };
if (needsSign) { if (needsSign) {
if (!credential.secret) { if (!credential.secret) {
throw new Error( throw new Error(`网关 ${call.gateway} 的接口需要加签,但未配置 appKey / secret。`);
`网关 ${call.gateway} 的接口需要加签,但未配置 appKey / secret。`,
);
} }
const signFields = await Promise.resolve( Object.assign(
body,
await Promise.resolve(
strategy.signer.fields({ strategy.signer.fields({
method: call.method, method: call.method,
params: effectiveParams, params: effectiveParams,
...@@ -75,20 +74,36 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) { ...@@ -75,20 +74,36 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) {
format: credential.format, format: credential.format,
exclude: call.unsignedKeys, exclude: call.unsignedKeys,
}), }),
),
); );
Object.assign(body, signFields);
} }
const token = resolveToken(); const token = deps.resolveToken?.() ?? '';
return sender const origin = credential.origin.replace(/\/+$/, '');
.send({ return {
method: 'POST', method: 'POST',
url: `${credential.origin.replace(/\/+$/, '')}/${strategy.router}`, url: `${origin}/${strategy.router.replace(/^\/+/, '')}`,
data: body, data: body,
headers: token ? { [strategy.tokenHeader]: token } : {}, headers: token ? { [strategy.tokenHeader]: token } : {},
timeout, timeout: deps.timeout,
normalize: strategy.normalize, normalize: strategy.normalize,
}) };
}
/**
* 构造一个「业务语义」RPC 调用器(小程序直连场景)。
*
* 组装交给 prepareRpcCall,这里只负责发送与拆信封;transport 由外部注入。
* 主壳那份唯一的签名 / 验签 / 401 登出链路不被触动:web 侧请改用
* `strategies.rpcGateway` 走统一 Request 门面,它是同一个组装实现。
*/
export function createRpcDispatcher(deps: RpcDispatcherDeps) {
const { sender, resolveCredential, resolveToken, timeout } = deps;
return async function rpcCall<T = unknown>(call: RpcCall): Promise<T> {
const req = await prepareRpcCall(call, { resolveCredential, resolveToken, timeout });
return sender
.send(req)
.then((res) => unwrapEnvelope(res.data as NormalizedEnvelope) as T); .then((res) => unwrapEnvelope(res.data as NormalizedEnvelope) as T);
}; };
} }
import type { RequestConfig } from './facade';
/**
* 带上下文的请求异常。
*
* 独立成模块是为了让 strategies.ts 能抛它而不必运行时反向 import facade
* (facade 会 import strategies,循环依赖在 CJS 产物里会拿到 undefined)。
* facade 原样 re-export,对 `@uj/api-core` 的公开 API 没有变化。
*/
export class RequestError extends Error {
readonly isRequestError = true;
code?: string | number;
/** 业务失败信封里的 data 字段(web 老壳 `Object.assign(new Error(msg), { code, data })` 的语义)。 */
data?: unknown;
config?: RequestConfig;
response?: unknown;
cause?: unknown;
constructor(message: string, init: Partial<RequestError> = {}) {
super(message);
this.name = 'RequestError';
if (init.code !== undefined) this.code = init.code;
if (init.data !== undefined) this.data = init.data;
if (init.config !== undefined) this.config = init.config;
if (init.response !== undefined) this.response = init.response;
if (init.cause !== undefined) this.cause = init.cause;
}
}
...@@ -7,14 +7,15 @@ export type { ...@@ -7,14 +7,15 @@ export type {
RawRequest, RawRequest,
RawResponse, RawResponse,
RequestSender, RequestSender,
ResponseVerifier,
RpcCall, RpcCall,
Signer, Signer,
SignInput, SignInput,
} from './types'; } from './types';
export { registerGateway, resolveGateway } from './registry'; export { registerGateway, resolveGateway } from './registry';
export { createRpcDispatcher, unwrapEnvelope, RpcError } from './dispatcher'; export { createRpcDispatcher, prepareRpcCall, unwrapEnvelope, RpcError } from './dispatcher';
export type { RpcDispatcherDeps } from './dispatcher'; export type { RpcDispatcherDeps, RpcPrepareDeps } from './dispatcher';
// 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。 // 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。
export { export {
...@@ -67,3 +68,82 @@ export type { ...@@ -67,3 +68,82 @@ export type {
GscResponseData, GscResponseData,
GscSessionConfig, GscSessionConfig,
} from './gsc'; } from './gsc';
// 第一代 ROP 客户端:独立于统一门面,仅保留给离线钉值测试与旧 `request(opts)` 形状的脚本。
// 新代码请用下方「客户端工厂」里的 createRopClient(走统一 Request 门面 + rop 方案策略)。
export { createLegacyRopClient } from './rop';
export type {
RopClient,
RopClientOptions,
RopEvents,
RopHosts,
RopCredential,
RopResolveCredential,
RopRequestOptions,
RopUiAdapter,
RopLoadingAdapter,
} from './rop';
// 客户端工厂:消费层默认入口,一个 createXxxClient({配置}) 直接拿 client。
// 与 createGscClient 同构,但底层委托的仍是下面这套统一门面 + 策略注册表。
export {
createRopClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
} from './clients';
// 统一请求门面:抹平平台(auto/wx/uni/fetch/host)、签名、拦截器。
// 方案与签名都是注册表里的策略;注册自定义策略 / 覆盖内置实现时才需要直接碰它们。
// 同时提供 '@uj/api-core/Request' 子路径入口(src/Request.ts)。
export {
Request,
createRequest,
Defaults,
InterceptorManager,
RequestError,
} from './facade';
// 子路径 `@uj/api-core/Request` 别名到本 bundle,需在此提供默认导出。
export { Request as default } from './facade';
export {
defineRequestStrategy,
defineSignatureStrategy,
registerRequestStrategy,
registerSignatureStrategy,
resolveRequestStrategy,
resolveSignatureStrategy,
listRequestStrategies,
listSignatureStrategies,
strategies,
ropPreset,
gscPreset,
webHostPreset,
restPreset,
rpcGatewayPreset,
} from './strategies';
export type {
RequestStrategy,
RequestStrategySpec,
SignatureStrategy,
SignatureSpec,
PreparedRequest,
SessionValue,
RopPresetOptions,
RpcGatewayPresetOptions,
} from './strategies';
export type {
RequestConfig,
RequestTransport,
RequestProfile,
SignaturePreset,
BodySignFn,
SessionOptions,
ResponseOptions,
RequestEvents,
UiAdapter,
RetryOptions,
ErrorHandler,
Interceptor,
} from './facade';
...@@ -41,11 +41,13 @@ export function createHostSender(send: HostSendFn): RequestSender { ...@@ -41,11 +41,13 @@ export function createHostSender(send: HostSendFn): RequestSender {
headers: req.headers, headers: req.headers,
timeout: req.timeout, timeout: req.timeout,
withCredentials: true, withCredentials: true,
transformResponse: req.normalize responseType: req.responseType,
transformResponse: req.transformResponse
?? (req.normalize
? [req.normalize as (raw: unknown, headers: Record<string, string>) => unknown] ? [req.normalize as (raw: unknown, headers: Record<string, string>) => unknown]
: undefined, : undefined),
})) as { status?: number; data: unknown; headers?: Record<string, string> }; })) as { status?: number; data: unknown; headers?: Record<string, string> };
return { status: res?.status ?? 200, data: res?.data }; return { status: res?.status ?? 200, data: res?.data, headers: res?.headers };
}, },
}; };
} }
......
...@@ -65,6 +65,16 @@ export interface HeaderSignInput { ...@@ -65,6 +65,16 @@ export interface HeaderSignInput {
secret: string; secret: string;
/** 不参与签名原文的参数名;请求本身仍会带上它们 */ /** 不参与签名原文的参数名;请求本身仍会带上它们 */
exclude?: string[]; exclude?: string[];
/** 完整 URL(含 baseURL + context-path + query),供签名器解析出 path / query。 */
url?: string;
/** canonical 第 2 行:相对 baseURL 的路径(已含 context-path)。 */
path?: string;
/** canonical 第 3 行:查询串,与线上 URL 的 query 同源(同一份序列化结果)。 */
query?: string;
/** canonical 第 4 行:Content-Type 的媒体类型(multipart / application/json / 空)。 */
mediaType?: string;
/** canonical 第 8 行:请求体字符串(POST 的 JSON 体,或 FormData 时为空串)。 */
bodyString?: string;
} }
/** 头部签名策略:返回要并入请求头的字段。 */ /** 头部签名策略:返回要并入请求头的字段。 */
...@@ -112,14 +122,29 @@ export interface RawRequest { ...@@ -112,14 +122,29 @@ export interface RawRequest {
data?: unknown; data?: unknown;
headers?: Record<string, string>; headers?: Record<string, string>;
timeout?: number; timeout?: number;
/** blob / arraybuffer 下载透传(host 主壳 axios 的 responseType)。 */
responseType?: 'json' | 'blob' | 'arraybuffer' | 'text';
/** 传输层是否携带跨域凭证(web 主壳 axios 的 withCredentials;小程序忽略)。 */
withCredentials?: boolean;
/** host 主壳 axios 的 transformResponse 透传(自定义解包回调)。 */
transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>;
/** 传输层在拿到响应后、交给业务层前,先把对方信封归一成 NormalizedEnvelope。 */ /** 传输层在拿到响应后、交给业务层前,先把对方信封归一成 NormalizedEnvelope。 */
normalize?: (raw: unknown) => NormalizedEnvelope; normalize?: (raw: unknown) => NormalizedEnvelope;
} }
/**
* 响应验签钩子:传输层拿到原始响应后、门面做业务码归一前调用。
* 抛错即拒绝请求(可携带自定义 message / code)。web(RSA)用它做服务端响应签名校验;
* 无签名头或公钥未就绪时按策略跳过(宽松放行 / 严格拒绝),由签名器决定。
*/
export type ResponseVerifier = (raw: RawResponse) => void | Promise<void>;
/** 一次原始传输的响应。 */ /** 一次原始传输的响应。 */
export interface RawResponse { export interface RawResponse {
status: number; status: number;
data: unknown; data: unknown;
/** 响应头(RSA 验签需要从 X-Sign / X-Sign-Timestamp / X-Sign-Nonce 还原原文)。 */
headers?: Record<string, string>;
} }
/** /**
......
/**
* 客户端工厂层钉值测试。
*
* 关注两件事:
* 1. createXxxClient({配置}) 与 new Request(strategies.xxx({...})) 逐字节等价 ——
* 工厂只是装配形态,不是另一套请求实现;
* 2. 消费层装配点(四个小程序 + web 主壳 + web points)必须保持工厂形态,
* 不得再出现 new Request / strategies.* / 全局注册签名。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import test from 'node:test';
const require = createRequire(import.meta.url);
const core = require('../dist/index.cjs');
const {
Request,
createRequest,
strategies,
defineSignatureStrategy,
registerGateway,
createLegacyRopClient,
createRopClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
} = core;
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..', '..');
const HOSTS = { scrm: 'https://scrm.test.glsx.com.cn', dj: 'https://dj.test.glsx.com.cn' };
const CRED = { appKey: 'ak', secret: 'sk' };
const OK = { status: 200, data: { code: '0', message: 'ok', data: { ok: 1 } } };
function makeSender(responder) {
const calls = [];
const sender = {
async send(req) {
calls.push(req);
const res = typeof responder === 'function' ? responder(req) : responder;
return res ?? OK;
},
};
return { calls, sender };
}
/** 模拟 wx/host sender 执行 RawRequest.normalize(老网关信封在此归一)。 */
function makeEnvelopeSender() {
const calls = [];
const sender = {
async send(req) {
calls.push(req);
const raw = { code: '0', data: { id: 7 } };
return { status: 200, data: req.normalize ? req.normalize(raw) : raw, headers: {} };
},
};
return { calls, sender };
}
const inlineSign = async (params, secret) => ({ ...params, sign: `inline#${secret}` });
// ---------------------------------------------------------------------------
// 1. 工厂 == 策略装配
// ---------------------------------------------------------------------------
test('CT-FAC-001 createRopClient 与 strategies.rop 装配逐字节等价', async () => {
const a = makeSender();
const b = makeSender();
const options = {
hosts: HOSTS,
pathEnum: { shopmall: '/rop-scrm-shopmall/' },
defaultCredential: CRED,
signature: inlineSign,
session: { sessionId: () => 'sess-1' },
};
const viaFactory = createRopClient({ ...options, sender: a.sender });
const viaStrategies = createRequest(strategies.rop({ ...options, sender: b.sender }));
assert.ok(viaFactory instanceof Request);
assert.ok(viaStrategies instanceof Request);
await viaFactory.post('scrm.api.shopmall.order.list', { pageNo: 1 });
await viaStrategies.post('scrm.api.shopmall.order.list', { pageNo: 1 });
const pick = (req) => ({
url: req.url, method: req.method, data: req.data, headers: req.headers,
});
assert.deepEqual(pick(a.calls[0]), pick(b.calls[0]));
assert.equal(
a.calls[0].url,
'https://scrm.test.glsx.com.cn/rop-scrm-shopmall/router?method=scrm.api.shopmall.order.list',
);
assert.equal(a.calls[0].data.sign, 'inline#sk');
});
test('CT-FAC-002 signature 直接给函数即可生效,无需 strategies.signature.register', async () => {
const { calls, sender } = makeSender();
const api = createRopClient({ hosts: HOSTS, defaultCredential: CRED, signature: inlineSign, sender });
await api.post('scrm.api.shopmall.order.list', { p: 1 });
assert.equal(calls[0].data.sign, 'inline#sk');
assert.ok(calls[0].url.includes('router?method=scrm.api.shopmall.order.list'));
});
test('CT-FAC-003 内置签名名 / 签名策略实例同样可用', async () => {
const byName = makeSender();
const named = createRopClient({
hosts: HOSTS, defaultCredential: CRED, signature: 'rop-sha1', sender: byName.sender,
});
await named.post('scrm.api.shopmall.order.list', { p: 1 });
assert.ok(byName.calls[0].data.sign, '内置 rop-sha1 必须产出 sign');
const byInstance = makeSender();
const custom = defineSignatureStrategy('ct-inline', { bodySign: inlineSign });
const api = createRopClient({
hosts: HOSTS, defaultCredential: CRED, signature: custom, sender: byInstance.sender,
});
await api.post('scrm.api.shopmall.order.list', { p: 1 });
assert.equal(byInstance.calls[0].data.sign, 'inline#sk');
});
test('CT-FAC-004 五个工厂都返回同一个 Request 类', () => {
const clients = [
createRopClient({ hosts: HOSTS }),
createWebHostClient({}),
createRestClient({}),
createGscRestClient({}),
createRpcGatewayClient({
gatewayCredential: () => ({ origin: 'https://gw.test', appKey: 'ak', secret: 'sk' }),
}),
];
for (const client of clients) {
assert.ok(client instanceof Request);
assert.equal(typeof client.post, 'function');
assert.equal(typeof client.get, 'function');
}
});
test('CT-FAC-005 createWebHostClient 与 strategies.webHost 装配等价(自带信封语义)', async () => {
const responder = { status: 200, data: { code: 200, data: { id: 7 } } };
const a = makeSender(responder);
const b = makeSender(responder);
const options = { baseURL: 'https://api.test', contentType: false };
const viaFactory = createWebHostClient({ ...options, sender: a.sender });
const viaStrategies = createRequest(strategies.webHost({ ...options, sender: b.sender }));
const x = await viaFactory.post('/x', { a: 1 });
const y = await viaStrategies.post('/x', { a: 1 });
assert.deepEqual(x, y);
// webHost 方案保留完整 ApiResult 信封 + headers(主壳 axios 形状适配层要用),不解包。
assert.equal(x.data.code, 200);
assert.deepEqual(x.data.data, { id: 7 });
});
test('CT-FAC-006 createRpcGatewayClient 业务侧只传 gateway', async () => {
registerGateway({
id: 'ct-rpc',
router: 'rop-ct/router',
tokenHeader: 'token',
fixedParams: { locale: 'zh_CN' },
signer: {
id: 'ct-signer',
fields: (input) => ({ appKey: input.appKey, sign: 'S' }),
},
normalize: (raw) => (String(raw.code) === '0' ? { data: raw.data } : { code: 500, message: 'bad' }),
});
const { calls, sender } = makeEnvelopeSender();
const api = createRpcGatewayClient({
sender,
gatewayCredential: () => ({ origin: 'https://gw.test', appKey: 'ak', secret: 'sk' }),
gatewayToken: () => 'tk-1',
});
const data = await api.post('scrm.api.shopmall.order.list', { pageNo: 1 }, { gateway: 'ct-rpc' });
assert.deepEqual(data, { id: 7 });
assert.equal(calls[0].url, 'https://gw.test/rop-ct/router');
assert.equal(calls[0].data.sign, 'S');
assert.equal(calls[0].data.locale, 'zh_CN');
assert.equal(calls[0].headers.token, 'tk-1');
});
test('CT-FAC-007 第一代 ROP 客户端与工厂分离,且子路径导出同一批工厂', () => {
assert.equal(typeof createLegacyRopClient, 'function');
assert.notEqual(core.createRopClient, createLegacyRopClient);
// './Request' 别名到同一 bundle,工厂因此也只有一个实例。
const pkg = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8'));
assert.equal(pkg.exports['./Request'].require, './dist/index.cjs');
assert.equal(typeof core.createRpcGatewayClient, 'function');
});
// ---------------------------------------------------------------------------
// 2. 消费层装配形态闸门
// ---------------------------------------------------------------------------
const ASSEMBLY_POINTS = [
'apps/mp/sales/utils/request/request.js',
'apps/mp/store/utils/request/request.js',
'apps/mp/usedcar/utils/request/request.js',
'apps/mp/points/api/request/http.js',
'packages/platform-core/src/api/core/http.ts',
'apps/web/subapps/points/src/adapter/rpc.ts',
// newRequest.js 这一族同样是「一个工厂 + 一份配置」的形态,钉住不许退化。
'apps/mp/store/utils/request/newRequest.js',
'apps/mp/usedcar/packageUsedCar/newRequest.js',
];
test('CT-FAC-008 所有装配点只用工厂,不再出现 new Request / strategies / 注册签名', () => {
for (const rel of ASSEMBLY_POINTS) {
const src = readFileSync(path.join(ROOT, rel), 'utf8');
assert.ok(!src.includes('new Request('), `${rel} 不应再直接 new Request`);
assert.ok(!/strategies\.(rop|gsc|webHost|rest|rpcGateway)\(/.test(src), `${rel} 不应再选策略`);
assert.ok(!src.includes('signature.register('), `${rel} 不应再全局注册签名`);
assert.ok(/create\w+Client\(\s*\{/.test(src), `${rel} 必须用一个 createXxxClient({配置}) 装配`);
}
});
...@@ -11,13 +11,50 @@ import { defineConfig } from 'tsup'; ...@@ -11,13 +11,50 @@ import { defineConfig } from 'tsup';
* - external: ['@uj/contracts'] —— HttpMethod 是 type-only 导入,运行期零耦合; * - external: ['@uj/contracts'] —— HttpMethod 是 type-only 导入,运行期零耦合;
* 显式 external 让 dts 仅保留类型引用,不把 workspace 包打进 bundle。 * 显式 external 让 dts 仅保留类型引用,不把 workspace 包打进 bundle。
* - 本包零运行时依赖,bundle 完全自包含。 * - 本包零运行时依赖,bundle 完全自包含。
*
* 【为什么还要第二份 miniprogram_dist】
* 微信开发者工具的 packnpm.js 里 `checkIsMiniprogramPack()` 只认 `miniprogram`
* 字段指向**目录**的情况(statSync(dir).isDirectory() 通过才走整目录拷贝):
*
* let a = 'miniprogram_dist'
* if (pkg.miniprogram) a = pkg.miniprogram
* statSync(join(pkgDir, a)).isDirectory() ? 拷贝该目录 : 走 packJs() 兜底
*
* 曾把 miniprogram 指到 ./dist/index.cjs(一个文件),检查必然失败,于是掉进
* packJs() 兜底分支——那个分支按 require 静态分析重打一遍,打不动我们的 bundle
* 就 `continue` 静默跳过。结果 miniprogram_npm 里根本没有 @uj/api-core,
* 小程序首屏 require('@uj/api-core') 报 module is not defined(白屏)。
*
* 因此:dist/ 服务 node / web;miniprogram_dist/ 是喂给「构建 npm」的目录形态,
* 里面必须是 index.js(小程序 require('@uj/api-core') 解析到它),所以用
* outExtension 把 cjs 产物落成 .js。不开 sourcemap:整目录会被拷进
* miniprogram_npm,.map 白占主包体积。
*/ */
export default defineConfig({ const shared = {
entry: ['src/index.ts'], entry: ['src/index.ts'],
target: 'es2018',
external: ['@uj/contracts'],
} as const;
export default defineConfig([
{
...shared,
// 只打一个自包含 bundle:子路径 `@uj/api-core/Request` 在 package.json 里别名到同一产物,
// 保证 Request 类全局唯一(多入口会各自内联一份,导致 instanceof / 引用比较失效)。
format: ['cjs', 'esm'], format: ['cjs', 'esm'],
dts: true, dts: true,
clean: true, clean: true,
target: 'es2018',
sourcemap: true, sourcemap: true,
external: ['@uj/contracts'], outDir: 'dist',
}); },
{
...shared,
// 小程序专用:单文件 CJS,文件名 index.js,无 dts / 无 map。
format: ['cjs'],
dts: false,
clean: true,
sourcemap: false,
outDir: 'miniprogram_dist',
outExtension: () => ({ js: '.js' }),
},
]);
...@@ -9,10 +9,11 @@ ...@@ -9,10 +9,11 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "catalog:",
"@uj/api-core": "workspace:^0.0.0",
"@uj/contracts": "workspace:*", "@uj/contracts": "workspace:*",
"@uj/design-tokens": "workspace:*", "@uj/design-tokens": "workspace:*",
"@uj/ui": "workspace:*", "@uj/ui": "workspace:*",
"@tanstack/react-query": "catalog:",
"antd": "catalog:", "antd": "catalog:",
"axios": "catalog:", "axios": "catalog:",
"jsrsasign": "catalog:", "jsrsasign": "catalog:",
......
// 可注入 @uj/api-core 统一门面的 RSA 签名 / 验签策略。
//
// 原先 RSA 加签写在 host axios 请求拦截器、验签写在响应拦截器,属于「web 特例引擎」。
// 现在抽成两个纯函数:createRsaHeaderSigner 产出 5 个签名头(X-App-Id / X-Timestamp /
// X-Nonce / X-Sign / X-Sign-Algorithm),createRsaResponseVerifier 做响应验签。两者都只是
// @uj/api-core 的 HeaderSigner / ResponseVerifier 契约实现,与原生小程序的 sha1/md5 策略地位
// 完全对等——web 与小程序因此共用同一个 `Request` 门面,差异只是「装配时传了哪份签名策略」。
// http.ts 用 defineSignatureStrategy('rsa', { headerSigner: signer }) 直接传给
// createWebHostClient,不需要全局注册,也不存在 web 特例引擎。
//
// 签名原文(canonical)与加签/验签算法全部复用 sign.ts / signCanonical.ts 的既有实现,
// 保证与后端逐字节一致(避免 10011 / 验签失败)。
import type { HeaderSigner, RawResponse, ResponseVerifier } from '@uj/api-core';
import {
ALGORITHM,
APP_ID,
isSignReady,
isVerifyReady,
rsaSign,
rsaVerify,
uuid,
} from './sign';
import { buildSignCanonical } from './signCanonical';
export interface RsaHeaderSignerOptions {
/** 应用标识(须在服务端 app-ids 白名单内)。 */
appId?: string;
/** 签名算法,默认 SHA256withRSA。 */
algorithm?: string;
/** 关闭请求加签(开发期借后端宽松模式直接放行)。默认 true。 */
enabled?: boolean;
}
/**
* RSA 头部签名器:构造 8 行 canonical 并用客户端私钥加签,产出 5 个签名头。
* 入参里的 path / query / mediaType / bodyString 由门面 preparePlain 统一算出,
* 且与线上 URL 同源(同一份 query),故「线上发什么 == 签名算什么」。
*/
export function createRsaHeaderSigner(options: RsaHeaderSignerOptions = {}): HeaderSigner {
const appId = options.appId ?? APP_ID;
const algorithm = options.algorithm ?? ALGORITHM;
return {
id: 'rsa-sha256',
headers(input) {
const empty: Record<string, string> = {};
if (options.enabled === false || !isSignReady()) return empty;
const method = (input.method || 'GET').toUpperCase();
const timestamp = String(Date.now());
const nonce = uuid();
const canonical = buildSignCanonical({
method,
path: input.path ?? '',
query: input.query ?? '',
media: input.mediaType ?? '',
timestamp,
nonce,
appId,
body: input.bodyString ?? '',
});
const signValue = rsaSign(canonical);
return {
'X-App-Id': appId,
'X-Timestamp': timestamp,
'X-Nonce': nonce,
'X-Sign': signValue,
'X-Sign-Algorithm': algorithm,
};
},
};
}
export interface RsaResponseVerifierOptions {
/** 严格模式:响应声称已签名却无法验签时直接拒绝;默认 false(宽松,仅告警放行)。 */
strict?: boolean;
/** 关闭响应验签。默认 true。 */
enabled?: boolean;
}
/**
* RSA 响应验签器:用服务端公钥校验 X-Sign。
* 跳过条件与老拦截器一致:非 JSON 响应(模板下载 / 导出 blob,服务端不签名)、
* 无签名头(引导接口 / 未启用)、公钥未就绪(宽松模式放行)。
*/
export function createRsaResponseVerifier(options: RsaResponseVerifierOptions = {}): ResponseVerifier {
const strict = options.strict ?? false;
return (raw: RawResponse) => {
if (options.enabled === false) return;
const headers = raw.headers ?? {};
const get = (k: string): string | undefined =>
(headers[k] ?? headers[k.toLowerCase()] ?? headers[k.toUpperCase()]) as string | undefined;
const ct = String(get('content-type') ?? '');
// 二进制 / 文件流:服务端不签名,直接放行(§4.3)。
if (!ct.includes('application/json')) return;
const sign = get('x-sign');
if (!sign) return; // 无签名头(引导接口 / 未启用验签)→ 放行
const ts = get('x-sign-timestamp') ?? get('x-timestamp');
const nonce = get('x-sign-nonce') ?? get('x-nonce');
if (!ts || !nonce) {
if (strict) throw new Error('响应缺少签名时间戳/随机串,无法验签');
console.warn('[sign] 响应带签名但缺少时间戳/随机串,已跳过验签');
return;
}
if (!isVerifyReady()) {
if (strict) throw new Error('未加载服务端公钥,无法验签');
console.warn('[sign] 未加载服务端公钥,已跳过响应验签');
return;
}
// 待验签原文:3 行 \n 连接,末尾保留一个换行(§3.2)。原始响应体为字符串,需原样传入。
const rawBody = typeof raw.data === 'string' ? raw.data : JSON.stringify(raw.data ?? '');
const canonical = [ts, nonce, rawBody, ''].join('\n');
if (!rsaVerify(canonical, String(sign))) {
throw new Error('响应签名校验失败,数据可能被篡改');
}
};
}
...@@ -673,6 +673,9 @@ importers: ...@@ -673,6 +673,9 @@ importers:
'@tanstack/react-query': '@tanstack/react-query':
specifier: 'catalog:' specifier: 'catalog:'
version: 5.106.1(@types/react@19.3.0)(react@19.3.1) version: 5.106.1(@types/react@19.3.0)(react@19.3.1)
'@uj/api-core':
specifier: workspace:^0.0.0
version: link:../api-core
'@uj/contracts': '@uj/contracts':
specifier: workspace:* specifier: workspace:*
version: link:../contracts version: link:../contracts
......
#!/usr/bin/env node
/**
* mp 小程序「构建 npm」全量入口:遍历 apps/mp/manifest.json 里所有 lane。
*
* 日常只改了一个小程序时,别用这个 —— 进那个 lane 目录跑它自己的 mp-npm.mjs,
* 谁改谁跑、失败互不牵连。本命令用于「一次把全仓 mp 环境准备好」或 CI 自检。
*
* 用法:
* pnpm mp # 全部 lane:准备 + 构建(服务端口可用时)+ 体检
* pnpm mp:check # 只体检,不动任何文件
* pnpm mp --lane usedcar # 只处理指定 lane(可逗号分隔)
* pnpm mp --no-build # 跳过 api-core 构建(确定产物是新的)
* pnpm mp --verbose # 透出子进程输出
*
* 退出码:0 全绿;1 有缺失(缺产物 / 未构建)。
*/
import { listLanes, parseArgs, runLanes } from './mp-npm-core.mjs';
const opts = parseArgs();
const lanes = opts.lanes.length ? opts.lanes : listLanes();
const { ok } = await runLanes(lanes, opts);
process.exit(ok ? 0 : 1);
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!