gbflowengine 0.1.0 → 0.1.1

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.
Files changed (79) hide show
  1. package/README.md +271 -271
  2. package/dist/gbflowengine.css +1 -1
  3. package/dist/gbflowengine.js +8232 -6913
  4. package/dist/gbflowengine.js.map +1 -1
  5. package/dist/gbflowengine.umd.cjs +2 -2
  6. package/dist/gbflowengine.umd.cjs.map +1 -1
  7. package/package.json +85 -84
  8. package/src/center/DefinitionInspect.vue +291 -291
  9. package/src/center/FlowCenter.vue +33 -33
  10. package/src/center/index.js +29 -29
  11. package/src/center/storage.js +748 -748
  12. package/src/core/flow/condition.js +160 -160
  13. package/src/core/flow/customNode.js +385 -385
  14. package/src/core/flow/defaults.js +124 -124
  15. package/src/core/flow/flowConstant.js +265 -265
  16. package/src/core/flow/flowNodeUtils.js +29 -29
  17. package/src/core/flow/index.js +47 -47
  18. package/src/core/flow/node.js +44 -44
  19. package/src/core/flow/nodeFactory.js +58 -58
  20. package/src/core/flow/prediction.js +325 -325
  21. package/src/core/flow/schema.js +864 -864
  22. package/src/definition/FlowDefinitionDesigner.vue +338 -338
  23. package/src/definition/index.js +9 -9
  24. package/src/index.js +39 -39
  25. package/src/storage.js +200 -200
  26. package/src/testing/FlowTestPanel.vue +2502 -2502
  27. package/src/testing/UserConfigDrawer.vue +376 -376
  28. package/src/testing/diagram/FlowProgressDiagram.vue +318 -318
  29. package/src/testing/diagramModel.js +517 -517
  30. package/src/testing/index.js +23 -23
  31. package/src/testing/mock.js +246 -246
  32. package/src/testing/oaExecutors.js +51 -51
  33. package/src/testing/oaSeed.js +467 -467
  34. package/src/testing/sample.js +412 -412
  35. package/src/testing/seed.js +122 -122
  36. package/src/utils/format.js +27 -27
  37. package/src/visual/FlowCanvas.vue +440 -440
  38. package/src/visual/NodeProgressDetail.vue +43 -43
  39. package/src/visual/NodeStatusBadge.vue +17 -17
  40. package/src/visual/NodeWrap.vue +46 -46
  41. package/src/visual/ScWorkflow.vue +49 -49
  42. package/src/visual/SelectDialog.vue +459 -459
  43. package/src/visual/conditionHelpers.js +116 -116
  44. package/src/visual/index.js +6 -6
  45. package/src/visual/nodes/AddNode.vue +222 -222
  46. package/src/visual/nodes/ApproverNode.vue +347 -347
  47. package/src/visual/nodes/BranchNode.vue +441 -441
  48. package/src/visual/nodes/CustomNode.vue +339 -339
  49. package/src/visual/nodes/EndNode.vue +21 -21
  50. package/src/visual/nodes/PassNode.vue +100 -100
  51. package/src/visual/nodes/PromoterNode.vue +134 -134
  52. package/src/visual/nodes/RejectNode.vue +100 -100
  53. package/src/visual/nodes/SendNode.vue +151 -151
  54. package/src/visual/styles.scss +879 -879
  55. package/src/visual/useScNodeStatus.js +18 -18
  56. package/src/workbench/OaWorkbench.vue +1341 -1341
  57. package/src/workbench/components/ApprovalWorkspace.vue +2090 -2090
  58. package/src/workbench/components/CategoryIcon.vue +74 -74
  59. package/src/workbench/components/NotificationIcon.vue +73 -73
  60. package/src/workbench/components/ProcessSteps.vue +557 -557
  61. package/src/workbench/components/ResubmitDialog.vue +227 -227
  62. package/src/workbench/components/SidebarNav.vue +138 -138
  63. package/src/workbench/components/StartFlowDialog.vue +1058 -1058
  64. package/src/workbench/components/UserAvatar.vue +68 -68
  65. package/src/workbench/model.js +1080 -1080
  66. package/src/workbench/pages/DesignPage.vue +798 -798
  67. package/src/workbench/pages/HomePage.vue +1050 -1050
  68. package/src/workbench/pages/MonitorPage.vue +1029 -1029
  69. package/src/workbench/pages/NotificationsPage.vue +554 -554
  70. package/src/workbench/pages/RequestsPage.vue +644 -644
  71. package/src/workbench/pages/TaskCenterPage.vue +1155 -1155
  72. package/src/workbench/pages/TemplatesPage.vue +680 -680
  73. package/src/workbench/styles.scss +555 -555
  74. package/types/center.d.ts +5 -5
  75. package/types/core.d.ts +479 -479
  76. package/types/definition.d.ts +4 -4
  77. package/types/index.d.ts +34 -34
  78. package/types/testing.d.ts +20 -20
  79. package/types/visual.d.ts +20 -20
@@ -1,385 +1,385 @@
1
- /**
2
- * 自定义节点执行约定:节点配置标准化、模板变量解析,以及 HTTP / 已注册方法执行。
3
- * 运行时只负责派发与收口,真正的异步执行由宿主(OA 工作台或导入方)调用。
4
- */
5
- import { getVariableValue } from './condition.js'
6
-
7
- export const CUSTOM_EXECUTOR_TYPE = Object.freeze({
8
- HTTP: 'http',
9
- METHOD: 'method'
10
- })
11
-
12
- export const CUSTOM_ERROR_POLICY = Object.freeze({
13
- TERMINATE: 'terminate',
14
- CONTINUE: 'continue'
15
- })
16
-
17
- export const CUSTOM_HTTP_METHODS = Object.freeze([
18
- 'GET',
19
- 'POST',
20
- 'PUT',
21
- 'PATCH',
22
- 'DELETE',
23
- 'HEAD'
24
- ])
25
-
26
- export const CUSTOM_TIMEOUT_DEFAULT = 10000
27
- export const CUSTOM_TIMEOUT_MIN = 1000
28
- export const CUSTOM_TIMEOUT_MAX = 120000
29
- export const CUSTOM_RESULT_LIMIT = 200 * 1024
30
-
31
- const DEFAULT_TIMEOUT = CUSTOM_TIMEOUT_DEFAULT
32
- const DEFAULT_HEADERS = [{ key: 'Content-Type', value: 'application/json' }]
33
- const VARIABLE_NAME = /^[A-Za-z_$][\w$]*$/
34
-
35
- const clone = (value) =>
36
- value === undefined ? undefined : JSON.parse(JSON.stringify(value))
37
-
38
- function isPlainObject(value) {
39
- return !!value && typeof value === 'object' && !Array.isArray(value)
40
- }
41
-
42
- function normalizeHeaders(headers) {
43
- if (!Array.isArray(headers)) return clone(DEFAULT_HEADERS)
44
- return headers
45
- .filter((header) => isPlainObject(header) && String(header.key || '').trim())
46
- .map((header) => ({
47
- key: String(header.key).trim(),
48
- value: String(header.value ?? '')
49
- }))
50
- }
51
-
52
- export function createCustomNodeConfig(overrides = {}) {
53
- return normalizeCustomNodeConfig(overrides)
54
- }
55
-
56
- export function normalizeCustomNodeConfig(input = {}) {
57
- const source = isPlainObject(input) ? input : {}
58
- const executorType =
59
- source.executorType === CUSTOM_EXECUTOR_TYPE.METHOD
60
- ? CUSTOM_EXECUTOR_TYPE.METHOD
61
- : CUSTOM_EXECUTOR_TYPE.HTTP
62
- const method = String(source.method || 'POST').toUpperCase()
63
- const timeout = Number(source.timeoutMs)
64
- const headerSource = Array.isArray(source.headers)
65
- ? source.headers
66
- : isPlainObject(source.headers)
67
- ? Object.entries(source.headers).map(([key, value]) => ({ key, value }))
68
- : null
69
- const headers = headerSource ? normalizeHeaders(headerSource) : clone(DEFAULT_HEADERS)
70
- return {
71
- executorType,
72
- url: typeof source.url === 'string' ? source.url.trim() : '',
73
- method: CUSTOM_HTTP_METHODS.includes(method) ? method : 'POST',
74
- headers,
75
- body:
76
- typeof source.body === 'string'
77
- ? source.body
78
- : source.body && typeof source.body === 'object'
79
- ? JSON.stringify(source.body)
80
- : '',
81
- timeoutMs:
82
- Number.isFinite(timeout) && timeout > 0
83
- ? Math.min(CUSTOM_TIMEOUT_MAX, Math.max(CUSTOM_TIMEOUT_MIN, Math.round(timeout)))
84
- : DEFAULT_TIMEOUT,
85
- methodKey: typeof source.methodKey === 'string' ? source.methodKey.trim() : '',
86
- resultVariable:
87
- typeof source.resultVariable === 'string' ? source.resultVariable.trim() : '',
88
- onError:
89
- source.onError === CUSTOM_ERROR_POLICY.CONTINUE
90
- ? CUSTOM_ERROR_POLICY.CONTINUE
91
- : CUSTOM_ERROR_POLICY.TERMINATE
92
- }
93
- }
94
-
95
- function isLiteralUrl(url) {
96
- return Boolean(url) && !url.includes('{{')
97
- }
98
-
99
- function isAllowedRequestUrl(url) {
100
- if (url.startsWith('/') && !url.startsWith('//')) return true
101
- try {
102
- const parsed = new URL(url)
103
- return (
104
- ['http:', 'https:'].includes(parsed.protocol) &&
105
- !parsed.username &&
106
- !parsed.password
107
- )
108
- } catch {
109
- return false
110
- }
111
- }
112
-
113
- export function validateCustomNodeConfig(input) {
114
- const config = normalizeCustomNodeConfig(input)
115
- const errors = []
116
- const warnings = []
117
- if (config.executorType === CUSTOM_EXECUTOR_TYPE.METHOD) {
118
- if (!config.methodKey) {
119
- errors.push({
120
- code: 'CUSTOM_METHOD_EMPTY',
121
- message: '自定义节点尚未填写已注册方法名'
122
- })
123
- }
124
- } else {
125
- if (!config.url) {
126
- errors.push({
127
- code: 'CUSTOM_URL_EMPTY',
128
- message: 'HTTP 自定义节点尚未填写请求地址'
129
- })
130
- } else if (isLiteralUrl(config.url) && !isAllowedRequestUrl(config.url)) {
131
- errors.push({
132
- code: 'CUSTOM_URL_INVALID',
133
- message: `自定义节点请求地址无效:${config.url}(仅支持 http(s) 或站内相对地址)`
134
- })
135
- }
136
- if (
137
- config.body.trim() &&
138
- (config.method === 'GET' || config.method === 'HEAD')
139
- ) {
140
- warnings.push({
141
- code: 'CUSTOM_BODY_IGNORED',
142
- message: `${config.method} 请求会忽略配置的请求体`
143
- })
144
- }
145
- if (
146
- config.headers.some((header) =>
147
- /^(authorization|cookie)$/i.test(header.key)
148
- )
149
- ) {
150
- warnings.push({
151
- code: 'CUSTOM_SECRET_HEADER',
152
- message: '节点配置中包含认证请求头;生产环境建议通过网关或已注册方法注入敏感凭据'
153
- })
154
- }
155
- }
156
- if (config.resultVariable && !VARIABLE_NAME.test(config.resultVariable)) {
157
- warnings.push({
158
- code: 'CUSTOM_RESULT_VARIABLE_INVALID',
159
- message: `结果变量「${config.resultVariable}」不符合变量命名规范,执行结果将只保存在节点轨迹中`
160
- })
161
- }
162
- return { errors, warnings, config }
163
- }
164
-
165
- export function customNodeSummary(input) {
166
- const config = normalizeCustomNodeConfig(input)
167
- const target =
168
- config.executorType === CUSTOM_EXECUTOR_TYPE.METHOD
169
- ? `方法 ${config.methodKey || '未配置方法'}`
170
- : `${config.method} ${config.url || '未配置地址'}`
171
- return config.resultVariable ? `${target} → ${config.resultVariable}` : target
172
- }
173
-
174
- export function isValidCustomResultVariable(value) {
175
- return VARIABLE_NAME.test(String(value || ''))
176
- }
177
-
178
- export function interpolateCustomTemplate(template, variables = {}) {
179
- if (template === null || template === undefined) return ''
180
- if (typeof template !== 'string') return template
181
- return template.replace(/{{\s*([^{}]+?)\s*}}/g, (_, rawKey) => {
182
- const key = String(rawKey).trim()
183
- if (!key) return ''
184
- const value = getVariableValue(variables, key)
185
- if (value === undefined || value === null) return ''
186
- if (typeof value === 'object') {
187
- try {
188
- return JSON.stringify(value)
189
- } catch {
190
- return ''
191
- }
192
- }
193
- return String(value)
194
- })
195
- }
196
-
197
-
198
- export function resolveCustomRequest(input, variables = {}) {
199
- const config = normalizeCustomNodeConfig(input)
200
- const body =
201
- typeof config.body === 'string'
202
- ? interpolateCustomTemplate(config.body, variables)
203
- : config.body
204
- return {
205
- url: interpolateCustomTemplate(config.url, variables),
206
- method: config.method,
207
- headers: config.headers.reduce((result, header) => {
208
- result[interpolateCustomTemplate(header.key, variables)] =
209
- interpolateCustomTemplate(header.value, variables)
210
- return result
211
- }, {}),
212
- body:
213
- config.method === 'GET' || config.method === 'HEAD' || !body
214
- ? undefined
215
- : body,
216
- timeoutMs: config.timeoutMs
217
- }
218
- }
219
-
220
- function serializeResult(value) {
221
- if (value === undefined) return null
222
- let text
223
- try {
224
- text = JSON.stringify(value)
225
- } catch (error) {
226
- throw new Error(`自定义节点执行结果无法序列化:${error.message}`)
227
- }
228
- if (text === undefined) return null
229
- if (text.length > CUSTOM_RESULT_LIMIT) {
230
- throw new Error(
231
- `自定义节点执行结果超过 ${Math.round(CUSTOM_RESULT_LIMIT / 1024)}KB 限制`
232
- )
233
- }
234
- return JSON.parse(text)
235
- }
236
-
237
- function responseHeaders(response) {
238
- const result = {}
239
- if (response?.headers?.forEach) {
240
- response.headers.forEach((value, key) => {
241
- result[String(key)] = String(value)
242
- })
243
- }
244
- return result
245
- }
246
-
247
- function previewResponse(data) {
248
- const text = typeof data === 'string' ? data : JSON.stringify(data)
249
- return String(text || '').slice(0, 200)
250
- }
251
-
252
- async function executeHttp(config, { variables, fetchImpl, signal } = {}) {
253
- const request = resolveCustomRequest(config, variables)
254
- const impl =
255
- fetchImpl ||
256
- (typeof globalThis.fetch === 'function'
257
- ? globalThis.fetch.bind(globalThis)
258
- : null)
259
- if (typeof impl !== 'function') {
260
- throw new Error('当前运行环境不支持 fetch,无法执行 HTTP 自定义节点')
261
- }
262
- if (!isAllowedRequestUrl(request.url)) {
263
- throw new Error(`HTTP 自定义节点地址无效:${request.url || '空'}`)
264
- }
265
-
266
- const controller = new AbortController()
267
- let timedOut = false
268
- const timeout = setTimeout(() => {
269
- timedOut = true
270
- controller.abort()
271
- }, request.timeoutMs)
272
- const abortExternal = () => controller.abort()
273
- if (signal) {
274
- if (signal.aborted) controller.abort()
275
- else signal.addEventListener('abort', abortExternal, { once: true })
276
- }
277
-
278
- try {
279
- const response = await impl(request.url, {
280
- method: request.method,
281
- headers: request.headers,
282
- body: request.body,
283
- signal: controller.signal,
284
- credentials: 'same-origin'
285
- })
286
- const text = await response.text()
287
- if (text.length > CUSTOM_RESULT_LIMIT) {
288
- throw new Error(
289
- `自定义节点响应超过 ${Math.round(CUSTOM_RESULT_LIMIT / 1024)}KB 限制`
290
- )
291
- }
292
- let data = text
293
- const contentType = String(response.headers?.get?.('content-type') || '')
294
- if (text.trim() && (contentType.includes('json') || /^[\[{]/.test(text.trim()))) {
295
- try {
296
- data = JSON.parse(text)
297
- } catch {
298
- data = text
299
- }
300
- }
301
- const result = serializeResult({
302
- status: response.status,
303
- ok: Boolean(response.ok),
304
- headers: responseHeaders(response),
305
- data
306
- })
307
- if (!response.ok) {
308
- const error = new Error(
309
- `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}:${previewResponse(data)}`
310
- )
311
- error.result = result
312
- throw error
313
- }
314
- return result
315
- } catch (error) {
316
- if (error.name === 'AbortError') {
317
- throw new Error(
318
- timedOut
319
- ? `自定义节点请求超时(${request.timeoutMs}ms)`
320
- : '自定义节点请求已取消'
321
- )
322
- }
323
- throw error
324
- } finally {
325
- clearTimeout(timeout)
326
- signal?.removeEventListener?.('abort', abortExternal)
327
- }
328
- }
329
-
330
- function runWithTimeout(promise, timeoutMs, signal, label) {
331
- return new Promise((resolve, reject) => {
332
- let settled = false
333
- const finish = (callback, value) => {
334
- if (settled) return
335
- settled = true
336
- clearTimeout(timer)
337
- signal?.removeEventListener?.('abort', onAbort)
338
- callback(value)
339
- }
340
- const onAbort = () => finish(reject, new Error(`${label}已取消`))
341
- const timer = setTimeout(
342
- () => finish(reject, new Error(`${label}超时(${timeoutMs}ms)`)),
343
- timeoutMs
344
- )
345
- if (signal?.aborted) onAbort()
346
- else signal?.addEventListener('abort', onAbort, { once: true })
347
- Promise.resolve(promise).then(
348
- (value) => finish(resolve, value),
349
- (error) => finish(reject, error)
350
- )
351
- })
352
- }
353
-
354
- async function executeMethod(config, { variables, executors, node, signal, instance } = {}) {
355
- const executor = executors?.[config.methodKey]
356
- if (typeof executor !== 'function') {
357
- throw new Error(`未注册自定义执行方法:${config.methodKey || '未配置方法'}`)
358
- }
359
- const result = await runWithTimeout(
360
- executor({
361
- config,
362
- variables: isPlainObject(variables) ? variables : {},
363
- node: node || null,
364
- instance: instance || null,
365
- signal,
366
- interpolate: (template) => interpolateCustomTemplate(template, variables)
367
- }),
368
- config.timeoutMs,
369
- signal,
370
- '自定义方法执行'
371
- )
372
- return serializeResult(result)
373
- }
374
-
375
- export async function executeCustomNode(input, options = {}) {
376
- const validated = validateCustomNodeConfig(input)
377
- if (validated.errors.length) {
378
- throw new Error(validated.errors[0].message)
379
- }
380
- const config = validated.config
381
- if (config.executorType === CUSTOM_EXECUTOR_TYPE.METHOD) {
382
- return executeMethod(config, options)
383
- }
384
- return executeHttp(config, options)
385
- }
1
+ /**
2
+ * 自定义节点执行约定:节点配置标准化、模板变量解析,以及 HTTP / 已注册方法执行。
3
+ * 运行时只负责派发与收口,真正的异步执行由宿主(OA 工作台或导入方)调用。
4
+ */
5
+ import { getVariableValue } from './condition.js'
6
+
7
+ export const CUSTOM_EXECUTOR_TYPE = Object.freeze({
8
+ HTTP: 'http',
9
+ METHOD: 'method'
10
+ })
11
+
12
+ export const CUSTOM_ERROR_POLICY = Object.freeze({
13
+ TERMINATE: 'terminate',
14
+ CONTINUE: 'continue'
15
+ })
16
+
17
+ export const CUSTOM_HTTP_METHODS = Object.freeze([
18
+ 'GET',
19
+ 'POST',
20
+ 'PUT',
21
+ 'PATCH',
22
+ 'DELETE',
23
+ 'HEAD'
24
+ ])
25
+
26
+ export const CUSTOM_TIMEOUT_DEFAULT = 10000
27
+ export const CUSTOM_TIMEOUT_MIN = 1000
28
+ export const CUSTOM_TIMEOUT_MAX = 120000
29
+ export const CUSTOM_RESULT_LIMIT = 200 * 1024
30
+
31
+ const DEFAULT_TIMEOUT = CUSTOM_TIMEOUT_DEFAULT
32
+ const DEFAULT_HEADERS = [{ key: 'Content-Type', value: 'application/json' }]
33
+ const VARIABLE_NAME = /^[A-Za-z_$][\w$]*$/
34
+
35
+ const clone = (value) =>
36
+ value === undefined ? undefined : JSON.parse(JSON.stringify(value))
37
+
38
+ function isPlainObject(value) {
39
+ return !!value && typeof value === 'object' && !Array.isArray(value)
40
+ }
41
+
42
+ function normalizeHeaders(headers) {
43
+ if (!Array.isArray(headers)) return clone(DEFAULT_HEADERS)
44
+ return headers
45
+ .filter((header) => isPlainObject(header) && String(header.key || '').trim())
46
+ .map((header) => ({
47
+ key: String(header.key).trim(),
48
+ value: String(header.value ?? '')
49
+ }))
50
+ }
51
+
52
+ export function createCustomNodeConfig(overrides = {}) {
53
+ return normalizeCustomNodeConfig(overrides)
54
+ }
55
+
56
+ export function normalizeCustomNodeConfig(input = {}) {
57
+ const source = isPlainObject(input) ? input : {}
58
+ const executorType =
59
+ source.executorType === CUSTOM_EXECUTOR_TYPE.METHOD
60
+ ? CUSTOM_EXECUTOR_TYPE.METHOD
61
+ : CUSTOM_EXECUTOR_TYPE.HTTP
62
+ const method = String(source.method || 'POST').toUpperCase()
63
+ const timeout = Number(source.timeoutMs)
64
+ const headerSource = Array.isArray(source.headers)
65
+ ? source.headers
66
+ : isPlainObject(source.headers)
67
+ ? Object.entries(source.headers).map(([key, value]) => ({ key, value }))
68
+ : null
69
+ const headers = headerSource ? normalizeHeaders(headerSource) : clone(DEFAULT_HEADERS)
70
+ return {
71
+ executorType,
72
+ url: typeof source.url === 'string' ? source.url.trim() : '',
73
+ method: CUSTOM_HTTP_METHODS.includes(method) ? method : 'POST',
74
+ headers,
75
+ body:
76
+ typeof source.body === 'string'
77
+ ? source.body
78
+ : source.body && typeof source.body === 'object'
79
+ ? JSON.stringify(source.body)
80
+ : '',
81
+ timeoutMs:
82
+ Number.isFinite(timeout) && timeout > 0
83
+ ? Math.min(CUSTOM_TIMEOUT_MAX, Math.max(CUSTOM_TIMEOUT_MIN, Math.round(timeout)))
84
+ : DEFAULT_TIMEOUT,
85
+ methodKey: typeof source.methodKey === 'string' ? source.methodKey.trim() : '',
86
+ resultVariable:
87
+ typeof source.resultVariable === 'string' ? source.resultVariable.trim() : '',
88
+ onError:
89
+ source.onError === CUSTOM_ERROR_POLICY.CONTINUE
90
+ ? CUSTOM_ERROR_POLICY.CONTINUE
91
+ : CUSTOM_ERROR_POLICY.TERMINATE
92
+ }
93
+ }
94
+
95
+ function isLiteralUrl(url) {
96
+ return Boolean(url) && !url.includes('{{')
97
+ }
98
+
99
+ function isAllowedRequestUrl(url) {
100
+ if (url.startsWith('/') && !url.startsWith('//')) return true
101
+ try {
102
+ const parsed = new URL(url)
103
+ return (
104
+ ['http:', 'https:'].includes(parsed.protocol) &&
105
+ !parsed.username &&
106
+ !parsed.password
107
+ )
108
+ } catch {
109
+ return false
110
+ }
111
+ }
112
+
113
+ export function validateCustomNodeConfig(input) {
114
+ const config = normalizeCustomNodeConfig(input)
115
+ const errors = []
116
+ const warnings = []
117
+ if (config.executorType === CUSTOM_EXECUTOR_TYPE.METHOD) {
118
+ if (!config.methodKey) {
119
+ errors.push({
120
+ code: 'CUSTOM_METHOD_EMPTY',
121
+ message: '自定义节点尚未填写已注册方法名'
122
+ })
123
+ }
124
+ } else {
125
+ if (!config.url) {
126
+ errors.push({
127
+ code: 'CUSTOM_URL_EMPTY',
128
+ message: 'HTTP 自定义节点尚未填写请求地址'
129
+ })
130
+ } else if (isLiteralUrl(config.url) && !isAllowedRequestUrl(config.url)) {
131
+ errors.push({
132
+ code: 'CUSTOM_URL_INVALID',
133
+ message: `自定义节点请求地址无效:${config.url}(仅支持 http(s) 或站内相对地址)`
134
+ })
135
+ }
136
+ if (
137
+ config.body.trim() &&
138
+ (config.method === 'GET' || config.method === 'HEAD')
139
+ ) {
140
+ warnings.push({
141
+ code: 'CUSTOM_BODY_IGNORED',
142
+ message: `${config.method} 请求会忽略配置的请求体`
143
+ })
144
+ }
145
+ if (
146
+ config.headers.some((header) =>
147
+ /^(authorization|cookie)$/i.test(header.key)
148
+ )
149
+ ) {
150
+ warnings.push({
151
+ code: 'CUSTOM_SECRET_HEADER',
152
+ message: '节点配置中包含认证请求头;生产环境建议通过网关或已注册方法注入敏感凭据'
153
+ })
154
+ }
155
+ }
156
+ if (config.resultVariable && !VARIABLE_NAME.test(config.resultVariable)) {
157
+ warnings.push({
158
+ code: 'CUSTOM_RESULT_VARIABLE_INVALID',
159
+ message: `结果变量「${config.resultVariable}」不符合变量命名规范,执行结果将只保存在节点轨迹中`
160
+ })
161
+ }
162
+ return { errors, warnings, config }
163
+ }
164
+
165
+ export function customNodeSummary(input) {
166
+ const config = normalizeCustomNodeConfig(input)
167
+ const target =
168
+ config.executorType === CUSTOM_EXECUTOR_TYPE.METHOD
169
+ ? `方法 ${config.methodKey || '未配置方法'}`
170
+ : `${config.method} ${config.url || '未配置地址'}`
171
+ return config.resultVariable ? `${target} → ${config.resultVariable}` : target
172
+ }
173
+
174
+ export function isValidCustomResultVariable(value) {
175
+ return VARIABLE_NAME.test(String(value || ''))
176
+ }
177
+
178
+ export function interpolateCustomTemplate(template, variables = {}) {
179
+ if (template === null || template === undefined) return ''
180
+ if (typeof template !== 'string') return template
181
+ return template.replace(/{{\s*([^{}]+?)\s*}}/g, (_, rawKey) => {
182
+ const key = String(rawKey).trim()
183
+ if (!key) return ''
184
+ const value = getVariableValue(variables, key)
185
+ if (value === undefined || value === null) return ''
186
+ if (typeof value === 'object') {
187
+ try {
188
+ return JSON.stringify(value)
189
+ } catch {
190
+ return ''
191
+ }
192
+ }
193
+ return String(value)
194
+ })
195
+ }
196
+
197
+
198
+ export function resolveCustomRequest(input, variables = {}) {
199
+ const config = normalizeCustomNodeConfig(input)
200
+ const body =
201
+ typeof config.body === 'string'
202
+ ? interpolateCustomTemplate(config.body, variables)
203
+ : config.body
204
+ return {
205
+ url: interpolateCustomTemplate(config.url, variables),
206
+ method: config.method,
207
+ headers: config.headers.reduce((result, header) => {
208
+ result[interpolateCustomTemplate(header.key, variables)] =
209
+ interpolateCustomTemplate(header.value, variables)
210
+ return result
211
+ }, {}),
212
+ body:
213
+ config.method === 'GET' || config.method === 'HEAD' || !body
214
+ ? undefined
215
+ : body,
216
+ timeoutMs: config.timeoutMs
217
+ }
218
+ }
219
+
220
+ function serializeResult(value) {
221
+ if (value === undefined) return null
222
+ let text
223
+ try {
224
+ text = JSON.stringify(value)
225
+ } catch (error) {
226
+ throw new Error(`自定义节点执行结果无法序列化:${error.message}`)
227
+ }
228
+ if (text === undefined) return null
229
+ if (text.length > CUSTOM_RESULT_LIMIT) {
230
+ throw new Error(
231
+ `自定义节点执行结果超过 ${Math.round(CUSTOM_RESULT_LIMIT / 1024)}KB 限制`
232
+ )
233
+ }
234
+ return JSON.parse(text)
235
+ }
236
+
237
+ function responseHeaders(response) {
238
+ const result = {}
239
+ if (response?.headers?.forEach) {
240
+ response.headers.forEach((value, key) => {
241
+ result[String(key)] = String(value)
242
+ })
243
+ }
244
+ return result
245
+ }
246
+
247
+ function previewResponse(data) {
248
+ const text = typeof data === 'string' ? data : JSON.stringify(data)
249
+ return String(text || '').slice(0, 200)
250
+ }
251
+
252
+ async function executeHttp(config, { variables, fetchImpl, signal } = {}) {
253
+ const request = resolveCustomRequest(config, variables)
254
+ const impl =
255
+ fetchImpl ||
256
+ (typeof globalThis.fetch === 'function'
257
+ ? globalThis.fetch.bind(globalThis)
258
+ : null)
259
+ if (typeof impl !== 'function') {
260
+ throw new Error('当前运行环境不支持 fetch,无法执行 HTTP 自定义节点')
261
+ }
262
+ if (!isAllowedRequestUrl(request.url)) {
263
+ throw new Error(`HTTP 自定义节点地址无效:${request.url || '空'}`)
264
+ }
265
+
266
+ const controller = new AbortController()
267
+ let timedOut = false
268
+ const timeout = setTimeout(() => {
269
+ timedOut = true
270
+ controller.abort()
271
+ }, request.timeoutMs)
272
+ const abortExternal = () => controller.abort()
273
+ if (signal) {
274
+ if (signal.aborted) controller.abort()
275
+ else signal.addEventListener('abort', abortExternal, { once: true })
276
+ }
277
+
278
+ try {
279
+ const response = await impl(request.url, {
280
+ method: request.method,
281
+ headers: request.headers,
282
+ body: request.body,
283
+ signal: controller.signal,
284
+ credentials: 'same-origin'
285
+ })
286
+ const text = await response.text()
287
+ if (text.length > CUSTOM_RESULT_LIMIT) {
288
+ throw new Error(
289
+ `自定义节点响应超过 ${Math.round(CUSTOM_RESULT_LIMIT / 1024)}KB 限制`
290
+ )
291
+ }
292
+ let data = text
293
+ const contentType = String(response.headers?.get?.('content-type') || '')
294
+ if (text.trim() && (contentType.includes('json') || /^[\[{]/.test(text.trim()))) {
295
+ try {
296
+ data = JSON.parse(text)
297
+ } catch {
298
+ data = text
299
+ }
300
+ }
301
+ const result = serializeResult({
302
+ status: response.status,
303
+ ok: Boolean(response.ok),
304
+ headers: responseHeaders(response),
305
+ data
306
+ })
307
+ if (!response.ok) {
308
+ const error = new Error(
309
+ `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}:${previewResponse(data)}`
310
+ )
311
+ error.result = result
312
+ throw error
313
+ }
314
+ return result
315
+ } catch (error) {
316
+ if (error.name === 'AbortError') {
317
+ throw new Error(
318
+ timedOut
319
+ ? `自定义节点请求超时(${request.timeoutMs}ms)`
320
+ : '自定义节点请求已取消'
321
+ )
322
+ }
323
+ throw error
324
+ } finally {
325
+ clearTimeout(timeout)
326
+ signal?.removeEventListener?.('abort', abortExternal)
327
+ }
328
+ }
329
+
330
+ function runWithTimeout(promise, timeoutMs, signal, label) {
331
+ return new Promise((resolve, reject) => {
332
+ let settled = false
333
+ const finish = (callback, value) => {
334
+ if (settled) return
335
+ settled = true
336
+ clearTimeout(timer)
337
+ signal?.removeEventListener?.('abort', onAbort)
338
+ callback(value)
339
+ }
340
+ const onAbort = () => finish(reject, new Error(`${label}已取消`))
341
+ const timer = setTimeout(
342
+ () => finish(reject, new Error(`${label}超时(${timeoutMs}ms)`)),
343
+ timeoutMs
344
+ )
345
+ if (signal?.aborted) onAbort()
346
+ else signal?.addEventListener('abort', onAbort, { once: true })
347
+ Promise.resolve(promise).then(
348
+ (value) => finish(resolve, value),
349
+ (error) => finish(reject, error)
350
+ )
351
+ })
352
+ }
353
+
354
+ async function executeMethod(config, { variables, executors, node, signal, instance } = {}) {
355
+ const executor = executors?.[config.methodKey]
356
+ if (typeof executor !== 'function') {
357
+ throw new Error(`未注册自定义执行方法:${config.methodKey || '未配置方法'}`)
358
+ }
359
+ const result = await runWithTimeout(
360
+ executor({
361
+ config,
362
+ variables: isPlainObject(variables) ? variables : {},
363
+ node: node || null,
364
+ instance: instance || null,
365
+ signal,
366
+ interpolate: (template) => interpolateCustomTemplate(template, variables)
367
+ }),
368
+ config.timeoutMs,
369
+ signal,
370
+ '自定义方法执行'
371
+ )
372
+ return serializeResult(result)
373
+ }
374
+
375
+ export async function executeCustomNode(input, options = {}) {
376
+ const validated = validateCustomNodeConfig(input)
377
+ if (validated.errors.length) {
378
+ throw new Error(validated.errors[0].message)
379
+ }
380
+ const config = validated.config
381
+ if (config.executorType === CUSTOM_EXECUTOR_TYPE.METHOD) {
382
+ return executeMethod(config, options)
383
+ }
384
+ return executeHttp(config, options)
385
+ }