bjchy-udg-sdk 1.0.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -97,7 +97,7 @@ const { status, token } = await client.checkScanLogin(sessionId)
97
97
 
98
98
  envId / mongoDatabase / AppSecret 由服务端从 `wxdb.config` 读取,客户端不传、不可传。
99
99
 
100
- **同一 appid 多数据源**(一个 client、一份 token,用 `dbKey` 切换;管理后台按 `databases[]` 登记,详见 `docs/multi-database-dbkey.md`):
100
+ **同一 appid 多数据源**(一个 client、一份 token,用 `dbKey` 切换;管理后台里租户的 `bindings[]` 把 `dbKey` 路由到数据源注册中心里的某个数据源,详见 `docs/datasource-registry-and-schema-dictionary.md`;`dbKey` 路由思路的历史版本见 `docs/archive/multi-database-dbkey.md`):
101
101
 
102
102
  ```js
103
103
  const client = udg.init({ endpoint, appid })
@@ -174,7 +174,7 @@ const { list } = await db.collection('orders').aggregate()
174
174
 
175
175
  返回兼容微信云开发:`get → {data}`、`count → {total}`、`aggregate → {list}`、`add → {_id}/{ids}`、`update → {stats:{updated}}`、`remove → {stats:{removed}}`。
176
176
 
177
- 失败抛统一错误对象:`{ errorCode, errorMessage, requestId, timestamp }`(如 `UNSUPPORTED_OPERATOR`、`TENANT_NOT_FOUND`、`DB_NOT_FOUND`(dbKey 未在 databases[] 中登记)、`READONLY_DATABASE`(对只读 dbKey 执行了写操作)、`FORBIDDEN`(Token 无效/过期,会自动 refresh 重试)、`TIMEOUT`)。
177
+ 失败抛统一错误对象:`{ errorCode, errorMessage, requestId, timestamp }`(如 `UNSUPPORTED_OPERATOR`、`TENANT_NOT_FOUND`、`DB_NOT_FOUND`(dbKey 未在租户 bindings[] 中登记)、`READONLY_DATABASE`(对只读 dbKey 执行了写操作)、`FORBIDDEN`(Token 无效/过期,会自动 refresh 重试)、`TIMEOUT`)。
178
178
 
179
179
  ## 说明
180
180
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bjchy-udg-sdk",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "description": "Universal Data Gateway SDK - 跨端统一数据访问(微信小程序 / Web / Node.js),API 兼容微信云开发",
5
5
  "main": "src/index.js",
6
6
  "type": "commonjs",
package/src/ai.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * client.ai.*(AI-4.1):租户级 AI 能力,走 Gateway /api/ai/*(JWT 鉴权 + 租户配额)。
3
+ * 需管理员在租户配置中开启 aiEnabled;purpose 仅限 Gateway 预注册模板(防 prompt 注入)。
4
+ */
5
+ const { post } = require('./request')
6
+
7
+ class AiNamespace {
8
+ constructor(ctx) {
9
+ this._ctx = ctx
10
+ }
11
+
12
+ /**
13
+ * 模板化补全。
14
+ * @param {object} p { purpose: 'summarize'|'explain'|'classify', prompt?|messages?, json? }
15
+ * @returns {Promise<{text?, json?, usage}>}
16
+ */
17
+ complete(p) {
18
+ const o = p || {}
19
+ return post(this._ctx, '/api/ai/complete', {
20
+ purpose: o.purpose,
21
+ prompt: o.prompt,
22
+ messages: o.messages,
23
+ json: o.json
24
+ })
25
+ }
26
+
27
+ /**
28
+ * 自然语言问数(只读,自动执行)。
29
+ * @param {object} p { collection, question, db? }
30
+ * @returns {Promise<{plan, validation, data, summary, copyable}>}
31
+ */
32
+ nlQuery(p) {
33
+ const o = p || {}
34
+ return post(this._ctx, '/api/ai/nl-query', {
35
+ db: o.db,
36
+ collection: o.collection,
37
+ question: o.question
38
+ })
39
+ }
40
+
41
+ /**
42
+ * 一行问数:内部 nlQuery + 结果解析。
43
+ * @param {string} question 中文问题
44
+ * @param {object} opts { collection(必填), db?, format?: 'number'|'rows'|'summary'(默认 summary) }
45
+ * @returns {Promise<number|Array|string>} format=number 时尽力解析出单个数字
46
+ */
47
+ async ask(question, opts) {
48
+ const o = opts || {}
49
+ const r = await this.nlQuery({ collection: o.collection, db: o.db, question })
50
+ const data = r.data || {}
51
+ if (o.format === 'number') {
52
+ if (typeof data.total === 'number') return data.total
53
+ const rows = data.list || data.data || []
54
+ if (rows.length === 1) {
55
+ const nums = Object.values(rows[0]).filter((v) => typeof v === 'number')
56
+ if (nums.length === 1) return nums[0]
57
+ }
58
+ throw new Error('无法从结果中解析出单个数字,请改用 format:"rows" 查看原始结果')
59
+ }
60
+ if (o.format === 'rows') return data.list || data.data || []
61
+ return r.summary || ''
62
+ }
63
+ }
64
+
65
+ module.exports = { AiNamespace }
package/src/collection.js CHANGED
@@ -9,7 +9,7 @@
9
9
  const { post } = require('./request')
10
10
  const { Aggregate } = require('./aggregate')
11
11
  const { UPDATE_OP_KEYS } = require('./command')
12
- const { isPlainObject } = require('./serialize')
12
+ const { isPlainObject, encode } = require('./serialize')
13
13
 
14
14
  /** 原生 JS RegExp → { $regex, $options }(兼容 wx.cloud 中直接写正则的用法) */
15
15
  function normalizeFilter(value) {
@@ -115,6 +115,41 @@ class Query {
115
115
  return { total: data.total || 0, errMsg: 'collection.count:ok' }
116
116
  }
117
117
 
118
+ /**
119
+ * 实时订阅(B2 SSE):数据变化时 Gateway 主动推送,兼容微信云开发 watch 概念。
120
+ * db.collection('logs').where({ status: 'waiting' }).watch({ onChange, onError })
121
+ * 事件覆盖:经 Gateway 的全部写入(四类数据源);外部直连写入在 mongodb / cloudbase 上由
122
+ * 原生监听补充(onChange 首个 watch-status 事件的 external 字段指示:active | degraded | unsupported)。
123
+ * 环境:浏览器 EventSource / Node >= 18;微信小程序不支持(抛错,请轮询)。
124
+ * @param {object} p { onChange(event), onError(err), fields?: ['a','b'] 推送字段白名单 }
125
+ * @returns {{ close: Function }}
126
+ */
127
+ watch({ onChange, onError, fields } = {}) {
128
+ if (typeof onChange !== 'function') {
129
+ throw new Error('watch 需要 onChange 回调')
130
+ }
131
+ const { connectSSE } = require('./sse')
132
+ const ctx = this._ctx
133
+ const token = ctx.auth ? ctx.auth.token : ''
134
+ const base = ctx.endpoint.replace(/\/+$/, '')
135
+ const params = new URLSearchParams({ appid: ctx.appid, collection: this._collection })
136
+ if (this._db) params.set('db', this._db)
137
+ const filter = this._state.filter
138
+ if (filter && Object.keys(filter).length > 0) params.set('filter', JSON.stringify(encode(filter)))
139
+ if (Array.isArray(fields) && fields.length > 0) params.set('fields', fields.join(','))
140
+ if (token) params.set('access_token', token)
141
+ return connectSSE(`${base}/api/subscribe?${params.toString()}`, {
142
+ events: ['change', 'ready', 'watch-status'],
143
+ onEvent: ({ event, data }) => {
144
+ if (event === 'change') onChange(data)
145
+ else if (event === 'watch-status' && typeof onChange === 'function') {
146
+ onChange({ type: 'watch-status', external: data && data.external })
147
+ }
148
+ },
149
+ onError: onError || ((err) => console.error('[udg-sdk] watch 连接错误:', err.errorMessage || err.message))
150
+ })
151
+ }
152
+
118
153
  async update(options) {
119
154
  const data = await post(this._ctx, '/api/update', {
120
155
  collection: this._collection,
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ const { Database } = require('./database')
21
21
  const { command, UdgRegExp } = require('./command')
22
22
  const { rawPost, postAuthed, UdgRequestError } = require('./request')
23
23
  const { AuthManager } = require('./auth')
24
+ const { AiNamespace } = require('./ai')
24
25
  const storage = require('./storage')
25
26
 
26
27
  function genSessionId() {
@@ -85,6 +86,8 @@ class UdgClient {
85
86
  // 外部 token 直入(与现有 JWT 体系互通)
86
87
  this._ctx.auth.setExternalToken(o.token)
87
88
  }
89
+ // AI 能力(AI-4.1,可选模块):client.ai.complete / nlQuery / ask;租户需开通 aiEnabled
90
+ this.ai = new AiNamespace(this._ctx)
88
91
  }
89
92
 
90
93
  /**
@@ -191,6 +194,75 @@ class UdgClient {
191
194
  }
192
195
  }
193
196
 
197
+ /**
198
+ * 实时扫码登录(B2 SSE,取代轮询):Gateway 推送状态变化,扫码确认后亚秒级返回。
199
+ * SSE 不可用(小程序 / 老浏览器 / 网络设备拦截)时自动降级为 pollScanLogin 轮询。
200
+ * @param {string} sessionId createScanSession 返回的 id
201
+ * @param {object} opts { timeout=300000, onStatus(status), viaStreetKey?, noFallback? }
202
+ * @returns {Promise<{token, refreshToken, userInfo}>} 语义与 pollScanLogin 一致
203
+ */
204
+ async subscribeScanLogin(sessionId, opts) {
205
+ await ensureAppid(this._ctx)
206
+ const o = opts || {}
207
+ const timeout = o.timeout || 5 * 60 * 1000
208
+ const { connectSSE } = require('./sse')
209
+ const base = this._ctx.endpoint.replace(/\/+$/, '')
210
+ const params = new URLSearchParams({ id: sessionId, appid: this._ctx.appid })
211
+ if (o.viaStreetKey) params.set('viaStreetKey', o.viaStreetKey)
212
+ const url = `${base}/auth/scan/subscribe?${params.toString()}`
213
+
214
+ const fallback = () =>
215
+ this.pollScanLogin(sessionId, { timeout, onStatus: o.onStatus, viaStreetKey: o.viaStreetKey })
216
+
217
+ return new Promise((resolve, reject) => {
218
+ let settled = false
219
+ let conn = null
220
+ const settle = (fn, val) => {
221
+ if (settled) return
222
+ settled = true
223
+ clearTimeout(timer)
224
+ if (conn) conn.close()
225
+ fn(val)
226
+ }
227
+ const degrade = () => {
228
+ if (settled) return
229
+ settled = true
230
+ clearTimeout(timer)
231
+ if (conn) conn.close()
232
+ if (o.noFallback) {
233
+ reject(new UdgRequestError({ errorCode: 'SSE_UNAVAILABLE', errorMessage: 'SSE 订阅不可用' }))
234
+ } else {
235
+ fallback().then(resolve, reject)
236
+ }
237
+ }
238
+ const timer = setTimeout(() => {
239
+ settle(reject, new UdgRequestError({ errorCode: 'SCAN_TIMEOUT', errorMessage: '扫码登录等待超时' }))
240
+ }, timeout)
241
+ if (timer.unref) timer.unref()
242
+
243
+ try {
244
+ conn = connectSSE(url, {
245
+ events: ['status'],
246
+ onEvent: ({ event, data }) => {
247
+ if (event !== 'status' || !data || typeof data !== 'object') return
248
+ if (typeof o.onStatus === 'function') o.onStatus(data.status)
249
+ if (data.status === 'confirmed') {
250
+ this._ctx.auth.setTokens(data.token, data.refreshToken, 'scan')
251
+ settle(resolve, { token: data.token, refreshToken: data.refreshToken, userInfo: data.userInfo })
252
+ } else if (data.status === 'expired') {
253
+ settle(reject, new UdgRequestError({ errorCode: 'SCAN_EXPIRED', errorMessage: '扫码会话已过期,请重新生成二维码' }))
254
+ } else if (data.status === 'error') {
255
+ degrade()
256
+ }
257
+ },
258
+ onError: degrade
259
+ })
260
+ } catch (err) {
261
+ degrade()
262
+ }
263
+ })
264
+ }
265
+
194
266
  /**
195
267
  * 单次调用扫码状态检查(不轮询,与 pollScanLogin 不同)。
196
268
  * confirmed 时与 pollScanLogin 一致,自动保存 token。
package/src/sse.js ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * 轻量 SSE 客户端(B2 订阅用):
3
+ * - 浏览器:原生 EventSource(自动重连 + 自动带 Last-Event-ID)
4
+ * - Node >= 18:fetch 流式读取 + 手动解析(断线回调 onError,由调用方决定重试/降级)
5
+ * - 微信小程序:不支持(抛 ENV_NOT_SUPPORTED,调用方降级为轮询)
6
+ */
7
+ const { UdgRequestError } = require('./request')
8
+
9
+ function isMiniProgram() {
10
+ // eslint-disable-next-line no-undef
11
+ return typeof wx !== 'undefined' && wx !== null && typeof wx.request === 'function'
12
+ }
13
+
14
+ /** 解析一段 SSE 帧文本 → { id, event, data } */
15
+ function parseFrame(frame) {
16
+ const out = { id: undefined, event: 'message', data: '' }
17
+ const dataLines = []
18
+ for (const line of frame.split('\n')) {
19
+ if (line.startsWith(':')) continue // 注释/心跳
20
+ const idx = line.indexOf(':')
21
+ if (idx < 0) continue
22
+ const field = line.slice(0, idx)
23
+ const value = line.slice(idx + 1).replace(/^ /, '')
24
+ if (field === 'id') out.id = value
25
+ else if (field === 'event') out.event = value
26
+ else if (field === 'data') dataLines.push(value)
27
+ }
28
+ out.data = dataLines.join('\n')
29
+ return out
30
+ }
31
+
32
+ function connectViaEventSource(url, { onEvent, onError, events }) {
33
+ // eslint-disable-next-line no-undef
34
+ const es = new EventSource(url)
35
+ const handler = (evtName) => (e) => {
36
+ let data = null
37
+ try { data = JSON.parse(e.data) } catch (_) { data = e.data }
38
+ onEvent({ id: e.lastEventId, event: evtName, data })
39
+ }
40
+ for (const name of events) es.addEventListener(name, handler(name))
41
+ es.onerror = () => {
42
+ // EventSource 自带重连;只有 CLOSED 才视为终止
43
+ if (es.readyState === 2 && onError) {
44
+ onError(new UdgRequestError({ errorCode: 'SSE_CLOSED', errorMessage: 'SSE 连接已关闭' }))
45
+ }
46
+ }
47
+ return { close: () => es.close() }
48
+ }
49
+
50
+ function connectViaFetch(url, { onEvent, onError }) {
51
+ const controller = new AbortController()
52
+ let closed = false
53
+ ;(async () => {
54
+ try {
55
+ const res = await fetch(url, {
56
+ headers: { Accept: 'text/event-stream' },
57
+ signal: controller.signal
58
+ })
59
+ if (!res.ok || !res.body) {
60
+ let payload = null
61
+ try { payload = await res.json() } catch (_) { /* 非 JSON */ }
62
+ throw new UdgRequestError(payload || { errorCode: 'HTTP_' + res.status, errorMessage: 'SSE 连接失败(HTTP ' + res.status + ')' }, res.status)
63
+ }
64
+ const reader = res.body.getReader()
65
+ const decoder = new TextDecoder()
66
+ let buffer = ''
67
+ for (;;) {
68
+ const { done, value } = await reader.read()
69
+ if (done) break
70
+ buffer += decoder.decode(value, { stream: true })
71
+ let idx
72
+ while ((idx = buffer.indexOf('\n\n')) >= 0) {
73
+ const frame = buffer.slice(0, idx)
74
+ buffer = buffer.slice(idx + 2)
75
+ if (!frame.trim() || frame.trim().startsWith(':')) continue
76
+ const parsed = parseFrame(frame)
77
+ if (parsed.data === '' && parsed.event === 'message') continue
78
+ let data = null
79
+ try { data = JSON.parse(parsed.data) } catch (_) { data = parsed.data }
80
+ onEvent({ id: parsed.id, event: parsed.event, data })
81
+ }
82
+ }
83
+ if (!closed && onError) {
84
+ onError(new UdgRequestError({ errorCode: 'SSE_CLOSED', errorMessage: 'SSE 连接被服务端关闭' }))
85
+ }
86
+ } catch (err) {
87
+ if (closed || (err && err.name === 'AbortError')) return
88
+ if (onError) {
89
+ onError(err instanceof UdgRequestError ? err : new UdgRequestError({ errorCode: 'NETWORK_ERROR', errorMessage: err.message || 'SSE 网络错误' }))
90
+ }
91
+ }
92
+ })()
93
+ return {
94
+ close: () => {
95
+ closed = true
96
+ controller.abort()
97
+ }
98
+ }
99
+ }
100
+
101
+ /**
102
+ * @param {string} url 完整 SSE URL(token 走查询参数)
103
+ * @param {object} p { onEvent({id,event,data}), onError(err), events: ['change',...] 监听的事件名 }
104
+ * @returns {{ close: Function }}
105
+ */
106
+ function connectSSE(url, { onEvent, onError, events = ['change', 'status', 'ready', 'watch-status'] }) {
107
+ if (isMiniProgram()) {
108
+ throw new UdgRequestError({
109
+ errorCode: 'ENV_NOT_SUPPORTED',
110
+ errorMessage: '微信小程序环境不支持 SSE 订阅,请使用轮询(pollScanLogin / 定时 get)'
111
+ })
112
+ }
113
+ // eslint-disable-next-line no-undef
114
+ if (typeof EventSource === 'function') {
115
+ return connectViaEventSource(url, { onEvent, onError, events })
116
+ }
117
+ if (typeof fetch === 'function') {
118
+ return connectViaFetch(url, { onEvent, onError })
119
+ }
120
+ throw new UdgRequestError({ errorCode: 'ENV_NOT_SUPPORTED', errorMessage: '当前环境不支持 SSE(需浏览器 EventSource 或 Node >= 18)' })
121
+ }
122
+
123
+ module.exports = { connectSSE }