@coze/realtime-api 1.0.4 → 1.0.5
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 +3 -1
- package/README.zh-CN.md +3 -1
- package/dist/cjs/index.cjs +2155 -1355
- package/dist/cjs/index.cjs.LICENSE.txt +22 -0
- package/dist/esm/index.js +2157 -1357
- package/dist/esm/index.js.LICENSE.txt +22 -0
- package/dist/types/client.d.ts +2 -1
- package/dist/types/index.d.ts +11 -1
- package/dist/umd/index.js +2155 -1355
- package/dist/umd/index.js.LICENSE.txt +22 -0
- package/package.json +18 -6
package/dist/cjs/index.cjs
CHANGED
@@ -1,11 +1,18 @@
|
|
1
1
|
/*! For license information please see index.cjs.LICENSE.txt */
|
2
2
|
"use strict";
|
3
3
|
var __webpack_modules__ = {
|
4
|
-
"
|
4
|
+
"../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js": function(module) {
|
5
|
+
module.exports = function() {
|
6
|
+
throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object");
|
7
|
+
};
|
8
|
+
},
|
9
|
+
"?666e": function() {
|
5
10
|
/* (ignored) */ },
|
6
|
-
"?
|
11
|
+
"?79fd": function() {
|
7
12
|
/* (ignored) */ },
|
8
|
-
"?
|
13
|
+
"?8dee": function() {
|
14
|
+
/* (ignored) */ },
|
15
|
+
"?9050": function() {
|
9
16
|
/* (ignored) */ }
|
10
17
|
};
|
11
18
|
/************************************************************************/ // The module cache
|
@@ -24,7 +31,22 @@ function __webpack_require__(moduleId) {
|
|
24
31
|
// Return the exports of the module
|
25
32
|
return module.exports;
|
26
33
|
}
|
27
|
-
/************************************************************************/ // webpack/runtime/
|
34
|
+
/************************************************************************/ // webpack/runtime/compat_get_default_export
|
35
|
+
(()=>{
|
36
|
+
// getDefaultExport function for compatibility with non-ESM modules
|
37
|
+
__webpack_require__.n = function(module) {
|
38
|
+
var getter = module && module.__esModule ? function() {
|
39
|
+
return module['default'];
|
40
|
+
} : function() {
|
41
|
+
return module;
|
42
|
+
};
|
43
|
+
__webpack_require__.d(getter, {
|
44
|
+
a: getter
|
45
|
+
});
|
46
|
+
return getter;
|
47
|
+
};
|
48
|
+
})();
|
49
|
+
// webpack/runtime/define_property_getters
|
28
50
|
(()=>{
|
29
51
|
__webpack_require__.d = function(exports1, definition) {
|
30
52
|
for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
|
@@ -92,480 +114,1038 @@ __webpack_require__.d(src_utils_namespaceObject, {
|
|
92
114
|
getAudioDevices: ()=>getAudioDevices,
|
93
115
|
isScreenShareDevice: ()=>isScreenShareDevice,
|
94
116
|
isScreenShareSupported: ()=>isScreenShareSupported,
|
95
|
-
sleep: ()=>
|
117
|
+
sleep: ()=>src_utils_sleep
|
96
118
|
});
|
97
|
-
|
98
|
-
|
99
|
-
|
100
|
-
}
|
119
|
+
class APIResource {
|
120
|
+
constructor(client){
|
121
|
+
this._client = client;
|
122
|
+
}
|
101
123
|
}
|
102
|
-
|
103
|
-
|
104
|
-
|
105
|
-
|
106
|
-
|
107
|
-
|
108
|
-
|
109
|
-
|
110
|
-
|
111
|
-
|
112
|
-
|
113
|
-
|
114
|
-
|
115
|
-
|
116
|
-
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
|
133
|
-
|
134
|
-
|
135
|
-
|
124
|
+
/* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
|
125
|
+
/**
|
126
|
+
* Create a new agent. | 调用接口创建一个新的智能体。
|
127
|
+
* @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
|
128
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
|
129
|
+
* @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
|
130
|
+
* @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
|
131
|
+
* @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
|
132
|
+
* @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
|
133
|
+
* @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
|
134
|
+
* @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
|
135
|
+
* @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
|
136
|
+
* @returns Information about the created bot. | 创建的 Bot 信息。
|
137
|
+
*/ async create(params, options) {
|
138
|
+
const apiUrl = '/v1/bot/create';
|
139
|
+
const result = await this._client.post(apiUrl, params, false, options);
|
140
|
+
return result.data;
|
141
|
+
}
|
142
|
+
/**
|
143
|
+
* Update the configuration of an agent. | 调用接口修改智能体的配置。
|
144
|
+
* @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
|
145
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
|
146
|
+
* @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
|
147
|
+
* @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
|
148
|
+
* @param params.name - Optional The name of the agent. | Bot 的名称。
|
149
|
+
* @param params.description - Optional The description of the agent. | Bot 的描述信息。
|
150
|
+
* @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
|
151
|
+
* @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
|
152
|
+
* @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
|
153
|
+
* @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
|
154
|
+
* @returns Undefined | 无返回值
|
155
|
+
*/ async update(params, options) {
|
156
|
+
const apiUrl = '/v1/bot/update';
|
157
|
+
const result = await this._client.post(apiUrl, params, false, options);
|
158
|
+
return result.data;
|
159
|
+
}
|
160
|
+
/**
|
161
|
+
* Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
|
162
|
+
* @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
|
163
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
|
164
|
+
* @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
|
165
|
+
* @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
|
166
|
+
* @param params.page_size - Optional Pagination size. | 分页大小。
|
167
|
+
* @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
|
168
|
+
* @returns List of published bots. | 已发布的 Bot 列表。
|
169
|
+
*/ async list(params, options) {
|
170
|
+
const apiUrl = '/v1/space/published_bots_list';
|
171
|
+
const result = await this._client.get(apiUrl, params, false, options);
|
172
|
+
return result.data;
|
173
|
+
}
|
174
|
+
/**
|
175
|
+
* Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
|
176
|
+
* @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
|
177
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
|
178
|
+
* @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
|
179
|
+
* @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
|
180
|
+
* @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
|
181
|
+
* @returns Undefined | 无返回值
|
182
|
+
*/ async publish(params, options) {
|
183
|
+
const apiUrl = '/v1/bot/publish';
|
184
|
+
const result = await this._client.post(apiUrl, params, false, options);
|
185
|
+
return result.data;
|
186
|
+
}
|
187
|
+
/**
|
188
|
+
* Get the configuration information of the agent. | 获取指定智能体的配置信息。
|
189
|
+
* @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
|
190
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
|
191
|
+
* @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
|
192
|
+
* @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
|
193
|
+
* @returns Information about the bot. | Bot 的配置信息。
|
194
|
+
*/ async retrieve(params, options) {
|
195
|
+
const apiUrl = '/v1/bot/get_online_info';
|
196
|
+
const result = await this._client.get(apiUrl, params, false, options);
|
197
|
+
return result.data;
|
198
|
+
}
|
136
199
|
}
|
137
|
-
|
138
|
-
|
139
|
-
|
140
|
-
|
141
|
-
|
142
|
-
|
143
|
-
|
144
|
-
/**
|
145
|
-
* Determine if a value is a view on an ArrayBuffer
|
146
|
-
*
|
147
|
-
* @param {*} val The value to test
|
148
|
-
*
|
149
|
-
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
|
150
|
-
*/ function isArrayBufferView(val) {
|
151
|
-
let result;
|
152
|
-
result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
|
153
|
-
return result;
|
200
|
+
/* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
|
201
|
+
let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
|
202
|
+
try {
|
203
|
+
return JSON.parse(jsonString);
|
204
|
+
} catch (error) {
|
205
|
+
return defaultValue;
|
206
|
+
}
|
154
207
|
}
|
155
|
-
|
156
|
-
|
157
|
-
|
158
|
-
|
159
|
-
|
160
|
-
|
161
|
-
|
162
|
-
|
163
|
-
|
164
|
-
|
165
|
-
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
|
179
|
-
|
180
|
-
|
181
|
-
|
182
|
-
|
183
|
-
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
|
189
|
-
|
190
|
-
|
191
|
-
|
192
|
-
|
193
|
-
|
194
|
-
|
195
|
-
|
196
|
-
|
197
|
-
|
198
|
-
|
199
|
-
/**
|
200
|
-
* Determine if a value is a Date
|
201
|
-
*
|
202
|
-
* @param {*} val The value to test
|
203
|
-
*
|
204
|
-
* @returns {boolean} True if value is a Date, otherwise false
|
205
|
-
*/ const isDate = kindOfTest('Date');
|
206
|
-
/**
|
207
|
-
* Determine if a value is a File
|
208
|
-
*
|
209
|
-
* @param {*} val The value to test
|
210
|
-
*
|
211
|
-
* @returns {boolean} True if value is a File, otherwise false
|
212
|
-
*/ const isFile = kindOfTest('File');
|
213
|
-
/**
|
214
|
-
* Determine if a value is a Blob
|
215
|
-
*
|
216
|
-
* @param {*} val The value to test
|
217
|
-
*
|
218
|
-
* @returns {boolean} True if value is a Blob, otherwise false
|
219
|
-
*/ const isBlob = kindOfTest('Blob');
|
220
|
-
/**
|
221
|
-
* Determine if a value is a FileList
|
222
|
-
*
|
223
|
-
* @param {*} val The value to test
|
224
|
-
*
|
225
|
-
* @returns {boolean} True if value is a File, otherwise false
|
226
|
-
*/ const utils_isFileList = kindOfTest('FileList');
|
227
|
-
/**
|
228
|
-
* Determine if a value is a Stream
|
229
|
-
*
|
230
|
-
* @param {*} val The value to test
|
231
|
-
*
|
232
|
-
* @returns {boolean} True if value is a Stream, otherwise false
|
233
|
-
*/ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
|
234
|
-
/**
|
235
|
-
* Determine if a value is a FormData
|
236
|
-
*
|
237
|
-
* @param {*} thing The value to test
|
238
|
-
*
|
239
|
-
* @returns {boolean} True if value is an FormData, otherwise false
|
240
|
-
*/ const utils_isFormData = (thing)=>{
|
241
|
-
let kind;
|
242
|
-
return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
|
243
|
-
'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
|
244
|
-
};
|
245
|
-
/**
|
246
|
-
* Determine if a value is a URLSearchParams object
|
247
|
-
*
|
248
|
-
* @param {*} val The value to test
|
249
|
-
*
|
250
|
-
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
|
251
|
-
*/ const isURLSearchParams = kindOfTest('URLSearchParams');
|
252
|
-
const [isReadableStream, isRequest, isResponse, isHeaders] = [
|
253
|
-
'ReadableStream',
|
254
|
-
'Request',
|
255
|
-
'Response',
|
256
|
-
'Headers'
|
257
|
-
].map(kindOfTest);
|
258
|
-
/**
|
259
|
-
* Trim excess whitespace off the beginning and end of a string
|
260
|
-
*
|
261
|
-
* @param {String} str The String to trim
|
262
|
-
*
|
263
|
-
* @returns {String} The String freed of excess whitespace
|
264
|
-
*/ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
|
265
|
-
/**
|
266
|
-
* Iterate over an Array or an Object invoking a function for each item.
|
267
|
-
*
|
268
|
-
* If `obj` is an Array callback will be called passing
|
269
|
-
* the value, index, and complete array for each item.
|
270
|
-
*
|
271
|
-
* If 'obj' is an Object callback will be called passing
|
272
|
-
* the value, key, and complete object for each property.
|
273
|
-
*
|
274
|
-
* @param {Object|Array} obj The object to iterate
|
275
|
-
* @param {Function} fn The callback to invoke for each item
|
276
|
-
*
|
277
|
-
* @param {Boolean} [allOwnKeys = false]
|
278
|
-
* @returns {any}
|
279
|
-
*/ function forEach(obj, fn, { allOwnKeys = false } = {}) {
|
280
|
-
// Don't bother if no value provided
|
281
|
-
if (null == obj) return;
|
282
|
-
let i;
|
283
|
-
let l;
|
284
|
-
// Force an array if not already something iterable
|
285
|
-
if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
|
286
|
-
obj
|
287
|
-
];
|
288
|
-
if (isArray(obj)) // Iterate over array values
|
289
|
-
for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
|
290
|
-
else {
|
291
|
-
// Iterate over object keys
|
292
|
-
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
|
293
|
-
const len = keys.length;
|
294
|
-
let key;
|
295
|
-
for(i = 0; i < len; i++){
|
296
|
-
key = keys[i];
|
297
|
-
fn.call(null, obj[key], key, obj);
|
208
|
+
function utils_sleep(ms) {
|
209
|
+
return new Promise((resolve)=>{
|
210
|
+
setTimeout(resolve, ms);
|
211
|
+
});
|
212
|
+
}
|
213
|
+
function utils_isBrowser() {
|
214
|
+
return 'undefined' != typeof window;
|
215
|
+
}
|
216
|
+
function isPlainObject(obj) {
|
217
|
+
if ('object' != typeof obj || null === obj) return false;
|
218
|
+
const proto = Object.getPrototypeOf(obj);
|
219
|
+
if (null === proto) return true;
|
220
|
+
let baseProto = proto;
|
221
|
+
while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
|
222
|
+
return proto === baseProto;
|
223
|
+
}
|
224
|
+
function mergeConfig() {
|
225
|
+
for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
|
226
|
+
return objects.reduce((result, obj)=>{
|
227
|
+
if (void 0 === obj) return result || {};
|
228
|
+
for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
229
|
+
if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
|
230
|
+
else result[key] = obj[key];
|
231
|
+
}
|
232
|
+
return result;
|
233
|
+
}, {});
|
234
|
+
}
|
235
|
+
function isPersonalAccessToken(token) {
|
236
|
+
return null == token ? void 0 : token.startsWith('pat_');
|
237
|
+
}
|
238
|
+
/* eslint-disable max-params */ class CozeError extends Error {
|
239
|
+
}
|
240
|
+
class error_APIError extends CozeError {
|
241
|
+
static makeMessage(status, errorBody, message, headers) {
|
242
|
+
if (!errorBody && message) return message;
|
243
|
+
if (errorBody) {
|
244
|
+
const list = [];
|
245
|
+
const { code, msg, error } = errorBody;
|
246
|
+
if (code) list.push(`code: ${code}`);
|
247
|
+
if (msg) list.push(`msg: ${msg}`);
|
248
|
+
if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
|
249
|
+
const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
|
250
|
+
if (logId) list.push(`logid: ${logId}`);
|
251
|
+
return list.join(', ');
|
298
252
|
}
|
253
|
+
if (status) return `http status code: ${status} (no body)`;
|
254
|
+
return '(no status code or body)';
|
255
|
+
}
|
256
|
+
static generate(status, errorResponse, message, headers) {
|
257
|
+
if (!status) return new APIConnectionError({
|
258
|
+
cause: castToError(errorResponse)
|
259
|
+
});
|
260
|
+
const error = errorResponse;
|
261
|
+
// https://www.coze.cn/docs/developer_guides/coze_error_codes
|
262
|
+
if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
|
263
|
+
if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
|
264
|
+
if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
|
265
|
+
if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
|
266
|
+
if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
|
267
|
+
if (408 === status) return new TimeoutError(status, error, message, headers);
|
268
|
+
if (502 === status) return new GatewayError(status, error, message, headers);
|
269
|
+
if (status >= 500) return new InternalServerError(status, error, message, headers);
|
270
|
+
return new error_APIError(status, error, message, headers);
|
271
|
+
}
|
272
|
+
constructor(status, error, message, headers){
|
273
|
+
var _error_detail, _error_error;
|
274
|
+
super(`${error_APIError.makeMessage(status, error, message, headers)}`);
|
275
|
+
this.status = status;
|
276
|
+
this.headers = headers;
|
277
|
+
this.logid = (null == error ? void 0 : null === (_error_detail = error.detail) || void 0 === _error_detail ? void 0 : _error_detail.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
|
278
|
+
// this.error = error;
|
279
|
+
this.code = null == error ? void 0 : error.code;
|
280
|
+
this.msg = null == error ? void 0 : error.msg;
|
281
|
+
this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
|
282
|
+
this.rawError = error;
|
299
283
|
}
|
300
284
|
}
|
301
|
-
|
302
|
-
|
303
|
-
|
304
|
-
|
305
|
-
|
306
|
-
|
307
|
-
_key = keys[i];
|
308
|
-
if (key === _key.toLowerCase()) return _key;
|
285
|
+
class APIConnectionError extends error_APIError {
|
286
|
+
constructor({ message, cause }){
|
287
|
+
super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
|
288
|
+
// if (cause) {
|
289
|
+
// this.cause = cause;
|
290
|
+
// }
|
309
291
|
}
|
310
|
-
return null;
|
311
292
|
}
|
312
|
-
|
313
|
-
|
314
|
-
|
315
|
-
}
|
316
|
-
const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
|
317
|
-
/**
|
318
|
-
* Accepts varargs expecting each argument to be an object, then
|
319
|
-
* immutably merges the properties of each object and returns result.
|
320
|
-
*
|
321
|
-
* When multiple objects contain the same key the later object in
|
322
|
-
* the arguments list will take precedence.
|
323
|
-
*
|
324
|
-
* Example:
|
325
|
-
*
|
326
|
-
* ```js
|
327
|
-
* var result = merge({foo: 123}, {foo: 456});
|
328
|
-
* console.log(result.foo); // outputs 456
|
329
|
-
* ```
|
330
|
-
*
|
331
|
-
* @param {Object} obj1 Object to merge
|
332
|
-
*
|
333
|
-
* @returns {Object} Result of all merge properties
|
334
|
-
*/ function utils_merge() {
|
335
|
-
const { caseless } = isContextDefined(this) && this || {};
|
336
|
-
const result = {};
|
337
|
-
const assignValue = (val, key)=>{
|
338
|
-
const targetKey = caseless && findKey(result, key) || key;
|
339
|
-
if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
|
340
|
-
else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
|
341
|
-
else if (isArray(val)) result[targetKey] = val.slice();
|
342
|
-
else result[targetKey] = val;
|
343
|
-
};
|
344
|
-
for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
|
345
|
-
return result;
|
293
|
+
class APIUserAbortError extends error_APIError {
|
294
|
+
constructor(message){
|
295
|
+
super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
|
296
|
+
}
|
346
297
|
}
|
347
|
-
|
348
|
-
|
349
|
-
|
350
|
-
|
351
|
-
|
352
|
-
|
353
|
-
|
354
|
-
|
355
|
-
|
356
|
-
|
357
|
-
|
358
|
-
|
359
|
-
|
360
|
-
}
|
361
|
-
|
362
|
-
|
363
|
-
|
364
|
-
|
365
|
-
|
366
|
-
|
367
|
-
|
368
|
-
|
369
|
-
|
370
|
-
|
371
|
-
|
372
|
-
|
373
|
-
|
374
|
-
|
375
|
-
|
376
|
-
|
377
|
-
|
378
|
-
|
379
|
-
|
380
|
-
|
381
|
-
|
382
|
-
|
383
|
-
|
384
|
-
|
385
|
-
|
386
|
-
|
387
|
-
|
388
|
-
|
389
|
-
|
390
|
-
};
|
391
|
-
/**
|
392
|
-
* Resolve object with deep prototype chain to a flat object
|
393
|
-
* @param {Object} sourceObj source object
|
394
|
-
* @param {Object} [destObj]
|
395
|
-
* @param {Function|Boolean} [filter]
|
396
|
-
* @param {Function} [propFilter]
|
397
|
-
*
|
398
|
-
* @returns {Object}
|
399
|
-
*/ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
|
400
|
-
let props;
|
401
|
-
let i;
|
402
|
-
let prop;
|
403
|
-
const merged = {};
|
404
|
-
destObj = destObj || {};
|
405
|
-
// eslint-disable-next-line no-eq-null,eqeqeq
|
406
|
-
if (null == sourceObj) return destObj;
|
407
|
-
do {
|
408
|
-
props = Object.getOwnPropertyNames(sourceObj);
|
409
|
-
i = props.length;
|
410
|
-
while(i-- > 0){
|
411
|
-
prop = props[i];
|
412
|
-
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
|
413
|
-
destObj[prop] = sourceObj[prop];
|
414
|
-
merged[prop] = true;
|
415
|
-
}
|
416
|
-
}
|
417
|
-
sourceObj = false !== filter && getPrototypeOf(sourceObj);
|
418
|
-
}while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
|
419
|
-
return destObj;
|
298
|
+
class BadRequestError extends error_APIError {
|
299
|
+
constructor(...args){
|
300
|
+
super(...args), this.name = 'BadRequestError', this.status = 400;
|
301
|
+
}
|
302
|
+
}
|
303
|
+
class AuthenticationError extends error_APIError {
|
304
|
+
constructor(...args){
|
305
|
+
super(...args), this.name = 'AuthenticationError', this.status = 401;
|
306
|
+
}
|
307
|
+
}
|
308
|
+
class PermissionDeniedError extends error_APIError {
|
309
|
+
constructor(...args){
|
310
|
+
super(...args), this.name = 'PermissionDeniedError', this.status = 403;
|
311
|
+
}
|
312
|
+
}
|
313
|
+
class NotFoundError extends error_APIError {
|
314
|
+
constructor(...args){
|
315
|
+
super(...args), this.name = 'NotFoundError', this.status = 404;
|
316
|
+
}
|
317
|
+
}
|
318
|
+
class TimeoutError extends error_APIError {
|
319
|
+
constructor(...args){
|
320
|
+
super(...args), this.name = 'TimeoutError', this.status = 408;
|
321
|
+
}
|
322
|
+
}
|
323
|
+
class RateLimitError extends error_APIError {
|
324
|
+
constructor(...args){
|
325
|
+
super(...args), this.name = 'RateLimitError', this.status = 429;
|
326
|
+
}
|
327
|
+
}
|
328
|
+
class InternalServerError extends error_APIError {
|
329
|
+
constructor(...args){
|
330
|
+
super(...args), this.name = 'InternalServerError', this.status = 500;
|
331
|
+
}
|
332
|
+
}
|
333
|
+
class GatewayError extends error_APIError {
|
334
|
+
constructor(...args){
|
335
|
+
super(...args), this.name = 'GatewayError', this.status = 502;
|
336
|
+
}
|
337
|
+
}
|
338
|
+
const castToError = (err)=>{
|
339
|
+
if (err instanceof Error) return err;
|
340
|
+
return new Error(err);
|
420
341
|
};
|
342
|
+
class Messages extends APIResource {
|
343
|
+
/**
|
344
|
+
* Get the list of messages in a chat. | 获取对话中的消息列表。
|
345
|
+
* @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
|
346
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
|
347
|
+
* @param conversation_id - Required The ID of the conversation. | 会话 ID。
|
348
|
+
* @param chat_id - Required The ID of the chat. | 对话 ID。
|
349
|
+
* @returns An array of chat messages. | 对话消息数组。
|
350
|
+
*/ async list(conversation_id, chat_id, options) {
|
351
|
+
const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
|
352
|
+
const result = await this._client.get(apiUrl, void 0, false, options);
|
353
|
+
return result.data;
|
354
|
+
}
|
355
|
+
}
|
356
|
+
const uuid = ()=>(Math.random() * new Date().getTime()).toString();
|
357
|
+
const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
|
358
|
+
...i,
|
359
|
+
content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
|
360
|
+
}));
|
361
|
+
class Chat extends APIResource {
|
362
|
+
/**
|
363
|
+
* Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
|
364
|
+
* @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
|
365
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
|
366
|
+
* @param params - Required The parameters for creating a chat session. | 创建会话的参数。
|
367
|
+
* @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
|
368
|
+
* @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
|
369
|
+
* @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
|
370
|
+
* @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
|
371
|
+
* @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
|
372
|
+
* @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
|
373
|
+
* @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
|
374
|
+
* @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
|
375
|
+
* @returns The data of the created chat. | 创建的对话数据。
|
376
|
+
*/ async create(params, options) {
|
377
|
+
if (!params.user_id) params.user_id = uuid();
|
378
|
+
const { conversation_id, ...rest } = params;
|
379
|
+
const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
|
380
|
+
const payload = {
|
381
|
+
...rest,
|
382
|
+
additional_messages: handleAdditionalMessages(params.additional_messages),
|
383
|
+
stream: false
|
384
|
+
};
|
385
|
+
const result = await this._client.post(apiUrl, payload, false, options);
|
386
|
+
return result.data;
|
387
|
+
}
|
388
|
+
/**
|
389
|
+
* Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
|
390
|
+
* @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
|
391
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
|
392
|
+
* @param params - Required The parameters for creating a chat session. | 创建会话的参数。
|
393
|
+
* @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
|
394
|
+
* @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
|
395
|
+
* @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
|
396
|
+
* @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
|
397
|
+
* @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
|
398
|
+
* @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
|
399
|
+
* @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
|
400
|
+
* @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
|
401
|
+
* @returns
|
402
|
+
*/ async createAndPoll(params, options) {
|
403
|
+
if (!params.user_id) params.user_id = uuid();
|
404
|
+
const { conversation_id, ...rest } = params;
|
405
|
+
const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
|
406
|
+
const payload = {
|
407
|
+
...rest,
|
408
|
+
additional_messages: handleAdditionalMessages(params.additional_messages),
|
409
|
+
stream: false
|
410
|
+
};
|
411
|
+
const result = await this._client.post(apiUrl, payload, false, options);
|
412
|
+
const chatId = result.data.id;
|
413
|
+
const conversationId = result.data.conversation_id;
|
414
|
+
let chat;
|
415
|
+
while(true){
|
416
|
+
await utils_sleep(100);
|
417
|
+
chat = await this.retrieve(conversationId, chatId);
|
418
|
+
if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
|
419
|
+
}
|
420
|
+
const messageList = await this.messages.list(conversationId, chatId);
|
421
|
+
return {
|
422
|
+
chat,
|
423
|
+
messages: messageList
|
424
|
+
};
|
425
|
+
}
|
426
|
+
/**
|
427
|
+
* Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
|
428
|
+
* @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
|
429
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
|
430
|
+
* @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
|
431
|
+
* @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
|
432
|
+
* @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
|
433
|
+
* @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
|
434
|
+
* @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
|
435
|
+
* @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
|
436
|
+
* @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
|
437
|
+
* @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
|
438
|
+
* @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
|
439
|
+
* @returns A stream of chat data. | 对话数据流。
|
440
|
+
*/ async *stream(params, options) {
|
441
|
+
if (!params.user_id) params.user_id = uuid();
|
442
|
+
const { conversation_id, ...rest } = params;
|
443
|
+
const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
|
444
|
+
const payload = {
|
445
|
+
...rest,
|
446
|
+
additional_messages: handleAdditionalMessages(params.additional_messages),
|
447
|
+
stream: true
|
448
|
+
};
|
449
|
+
const result = await this._client.post(apiUrl, payload, true, options);
|
450
|
+
for await (const message of result)if ("done" === message.event) {
|
451
|
+
const ret = {
|
452
|
+
event: message.event,
|
453
|
+
data: '[DONE]'
|
454
|
+
};
|
455
|
+
yield ret;
|
456
|
+
} else try {
|
457
|
+
const ret = {
|
458
|
+
event: message.event,
|
459
|
+
data: JSON.parse(message.data)
|
460
|
+
};
|
461
|
+
yield ret;
|
462
|
+
} catch (error) {
|
463
|
+
throw new CozeError(`Could not parse message into JSON:${message.data}`);
|
464
|
+
}
|
465
|
+
}
|
466
|
+
/**
|
467
|
+
* Get the detailed information of the chat. | 查看对话的详细信息。
|
468
|
+
* @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
|
469
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
|
470
|
+
* @param conversation_id - Required The ID of the conversation. | 会话 ID。
|
471
|
+
* @param chat_id - Required The ID of the chat. | 对话 ID。
|
472
|
+
* @returns The data of the retrieved chat. | 检索到的对话数据。
|
473
|
+
*/ async retrieve(conversation_id, chat_id, options) {
|
474
|
+
const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
|
475
|
+
const result = await this._client.post(apiUrl, void 0, false, options);
|
476
|
+
return result.data;
|
477
|
+
}
|
478
|
+
/**
|
479
|
+
* Cancel a chat session. | 取消对话会话。
|
480
|
+
* @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
|
481
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
|
482
|
+
* @param conversation_id - Required The ID of the conversation. | 会话 ID。
|
483
|
+
* @param chat_id - Required The ID of the chat. | 对话 ID。
|
484
|
+
* @returns The data of the canceled chat. | 取消的对话数据。
|
485
|
+
*/ async cancel(conversation_id, chat_id, options) {
|
486
|
+
const apiUrl = '/v3/chat/cancel';
|
487
|
+
const payload = {
|
488
|
+
conversation_id,
|
489
|
+
chat_id
|
490
|
+
};
|
491
|
+
const result = await this._client.post(apiUrl, payload, false, options);
|
492
|
+
return result.data;
|
493
|
+
}
|
494
|
+
/**
|
495
|
+
* Submit tool outputs for a chat session. | 提交对话会话的工具输出。
|
496
|
+
* @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
|
497
|
+
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
|
498
|
+
* @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
|
499
|
+
* @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
|
500
|
+
* @param params.chat_id - Required The ID of the chat. | 对话 ID。
|
501
|
+
* @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
|
502
|
+
* @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
|
503
|
+
* @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
|
504
|
+
*/ async *submitToolOutputs(params, options) {
|
505
|
+
const { conversation_id, chat_id, ...rest } = params;
|
506
|
+
const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
|
507
|
+
const payload = {
|
508
|
+
...rest
|
509
|
+
};
|
510
|
+
if (false === params.stream) {
|
511
|
+
const response = await this._client.post(apiUrl, payload, false, options);
|
512
|
+
return response.data;
|
513
|
+
}
|
514
|
+
{
|
515
|
+
const result = await this._client.post(apiUrl, payload, true, options);
|
516
|
+
for await (const message of result)if ("done" === message.event) {
|
517
|
+
const ret = {
|
518
|
+
event: message.event,
|
519
|
+
data: '[DONE]'
|
520
|
+
};
|
521
|
+
yield ret;
|
522
|
+
} else try {
|
523
|
+
const ret = {
|
524
|
+
event: message.event,
|
525
|
+
data: JSON.parse(message.data)
|
526
|
+
};
|
527
|
+
yield ret;
|
528
|
+
} catch (error) {
|
529
|
+
throw new CozeError(`Could not parse message into JSON:${message.data}`);
|
530
|
+
}
|
531
|
+
}
|
532
|
+
}
|
533
|
+
constructor(...args){
|
534
|
+
super(...args), this.messages = new Messages(this._client);
|
535
|
+
}
|
536
|
+
}
|
537
|
+
var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
|
538
|
+
ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
|
539
|
+
ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
|
540
|
+
ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
|
541
|
+
ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
|
542
|
+
ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
|
543
|
+
ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
|
544
|
+
ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
|
545
|
+
ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
|
546
|
+
ChatEventType["DONE"] = "done";
|
547
|
+
ChatEventType["ERROR"] = "error";
|
548
|
+
return ChatEventType;
|
549
|
+
}({});
|
550
|
+
class messages_Messages extends APIResource {
|
551
|
+
/**
|
552
|
+
* Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
|
553
|
+
* @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
|
554
|
+
* @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
|
555
|
+
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
556
|
+
* @param params - Required The parameters for creating a message | 创建消息所需的参数
|
557
|
+
* @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
|
558
|
+
* @param params.content - Required The content of the message. | 消息的内容。
|
559
|
+
* @param params.content_type - Required The type of the message content. | 消息内容的类型。
|
560
|
+
* @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
|
561
|
+
* @returns Information about the new message. | 消息详情。
|
562
|
+
*/ async create(conversation_id, params, options) {
|
563
|
+
const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
|
564
|
+
const response = await this._client.post(apiUrl, params, false, options);
|
565
|
+
return response.data;
|
566
|
+
}
|
567
|
+
/**
|
568
|
+
* Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
|
569
|
+
* @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
|
570
|
+
* @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
|
571
|
+
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
572
|
+
* @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
|
573
|
+
* @param params - Required The parameters for modifying a message | 修改消息所需的参数
|
574
|
+
* @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
|
575
|
+
* @param params.content - Optional The content of the message. | 消息的内容。
|
576
|
+
* @param params.content_type - Optional The type of the message content. | 消息内容的类型。
|
577
|
+
* @returns Information about the modified message. | 消息详情。
|
578
|
+
*/ // eslint-disable-next-line max-params
|
579
|
+
async update(conversation_id, message_id, params, options) {
|
580
|
+
const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
|
581
|
+
const response = await this._client.post(apiUrl, params, false, options);
|
582
|
+
return response.message;
|
583
|
+
}
|
584
|
+
/**
|
585
|
+
* Get the detailed information of specified message. | 查看指定消息的详细信息。
|
586
|
+
* @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
|
587
|
+
* @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
|
588
|
+
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
589
|
+
* @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
|
590
|
+
* @returns Information about the message. | 消息详情。
|
591
|
+
*/ async retrieve(conversation_id, message_id, options) {
|
592
|
+
const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
|
593
|
+
const response = await this._client.get(apiUrl, null, false, options);
|
594
|
+
return response.data;
|
595
|
+
}
|
596
|
+
/**
|
597
|
+
* List messages in a conversation. | 列出会话中的消息。
|
598
|
+
* @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
|
599
|
+
* @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
|
600
|
+
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
601
|
+
* @param params - Optional The parameters for listing messages | 列出消息所需的参数
|
602
|
+
* @param params.order - Optional The order of the messages. | 消息的顺序。
|
603
|
+
* @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
|
604
|
+
* @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
|
605
|
+
* @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
|
606
|
+
* @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
|
607
|
+
* @returns A list of messages. | 消息列表。
|
608
|
+
*/ async list(conversation_id, params, options) {
|
609
|
+
const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
|
610
|
+
const response = await this._client.post(apiUrl, params, false, options);
|
611
|
+
return response;
|
612
|
+
}
|
613
|
+
/**
|
614
|
+
* Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
|
615
|
+
* @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
|
616
|
+
* @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
|
617
|
+
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
618
|
+
* @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
|
619
|
+
* @returns Details of the deleted message. | 已删除的消息详情。
|
620
|
+
*/ async delete(conversation_id, message_id, options) {
|
621
|
+
const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
|
622
|
+
const response = await this._client.post(apiUrl, void 0, false, options);
|
623
|
+
return response.data;
|
624
|
+
}
|
625
|
+
}
|
626
|
+
class Conversations extends APIResource {
|
627
|
+
/**
|
628
|
+
* Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
|
629
|
+
* @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
|
630
|
+
* @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
|
631
|
+
* @param params - Required The parameters for creating a conversation | 创建会话所需的参数
|
632
|
+
* @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
|
633
|
+
* @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
|
634
|
+
* @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
|
635
|
+
* @returns Information about the created conversation. | 会话的基础信息。
|
636
|
+
*/ async create(params, options) {
|
637
|
+
const apiUrl = '/v1/conversation/create';
|
638
|
+
const response = await this._client.post(apiUrl, params, false, options);
|
639
|
+
return response.data;
|
640
|
+
}
|
641
|
+
/**
|
642
|
+
* Get the information of specific conversation. | 通过会话 ID 查看会话信息。
|
643
|
+
* @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
|
644
|
+
* @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
|
645
|
+
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
646
|
+
* @returns Information about the conversation. | 会话的基础信息。
|
647
|
+
*/ async retrieve(conversation_id, options) {
|
648
|
+
const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
|
649
|
+
const response = await this._client.get(apiUrl, null, false, options);
|
650
|
+
return response.data;
|
651
|
+
}
|
652
|
+
/**
|
653
|
+
* List all conversations. | 列出 Bot 下所有会话。
|
654
|
+
* @param params
|
655
|
+
* @param params.bot_id - Required Bot ID. | Bot ID。
|
656
|
+
* @param params.page_num - Optional The page number. | 页码,默认值为 1。
|
657
|
+
* @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
|
658
|
+
* @returns Information about the conversations. | 会话的信息。
|
659
|
+
*/ async list(params, options) {
|
660
|
+
const apiUrl = '/v1/conversations';
|
661
|
+
const response = await this._client.get(apiUrl, params, false, options);
|
662
|
+
return response.data;
|
663
|
+
}
|
664
|
+
/**
|
665
|
+
* Clear a conversation. | 清空会话。
|
666
|
+
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
667
|
+
* @returns Information about the conversation session. | 会话的会话 ID。
|
668
|
+
*/ async clear(conversation_id, options) {
|
669
|
+
const apiUrl = `/v1/conversations/${conversation_id}/clear`;
|
670
|
+
const response = await this._client.post(apiUrl, null, false, options);
|
671
|
+
return response.data;
|
672
|
+
}
|
673
|
+
constructor(...args){
|
674
|
+
super(...args), this.messages = new messages_Messages(this._client);
|
675
|
+
}
|
676
|
+
}
|
677
|
+
function bind(fn, thisArg) {
|
678
|
+
return function() {
|
679
|
+
return fn.apply(thisArg, arguments);
|
680
|
+
};
|
681
|
+
}
|
682
|
+
// utils is a library of generic helper functions non-specific to axios
|
683
|
+
const { toString: utils_toString } = Object.prototype;
|
684
|
+
const { getPrototypeOf } = Object;
|
685
|
+
const kindOf = ((cache)=>(thing)=>{
|
686
|
+
const str = utils_toString.call(thing);
|
687
|
+
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
|
688
|
+
})(Object.create(null));
|
689
|
+
const kindOfTest = (type)=>{
|
690
|
+
type = type.toLowerCase();
|
691
|
+
return (thing)=>kindOf(thing) === type;
|
692
|
+
};
|
693
|
+
const typeOfTest = (type)=>(thing)=>typeof thing === type;
|
421
694
|
/**
|
422
|
-
*
|
695
|
+
* Determine if a value is an Array
|
423
696
|
*
|
424
|
-
* @param {
|
425
|
-
* @param {String} searchString
|
426
|
-
* @param {Number} [position= 0]
|
697
|
+
* @param {Object} val The value to test
|
427
698
|
*
|
428
|
-
* @returns {boolean}
|
429
|
-
*/ const
|
430
|
-
str = String(str);
|
431
|
-
if (void 0 === position || position > str.length) position = str.length;
|
432
|
-
position -= searchString.length;
|
433
|
-
const lastIndex = str.indexOf(searchString, position);
|
434
|
-
return -1 !== lastIndex && lastIndex === position;
|
435
|
-
};
|
699
|
+
* @returns {boolean} True if value is an Array, otherwise false
|
700
|
+
*/ const { isArray } = Array;
|
436
701
|
/**
|
437
|
-
*
|
702
|
+
* Determine if a value is undefined
|
438
703
|
*
|
439
|
-
* @param {*}
|
704
|
+
* @param {*} val The value to test
|
440
705
|
*
|
441
|
-
* @returns {
|
442
|
-
*/ const
|
443
|
-
if (!thing) return null;
|
444
|
-
if (isArray(thing)) return thing;
|
445
|
-
let i = thing.length;
|
446
|
-
if (!isNumber(i)) return null;
|
447
|
-
const arr = new Array(i);
|
448
|
-
while(i-- > 0)arr[i] = thing[i];
|
449
|
-
return arr;
|
450
|
-
};
|
706
|
+
* @returns {boolean} True if the value is undefined, otherwise false
|
707
|
+
*/ const isUndefined = typeOfTest('undefined');
|
451
708
|
/**
|
452
|
-
*
|
453
|
-
* thing passed in is an instance of Uint8Array
|
709
|
+
* Determine if a value is a Buffer
|
454
710
|
*
|
455
|
-
* @param {
|
711
|
+
* @param {*} val The value to test
|
456
712
|
*
|
457
|
-
* @returns {
|
458
|
-
*/
|
459
|
-
|
713
|
+
* @returns {boolean} True if value is a Buffer, otherwise false
|
714
|
+
*/ function isBuffer(val) {
|
715
|
+
return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
|
716
|
+
}
|
460
717
|
/**
|
461
|
-
*
|
718
|
+
* Determine if a value is an ArrayBuffer
|
462
719
|
*
|
463
|
-
* @param {
|
464
|
-
* @param {Function} fn - The function to call for each entry.
|
720
|
+
* @param {*} val The value to test
|
465
721
|
*
|
466
|
-
* @returns {
|
467
|
-
*/ const
|
468
|
-
const generator = obj && obj[Symbol.iterator];
|
469
|
-
const iterator = generator.call(obj);
|
470
|
-
let result;
|
471
|
-
while((result = iterator.next()) && !result.done){
|
472
|
-
const pair = result.value;
|
473
|
-
fn.call(obj, pair[0], pair[1]);
|
474
|
-
}
|
475
|
-
};
|
722
|
+
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
|
723
|
+
*/ const isArrayBuffer = kindOfTest('ArrayBuffer');
|
476
724
|
/**
|
477
|
-
*
|
725
|
+
* Determine if a value is a view on an ArrayBuffer
|
478
726
|
*
|
479
|
-
* @param {
|
480
|
-
* @param {string} str - The string to search.
|
727
|
+
* @param {*} val The value to test
|
481
728
|
*
|
482
|
-
* @returns {
|
483
|
-
*/
|
484
|
-
let
|
485
|
-
|
486
|
-
|
487
|
-
|
488
|
-
};
|
489
|
-
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
|
490
|
-
const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
|
491
|
-
return p1.toUpperCase() + p2;
|
492
|
-
});
|
493
|
-
/* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
|
729
|
+
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
|
730
|
+
*/ function isArrayBufferView(val) {
|
731
|
+
let result;
|
732
|
+
result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
|
733
|
+
return result;
|
734
|
+
}
|
494
735
|
/**
|
495
|
-
* Determine if a value is a
|
736
|
+
* Determine if a value is a String
|
496
737
|
*
|
497
738
|
* @param {*} val The value to test
|
498
739
|
*
|
499
|
-
* @returns {boolean} True if value is a
|
500
|
-
*/ const
|
501
|
-
const reduceDescriptors = (obj, reducer)=>{
|
502
|
-
const descriptors = Object.getOwnPropertyDescriptors(obj);
|
503
|
-
const reducedDescriptors = {};
|
504
|
-
forEach(descriptors, (descriptor, name)=>{
|
505
|
-
let ret;
|
506
|
-
if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
|
507
|
-
});
|
508
|
-
Object.defineProperties(obj, reducedDescriptors);
|
509
|
-
};
|
740
|
+
* @returns {boolean} True if value is a String, otherwise false
|
741
|
+
*/ const isString = typeOfTest('string');
|
510
742
|
/**
|
511
|
-
*
|
512
|
-
*
|
513
|
-
|
514
|
-
|
515
|
-
|
516
|
-
if (isFunction(obj) && -1 !== [
|
517
|
-
'arguments',
|
518
|
-
'caller',
|
519
|
-
'callee'
|
520
|
-
].indexOf(name)) return false;
|
521
|
-
const value = obj[name];
|
522
|
-
if (!isFunction(value)) return;
|
523
|
-
descriptor.enumerable = false;
|
524
|
-
if ('writable' in descriptor) {
|
525
|
-
descriptor.writable = false;
|
526
|
-
return;
|
527
|
-
}
|
528
|
-
if (!descriptor.set) descriptor.set = ()=>{
|
529
|
-
throw Error('Can not rewrite read-only method \'' + name + '\'');
|
530
|
-
};
|
531
|
-
});
|
532
|
-
};
|
533
|
-
const toObjectSet = (arrayOrString, delimiter)=>{
|
534
|
-
const obj = {};
|
535
|
-
const define = (arr)=>{
|
536
|
-
arr.forEach((value)=>{
|
537
|
-
obj[value] = true;
|
538
|
-
});
|
539
|
-
};
|
540
|
-
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
|
541
|
-
return obj;
|
542
|
-
};
|
543
|
-
const noop = ()=>{};
|
544
|
-
const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
|
545
|
-
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
|
546
|
-
const DIGIT = '0123456789';
|
547
|
-
const ALPHABET = {
|
548
|
-
DIGIT,
|
549
|
-
ALPHA,
|
550
|
-
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
|
551
|
-
};
|
552
|
-
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
|
553
|
-
let str = '';
|
554
|
-
const { length } = alphabet;
|
555
|
-
while(size--)str += alphabet[Math.random() * length | 0];
|
556
|
-
return str;
|
557
|
-
};
|
743
|
+
* Determine if a value is a Function
|
744
|
+
*
|
745
|
+
* @param {*} val The value to test
|
746
|
+
* @returns {boolean} True if value is a Function, otherwise false
|
747
|
+
*/ const isFunction = typeOfTest('function');
|
558
748
|
/**
|
559
|
-
*
|
749
|
+
* Determine if a value is a Number
|
560
750
|
*
|
561
|
-
* @param {
|
751
|
+
* @param {*} val The value to test
|
562
752
|
*
|
563
|
-
* @returns {boolean}
|
564
|
-
*/
|
565
|
-
|
566
|
-
|
567
|
-
|
568
|
-
|
753
|
+
* @returns {boolean} True if value is a Number, otherwise false
|
754
|
+
*/ const isNumber = typeOfTest('number');
|
755
|
+
/**
|
756
|
+
* Determine if a value is an Object
|
757
|
+
*
|
758
|
+
* @param {*} thing The value to test
|
759
|
+
*
|
760
|
+
* @returns {boolean} True if value is an Object, otherwise false
|
761
|
+
*/ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
|
762
|
+
/**
|
763
|
+
* Determine if a value is a Boolean
|
764
|
+
*
|
765
|
+
* @param {*} thing The value to test
|
766
|
+
* @returns {boolean} True if value is a Boolean, otherwise false
|
767
|
+
*/ const isBoolean = (thing)=>true === thing || false === thing;
|
768
|
+
/**
|
769
|
+
* Determine if a value is a plain Object
|
770
|
+
*
|
771
|
+
* @param {*} val The value to test
|
772
|
+
*
|
773
|
+
* @returns {boolean} True if value is a plain Object, otherwise false
|
774
|
+
*/ const utils_isPlainObject = (val)=>{
|
775
|
+
if ('object' !== kindOf(val)) return false;
|
776
|
+
const prototype = getPrototypeOf(val);
|
777
|
+
return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
|
778
|
+
};
|
779
|
+
/**
|
780
|
+
* Determine if a value is a Date
|
781
|
+
*
|
782
|
+
* @param {*} val The value to test
|
783
|
+
*
|
784
|
+
* @returns {boolean} True if value is a Date, otherwise false
|
785
|
+
*/ const isDate = kindOfTest('Date');
|
786
|
+
/**
|
787
|
+
* Determine if a value is a File
|
788
|
+
*
|
789
|
+
* @param {*} val The value to test
|
790
|
+
*
|
791
|
+
* @returns {boolean} True if value is a File, otherwise false
|
792
|
+
*/ const isFile = kindOfTest('File');
|
793
|
+
/**
|
794
|
+
* Determine if a value is a Blob
|
795
|
+
*
|
796
|
+
* @param {*} val The value to test
|
797
|
+
*
|
798
|
+
* @returns {boolean} True if value is a Blob, otherwise false
|
799
|
+
*/ const isBlob = kindOfTest('Blob');
|
800
|
+
/**
|
801
|
+
* Determine if a value is a FileList
|
802
|
+
*
|
803
|
+
* @param {*} val The value to test
|
804
|
+
*
|
805
|
+
* @returns {boolean} True if value is a File, otherwise false
|
806
|
+
*/ const utils_isFileList = kindOfTest('FileList');
|
807
|
+
/**
|
808
|
+
* Determine if a value is a Stream
|
809
|
+
*
|
810
|
+
* @param {*} val The value to test
|
811
|
+
*
|
812
|
+
* @returns {boolean} True if value is a Stream, otherwise false
|
813
|
+
*/ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
|
814
|
+
/**
|
815
|
+
* Determine if a value is a FormData
|
816
|
+
*
|
817
|
+
* @param {*} thing The value to test
|
818
|
+
*
|
819
|
+
* @returns {boolean} True if value is an FormData, otherwise false
|
820
|
+
*/ const utils_isFormData = (thing)=>{
|
821
|
+
let kind;
|
822
|
+
return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
|
823
|
+
'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
|
824
|
+
};
|
825
|
+
/**
|
826
|
+
* Determine if a value is a URLSearchParams object
|
827
|
+
*
|
828
|
+
* @param {*} val The value to test
|
829
|
+
*
|
830
|
+
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
|
831
|
+
*/ const isURLSearchParams = kindOfTest('URLSearchParams');
|
832
|
+
const [isReadableStream, isRequest, isResponse, isHeaders] = [
|
833
|
+
'ReadableStream',
|
834
|
+
'Request',
|
835
|
+
'Response',
|
836
|
+
'Headers'
|
837
|
+
].map(kindOfTest);
|
838
|
+
/**
|
839
|
+
* Trim excess whitespace off the beginning and end of a string
|
840
|
+
*
|
841
|
+
* @param {String} str The String to trim
|
842
|
+
*
|
843
|
+
* @returns {String} The String freed of excess whitespace
|
844
|
+
*/ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
|
845
|
+
/**
|
846
|
+
* Iterate over an Array or an Object invoking a function for each item.
|
847
|
+
*
|
848
|
+
* If `obj` is an Array callback will be called passing
|
849
|
+
* the value, index, and complete array for each item.
|
850
|
+
*
|
851
|
+
* If 'obj' is an Object callback will be called passing
|
852
|
+
* the value, key, and complete object for each property.
|
853
|
+
*
|
854
|
+
* @param {Object|Array} obj The object to iterate
|
855
|
+
* @param {Function} fn The callback to invoke for each item
|
856
|
+
*
|
857
|
+
* @param {Boolean} [allOwnKeys = false]
|
858
|
+
* @returns {any}
|
859
|
+
*/ function forEach(obj, fn, { allOwnKeys = false } = {}) {
|
860
|
+
// Don't bother if no value provided
|
861
|
+
if (null == obj) return;
|
862
|
+
let i;
|
863
|
+
let l;
|
864
|
+
// Force an array if not already something iterable
|
865
|
+
if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
|
866
|
+
obj
|
867
|
+
];
|
868
|
+
if (isArray(obj)) // Iterate over array values
|
869
|
+
for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
|
870
|
+
else {
|
871
|
+
// Iterate over object keys
|
872
|
+
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
|
873
|
+
const len = keys.length;
|
874
|
+
let key;
|
875
|
+
for(i = 0; i < len; i++){
|
876
|
+
key = keys[i];
|
877
|
+
fn.call(null, obj[key], key, obj);
|
878
|
+
}
|
879
|
+
}
|
880
|
+
}
|
881
|
+
function findKey(obj, key) {
|
882
|
+
key = key.toLowerCase();
|
883
|
+
const keys = Object.keys(obj);
|
884
|
+
let i = keys.length;
|
885
|
+
let _key;
|
886
|
+
while(i-- > 0){
|
887
|
+
_key = keys[i];
|
888
|
+
if (key === _key.toLowerCase()) return _key;
|
889
|
+
}
|
890
|
+
return null;
|
891
|
+
}
|
892
|
+
const _global = (()=>{
|
893
|
+
/*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
|
894
|
+
return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
|
895
|
+
})();
|
896
|
+
const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
|
897
|
+
/**
|
898
|
+
* Accepts varargs expecting each argument to be an object, then
|
899
|
+
* immutably merges the properties of each object and returns result.
|
900
|
+
*
|
901
|
+
* When multiple objects contain the same key the later object in
|
902
|
+
* the arguments list will take precedence.
|
903
|
+
*
|
904
|
+
* Example:
|
905
|
+
*
|
906
|
+
* ```js
|
907
|
+
* var result = merge({foo: 123}, {foo: 456});
|
908
|
+
* console.log(result.foo); // outputs 456
|
909
|
+
* ```
|
910
|
+
*
|
911
|
+
* @param {Object} obj1 Object to merge
|
912
|
+
*
|
913
|
+
* @returns {Object} Result of all merge properties
|
914
|
+
*/ function utils_merge() {
|
915
|
+
const { caseless } = isContextDefined(this) && this || {};
|
916
|
+
const result = {};
|
917
|
+
const assignValue = (val, key)=>{
|
918
|
+
const targetKey = caseless && findKey(result, key) || key;
|
919
|
+
if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
|
920
|
+
else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
|
921
|
+
else if (isArray(val)) result[targetKey] = val.slice();
|
922
|
+
else result[targetKey] = val;
|
923
|
+
};
|
924
|
+
for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
|
925
|
+
return result;
|
926
|
+
}
|
927
|
+
/**
|
928
|
+
* Extends object a by mutably adding to it the properties of object b.
|
929
|
+
*
|
930
|
+
* @param {Object} a The object to be extended
|
931
|
+
* @param {Object} b The object to copy properties from
|
932
|
+
* @param {Object} thisArg The object to bind function to
|
933
|
+
*
|
934
|
+
* @param {Boolean} [allOwnKeys]
|
935
|
+
* @returns {Object} The resulting value of object a
|
936
|
+
*/ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
|
937
|
+
forEach(b, (val, key)=>{
|
938
|
+
if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
|
939
|
+
else a[key] = val;
|
940
|
+
}, {
|
941
|
+
allOwnKeys
|
942
|
+
});
|
943
|
+
return a;
|
944
|
+
};
|
945
|
+
/**
|
946
|
+
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
|
947
|
+
*
|
948
|
+
* @param {string} content with BOM
|
949
|
+
*
|
950
|
+
* @returns {string} content value without BOM
|
951
|
+
*/ const stripBOM = (content)=>{
|
952
|
+
if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
|
953
|
+
return content;
|
954
|
+
};
|
955
|
+
/**
|
956
|
+
* Inherit the prototype methods from one constructor into another
|
957
|
+
* @param {function} constructor
|
958
|
+
* @param {function} superConstructor
|
959
|
+
* @param {object} [props]
|
960
|
+
* @param {object} [descriptors]
|
961
|
+
*
|
962
|
+
* @returns {void}
|
963
|
+
*/ const inherits = (constructor, superConstructor, props, descriptors)=>{
|
964
|
+
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
|
965
|
+
constructor.prototype.constructor = constructor;
|
966
|
+
Object.defineProperty(constructor, 'super', {
|
967
|
+
value: superConstructor.prototype
|
968
|
+
});
|
969
|
+
props && Object.assign(constructor.prototype, props);
|
970
|
+
};
|
971
|
+
/**
|
972
|
+
* Resolve object with deep prototype chain to a flat object
|
973
|
+
* @param {Object} sourceObj source object
|
974
|
+
* @param {Object} [destObj]
|
975
|
+
* @param {Function|Boolean} [filter]
|
976
|
+
* @param {Function} [propFilter]
|
977
|
+
*
|
978
|
+
* @returns {Object}
|
979
|
+
*/ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
|
980
|
+
let props;
|
981
|
+
let i;
|
982
|
+
let prop;
|
983
|
+
const merged = {};
|
984
|
+
destObj = destObj || {};
|
985
|
+
// eslint-disable-next-line no-eq-null,eqeqeq
|
986
|
+
if (null == sourceObj) return destObj;
|
987
|
+
do {
|
988
|
+
props = Object.getOwnPropertyNames(sourceObj);
|
989
|
+
i = props.length;
|
990
|
+
while(i-- > 0){
|
991
|
+
prop = props[i];
|
992
|
+
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
|
993
|
+
destObj[prop] = sourceObj[prop];
|
994
|
+
merged[prop] = true;
|
995
|
+
}
|
996
|
+
}
|
997
|
+
sourceObj = false !== filter && getPrototypeOf(sourceObj);
|
998
|
+
}while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
|
999
|
+
return destObj;
|
1000
|
+
};
|
1001
|
+
/**
|
1002
|
+
* Determines whether a string ends with the characters of a specified string
|
1003
|
+
*
|
1004
|
+
* @param {String} str
|
1005
|
+
* @param {String} searchString
|
1006
|
+
* @param {Number} [position= 0]
|
1007
|
+
*
|
1008
|
+
* @returns {boolean}
|
1009
|
+
*/ const endsWith = (str, searchString, position)=>{
|
1010
|
+
str = String(str);
|
1011
|
+
if (void 0 === position || position > str.length) position = str.length;
|
1012
|
+
position -= searchString.length;
|
1013
|
+
const lastIndex = str.indexOf(searchString, position);
|
1014
|
+
return -1 !== lastIndex && lastIndex === position;
|
1015
|
+
};
|
1016
|
+
/**
|
1017
|
+
* Returns new array from array like object or null if failed
|
1018
|
+
*
|
1019
|
+
* @param {*} [thing]
|
1020
|
+
*
|
1021
|
+
* @returns {?Array}
|
1022
|
+
*/ const toArray = (thing)=>{
|
1023
|
+
if (!thing) return null;
|
1024
|
+
if (isArray(thing)) return thing;
|
1025
|
+
let i = thing.length;
|
1026
|
+
if (!isNumber(i)) return null;
|
1027
|
+
const arr = new Array(i);
|
1028
|
+
while(i-- > 0)arr[i] = thing[i];
|
1029
|
+
return arr;
|
1030
|
+
};
|
1031
|
+
/**
|
1032
|
+
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
|
1033
|
+
* thing passed in is an instance of Uint8Array
|
1034
|
+
*
|
1035
|
+
* @param {TypedArray}
|
1036
|
+
*
|
1037
|
+
* @returns {Array}
|
1038
|
+
*/ // eslint-disable-next-line func-names
|
1039
|
+
const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
|
1040
|
+
/**
|
1041
|
+
* For each entry in the object, call the function with the key and value.
|
1042
|
+
*
|
1043
|
+
* @param {Object<any, any>} obj - The object to iterate over.
|
1044
|
+
* @param {Function} fn - The function to call for each entry.
|
1045
|
+
*
|
1046
|
+
* @returns {void}
|
1047
|
+
*/ const forEachEntry = (obj, fn)=>{
|
1048
|
+
const generator = obj && obj[Symbol.iterator];
|
1049
|
+
const iterator = generator.call(obj);
|
1050
|
+
let result;
|
1051
|
+
while((result = iterator.next()) && !result.done){
|
1052
|
+
const pair = result.value;
|
1053
|
+
fn.call(obj, pair[0], pair[1]);
|
1054
|
+
}
|
1055
|
+
};
|
1056
|
+
/**
|
1057
|
+
* It takes a regular expression and a string, and returns an array of all the matches
|
1058
|
+
*
|
1059
|
+
* @param {string} regExp - The regular expression to match against.
|
1060
|
+
* @param {string} str - The string to search.
|
1061
|
+
*
|
1062
|
+
* @returns {Array<boolean>}
|
1063
|
+
*/ const matchAll = (regExp, str)=>{
|
1064
|
+
let matches;
|
1065
|
+
const arr = [];
|
1066
|
+
while(null !== (matches = regExp.exec(str)))arr.push(matches);
|
1067
|
+
return arr;
|
1068
|
+
};
|
1069
|
+
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
|
1070
|
+
const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
|
1071
|
+
return p1.toUpperCase() + p2;
|
1072
|
+
});
|
1073
|
+
/* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
|
1074
|
+
/**
|
1075
|
+
* Determine if a value is a RegExp object
|
1076
|
+
*
|
1077
|
+
* @param {*} val The value to test
|
1078
|
+
*
|
1079
|
+
* @returns {boolean} True if value is a RegExp object, otherwise false
|
1080
|
+
*/ const isRegExp = kindOfTest('RegExp');
|
1081
|
+
const reduceDescriptors = (obj, reducer)=>{
|
1082
|
+
const descriptors = Object.getOwnPropertyDescriptors(obj);
|
1083
|
+
const reducedDescriptors = {};
|
1084
|
+
forEach(descriptors, (descriptor, name)=>{
|
1085
|
+
let ret;
|
1086
|
+
if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
|
1087
|
+
});
|
1088
|
+
Object.defineProperties(obj, reducedDescriptors);
|
1089
|
+
};
|
1090
|
+
/**
|
1091
|
+
* Makes all methods read-only
|
1092
|
+
* @param {Object} obj
|
1093
|
+
*/ const freezeMethods = (obj)=>{
|
1094
|
+
reduceDescriptors(obj, (descriptor, name)=>{
|
1095
|
+
// skip restricted props in strict mode
|
1096
|
+
if (isFunction(obj) && -1 !== [
|
1097
|
+
'arguments',
|
1098
|
+
'caller',
|
1099
|
+
'callee'
|
1100
|
+
].indexOf(name)) return false;
|
1101
|
+
const value = obj[name];
|
1102
|
+
if (!isFunction(value)) return;
|
1103
|
+
descriptor.enumerable = false;
|
1104
|
+
if ('writable' in descriptor) {
|
1105
|
+
descriptor.writable = false;
|
1106
|
+
return;
|
1107
|
+
}
|
1108
|
+
if (!descriptor.set) descriptor.set = ()=>{
|
1109
|
+
throw Error('Can not rewrite read-only method \'' + name + '\'');
|
1110
|
+
};
|
1111
|
+
});
|
1112
|
+
};
|
1113
|
+
const toObjectSet = (arrayOrString, delimiter)=>{
|
1114
|
+
const obj = {};
|
1115
|
+
const define = (arr)=>{
|
1116
|
+
arr.forEach((value)=>{
|
1117
|
+
obj[value] = true;
|
1118
|
+
});
|
1119
|
+
};
|
1120
|
+
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
|
1121
|
+
return obj;
|
1122
|
+
};
|
1123
|
+
const noop = ()=>{};
|
1124
|
+
const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
|
1125
|
+
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
|
1126
|
+
const DIGIT = '0123456789';
|
1127
|
+
const ALPHABET = {
|
1128
|
+
DIGIT,
|
1129
|
+
ALPHA,
|
1130
|
+
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
|
1131
|
+
};
|
1132
|
+
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
|
1133
|
+
let str = '';
|
1134
|
+
const { length } = alphabet;
|
1135
|
+
while(size--)str += alphabet[Math.random() * length | 0];
|
1136
|
+
return str;
|
1137
|
+
};
|
1138
|
+
/**
|
1139
|
+
* If the thing is a FormData object, return true, otherwise return false.
|
1140
|
+
*
|
1141
|
+
* @param {unknown} thing - The thing to check.
|
1142
|
+
*
|
1143
|
+
* @returns {boolean}
|
1144
|
+
*/ function isSpecCompliantForm(thing) {
|
1145
|
+
return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
|
1146
|
+
}
|
1147
|
+
const toJSONObject = (obj)=>{
|
1148
|
+
const stack = new Array(10);
|
569
1149
|
const visit = (source, i)=>{
|
570
1150
|
if (isObject(source)) {
|
571
1151
|
if (stack.indexOf(source) >= 0) return;
|
@@ -612,7 +1192,7 @@ const asap = 'undefined' != typeof queueMicrotask ? queueMicrotask.bind(_global)
|
|
612
1192
|
isNumber,
|
613
1193
|
isBoolean,
|
614
1194
|
isObject,
|
615
|
-
isPlainObject,
|
1195
|
+
isPlainObject: utils_isPlainObject,
|
616
1196
|
isReadableStream,
|
617
1197
|
isRequest,
|
618
1198
|
isResponse,
|
@@ -1810,7 +2390,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
|
|
1810
2390
|
* @param {Object} config2
|
1811
2391
|
*
|
1812
2392
|
* @returns {Object} New object resulting from merging config2 to config1
|
1813
|
-
*/ function
|
2393
|
+
*/ function mergeConfig_mergeConfig(config1, config2) {
|
1814
2394
|
// eslint-disable-next-line no-param-reassign
|
1815
2395
|
config2 = config2 || {};
|
1816
2396
|
const config = {};
|
@@ -1880,7 +2460,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
|
|
1880
2460
|
return config;
|
1881
2461
|
}
|
1882
2462
|
/* ESM default export */ const resolveConfig = (config)=>{
|
1883
|
-
const newConfig =
|
2463
|
+
const newConfig = mergeConfig_mergeConfig({}, config);
|
1884
2464
|
let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
|
1885
2465
|
newConfig.headers = headers = AxiosHeaders.from(headers);
|
1886
2466
|
newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
|
@@ -2486,7 +3066,7 @@ const Axios_validators = helpers_validator.validators;
|
|
2486
3066
|
config = config || {};
|
2487
3067
|
config.url = configOrUrl;
|
2488
3068
|
} else config = configOrUrl || {};
|
2489
|
-
config =
|
3069
|
+
config = mergeConfig_mergeConfig(this.defaults, config);
|
2490
3070
|
const { transitional, paramsSerializer, headers } = config;
|
2491
3071
|
if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
|
2492
3072
|
silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
|
@@ -2564,868 +3144,301 @@ const Axios_validators = helpers_validator.validators;
|
|
2564
3144
|
return Promise.reject(error);
|
2565
3145
|
}
|
2566
3146
|
i = 0;
|
2567
|
-
len = responseInterceptorChain.length;
|
2568
|
-
while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
|
2569
|
-
return promise;
|
2570
|
-
}
|
2571
|
-
getUri(config) {
|
2572
|
-
config = mergeConfig(this.defaults, config);
|
2573
|
-
const fullPath = buildFullPath(config.baseURL, config.url);
|
2574
|
-
return buildURL(fullPath, config.params, config.paramsSerializer);
|
2575
|
-
}
|
2576
|
-
}
|
2577
|
-
// Provide aliases for supported request methods
|
2578
|
-
utils.forEach([
|
2579
|
-
'delete',
|
2580
|
-
'get',
|
2581
|
-
'head',
|
2582
|
-
'options'
|
2583
|
-
], function(method) {
|
2584
|
-
/*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
|
2585
|
-
return this.request(mergeConfig(config || {}, {
|
2586
|
-
method,
|
2587
|
-
url,
|
2588
|
-
data: (config || {}).data
|
2589
|
-
}));
|
2590
|
-
};
|
2591
|
-
});
|
2592
|
-
utils.forEach([
|
2593
|
-
'post',
|
2594
|
-
'put',
|
2595
|
-
'patch'
|
2596
|
-
], function(method) {
|
2597
|
-
/*eslint func-names:0*/ function generateHTTPMethod(isForm) {
|
2598
|
-
return function(url, data, config) {
|
2599
|
-
return this.request(mergeConfig(config || {}, {
|
2600
|
-
method,
|
2601
|
-
headers: isForm ? {
|
2602
|
-
'Content-Type': 'multipart/form-data'
|
2603
|
-
} : {},
|
2604
|
-
url,
|
2605
|
-
data
|
2606
|
-
}));
|
2607
|
-
};
|
2608
|
-
}
|
2609
|
-
Axios_Axios.prototype[method] = generateHTTPMethod();
|
2610
|
-
Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
|
2611
|
-
});
|
2612
|
-
/* ESM default export */ const Axios = Axios_Axios;
|
2613
|
-
/**
|
2614
|
-
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
2615
|
-
*
|
2616
|
-
* @param {Function} executor The executor function.
|
2617
|
-
*
|
2618
|
-
* @returns {CancelToken}
|
2619
|
-
*/ class CancelToken_CancelToken {
|
2620
|
-
constructor(executor){
|
2621
|
-
if ('function' != typeof executor) throw new TypeError('executor must be a function.');
|
2622
|
-
let resolvePromise;
|
2623
|
-
this.promise = new Promise(function(resolve) {
|
2624
|
-
resolvePromise = resolve;
|
2625
|
-
});
|
2626
|
-
const token = this;
|
2627
|
-
// eslint-disable-next-line func-names
|
2628
|
-
this.promise.then((cancel)=>{
|
2629
|
-
if (!token._listeners) return;
|
2630
|
-
let i = token._listeners.length;
|
2631
|
-
while(i-- > 0)token._listeners[i](cancel);
|
2632
|
-
token._listeners = null;
|
2633
|
-
});
|
2634
|
-
// eslint-disable-next-line func-names
|
2635
|
-
this.promise.then = (onfulfilled)=>{
|
2636
|
-
let _resolve;
|
2637
|
-
// eslint-disable-next-line func-names
|
2638
|
-
const promise = new Promise((resolve)=>{
|
2639
|
-
token.subscribe(resolve);
|
2640
|
-
_resolve = resolve;
|
2641
|
-
}).then(onfulfilled);
|
2642
|
-
promise.cancel = function() {
|
2643
|
-
token.unsubscribe(_resolve);
|
2644
|
-
};
|
2645
|
-
return promise;
|
2646
|
-
};
|
2647
|
-
executor(function(message, config, request) {
|
2648
|
-
if (token.reason) // Cancellation has already been requested
|
2649
|
-
return;
|
2650
|
-
token.reason = new CanceledError(message, config, request);
|
2651
|
-
resolvePromise(token.reason);
|
2652
|
-
});
|
2653
|
-
}
|
2654
|
-
/**
|
2655
|
-
* Throws a `CanceledError` if cancellation has been requested.
|
2656
|
-
*/ throwIfRequested() {
|
2657
|
-
if (this.reason) throw this.reason;
|
2658
|
-
}
|
2659
|
-
/**
|
2660
|
-
* Subscribe to the cancel signal
|
2661
|
-
*/ subscribe(listener) {
|
2662
|
-
if (this.reason) {
|
2663
|
-
listener(this.reason);
|
2664
|
-
return;
|
2665
|
-
}
|
2666
|
-
if (this._listeners) this._listeners.push(listener);
|
2667
|
-
else this._listeners = [
|
2668
|
-
listener
|
2669
|
-
];
|
2670
|
-
}
|
2671
|
-
/**
|
2672
|
-
* Unsubscribe from the cancel signal
|
2673
|
-
*/ unsubscribe(listener) {
|
2674
|
-
if (!this._listeners) return;
|
2675
|
-
const index = this._listeners.indexOf(listener);
|
2676
|
-
if (-1 !== index) this._listeners.splice(index, 1);
|
2677
|
-
}
|
2678
|
-
toAbortSignal() {
|
2679
|
-
const controller = new AbortController();
|
2680
|
-
const abort = (err)=>{
|
2681
|
-
controller.abort(err);
|
2682
|
-
};
|
2683
|
-
this.subscribe(abort);
|
2684
|
-
controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
|
2685
|
-
return controller.signal;
|
2686
|
-
}
|
2687
|
-
/**
|
2688
|
-
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
2689
|
-
* cancels the `CancelToken`.
|
2690
|
-
*/ static source() {
|
2691
|
-
let cancel;
|
2692
|
-
const token = new CancelToken_CancelToken(function(c) {
|
2693
|
-
cancel = c;
|
2694
|
-
});
|
2695
|
-
return {
|
2696
|
-
token,
|
2697
|
-
cancel
|
2698
|
-
};
|
2699
|
-
}
|
2700
|
-
}
|
2701
|
-
/* ESM default export */ const CancelToken = CancelToken_CancelToken;
|
2702
|
-
/**
|
2703
|
-
* Syntactic sugar for invoking a function and expanding an array for arguments.
|
2704
|
-
*
|
2705
|
-
* Common use case would be to use `Function.prototype.apply`.
|
2706
|
-
*
|
2707
|
-
* ```js
|
2708
|
-
* function f(x, y, z) {}
|
2709
|
-
* var args = [1, 2, 3];
|
2710
|
-
* f.apply(null, args);
|
2711
|
-
* ```
|
2712
|
-
*
|
2713
|
-
* With `spread` this example can be re-written.
|
2714
|
-
*
|
2715
|
-
* ```js
|
2716
|
-
* spread(function(x, y, z) {})([1, 2, 3]);
|
2717
|
-
* ```
|
2718
|
-
*
|
2719
|
-
* @param {Function} callback
|
2720
|
-
*
|
2721
|
-
* @returns {Function}
|
2722
|
-
*/ function spread(callback) {
|
2723
|
-
return function(arr) {
|
2724
|
-
return callback.apply(null, arr);
|
2725
|
-
};
|
2726
|
-
}
|
2727
|
-
/**
|
2728
|
-
* Determines whether the payload is an error thrown by Axios
|
2729
|
-
*
|
2730
|
-
* @param {*} payload The value to test
|
2731
|
-
*
|
2732
|
-
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
|
2733
|
-
*/ function isAxiosError(payload) {
|
2734
|
-
return utils.isObject(payload) && true === payload.isAxiosError;
|
2735
|
-
}
|
2736
|
-
const HttpStatusCode = {
|
2737
|
-
Continue: 100,
|
2738
|
-
SwitchingProtocols: 101,
|
2739
|
-
Processing: 102,
|
2740
|
-
EarlyHints: 103,
|
2741
|
-
Ok: 200,
|
2742
|
-
Created: 201,
|
2743
|
-
Accepted: 202,
|
2744
|
-
NonAuthoritativeInformation: 203,
|
2745
|
-
NoContent: 204,
|
2746
|
-
ResetContent: 205,
|
2747
|
-
PartialContent: 206,
|
2748
|
-
MultiStatus: 207,
|
2749
|
-
AlreadyReported: 208,
|
2750
|
-
ImUsed: 226,
|
2751
|
-
MultipleChoices: 300,
|
2752
|
-
MovedPermanently: 301,
|
2753
|
-
Found: 302,
|
2754
|
-
SeeOther: 303,
|
2755
|
-
NotModified: 304,
|
2756
|
-
UseProxy: 305,
|
2757
|
-
Unused: 306,
|
2758
|
-
TemporaryRedirect: 307,
|
2759
|
-
PermanentRedirect: 308,
|
2760
|
-
BadRequest: 400,
|
2761
|
-
Unauthorized: 401,
|
2762
|
-
PaymentRequired: 402,
|
2763
|
-
Forbidden: 403,
|
2764
|
-
NotFound: 404,
|
2765
|
-
MethodNotAllowed: 405,
|
2766
|
-
NotAcceptable: 406,
|
2767
|
-
ProxyAuthenticationRequired: 407,
|
2768
|
-
RequestTimeout: 408,
|
2769
|
-
Conflict: 409,
|
2770
|
-
Gone: 410,
|
2771
|
-
LengthRequired: 411,
|
2772
|
-
PreconditionFailed: 412,
|
2773
|
-
PayloadTooLarge: 413,
|
2774
|
-
UriTooLong: 414,
|
2775
|
-
UnsupportedMediaType: 415,
|
2776
|
-
RangeNotSatisfiable: 416,
|
2777
|
-
ExpectationFailed: 417,
|
2778
|
-
ImATeapot: 418,
|
2779
|
-
MisdirectedRequest: 421,
|
2780
|
-
UnprocessableEntity: 422,
|
2781
|
-
Locked: 423,
|
2782
|
-
FailedDependency: 424,
|
2783
|
-
TooEarly: 425,
|
2784
|
-
UpgradeRequired: 426,
|
2785
|
-
PreconditionRequired: 428,
|
2786
|
-
TooManyRequests: 429,
|
2787
|
-
RequestHeaderFieldsTooLarge: 431,
|
2788
|
-
UnavailableForLegalReasons: 451,
|
2789
|
-
InternalServerError: 500,
|
2790
|
-
NotImplemented: 501,
|
2791
|
-
BadGateway: 502,
|
2792
|
-
ServiceUnavailable: 503,
|
2793
|
-
GatewayTimeout: 504,
|
2794
|
-
HttpVersionNotSupported: 505,
|
2795
|
-
VariantAlsoNegotiates: 506,
|
2796
|
-
InsufficientStorage: 507,
|
2797
|
-
LoopDetected: 508,
|
2798
|
-
NotExtended: 510,
|
2799
|
-
NetworkAuthenticationRequired: 511
|
2800
|
-
};
|
2801
|
-
Object.entries(HttpStatusCode).forEach(([key, value])=>{
|
2802
|
-
HttpStatusCode[value] = key;
|
2803
|
-
});
|
2804
|
-
/* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
|
2805
|
-
/**
|
2806
|
-
* Create an instance of Axios
|
2807
|
-
*
|
2808
|
-
* @param {Object} defaultConfig The default config for the instance
|
2809
|
-
*
|
2810
|
-
* @returns {Axios} A new instance of Axios
|
2811
|
-
*/ function createInstance(defaultConfig) {
|
2812
|
-
const context = new Axios(defaultConfig);
|
2813
|
-
const instance = bind(Axios.prototype.request, context);
|
2814
|
-
// Copy axios.prototype to instance
|
2815
|
-
utils.extend(instance, Axios.prototype, context, {
|
2816
|
-
allOwnKeys: true
|
2817
|
-
});
|
2818
|
-
// Copy context to instance
|
2819
|
-
utils.extend(instance, context, null, {
|
2820
|
-
allOwnKeys: true
|
2821
|
-
});
|
2822
|
-
// Factory for creating new instances
|
2823
|
-
instance.create = function(instanceConfig) {
|
2824
|
-
return createInstance(mergeConfig(defaultConfig, instanceConfig));
|
2825
|
-
};
|
2826
|
-
return instance;
|
2827
|
-
}
|
2828
|
-
// Create the default instance to be exported
|
2829
|
-
const axios = createInstance(defaults);
|
2830
|
-
// Expose Axios class to allow class inheritance
|
2831
|
-
axios.Axios = Axios;
|
2832
|
-
// Expose Cancel & CancelToken
|
2833
|
-
axios.CanceledError = CanceledError;
|
2834
|
-
axios.CancelToken = CancelToken;
|
2835
|
-
axios.isCancel = isCancel;
|
2836
|
-
axios.VERSION = VERSION;
|
2837
|
-
axios.toFormData = toFormData;
|
2838
|
-
// Expose AxiosError class
|
2839
|
-
axios.AxiosError = core_AxiosError;
|
2840
|
-
// alias for CanceledError for backward compatibility
|
2841
|
-
axios.Cancel = axios.CanceledError;
|
2842
|
-
// Expose all/spread
|
2843
|
-
axios.all = function(promises) {
|
2844
|
-
return Promise.all(promises);
|
2845
|
-
};
|
2846
|
-
axios.spread = spread;
|
2847
|
-
// Expose isAxiosError
|
2848
|
-
axios.isAxiosError = isAxiosError;
|
2849
|
-
// Expose mergeConfig
|
2850
|
-
axios.mergeConfig = mergeConfig;
|
2851
|
-
axios.AxiosHeaders = AxiosHeaders;
|
2852
|
-
axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
|
2853
|
-
axios.getAdapter = adapters_adapters.getAdapter;
|
2854
|
-
axios.HttpStatusCode = helpers_HttpStatusCode;
|
2855
|
-
axios.default = axios;
|
2856
|
-
// this module should only have a default export
|
2857
|
-
/* ESM default export */ const lib_axios = axios;
|
2858
|
-
// This module is intended to unwrap Axios default export as named.
|
2859
|
-
// Keep top-level export same with static properties
|
2860
|
-
// so that it can keep same with es module or cjs
|
2861
|
-
const { Axios: axios_Axios, AxiosError: axios_AxiosError, CanceledError: axios_CanceledError, isCancel: axios_isCancel, CancelToken: axios_CancelToken, VERSION: axios_VERSION, all: axios_all, Cancel, isAxiosError: axios_isAxiosError, spread: axios_spread, toFormData: axios_toFormData, AxiosHeaders: axios_AxiosHeaders, HttpStatusCode: axios_HttpStatusCode, formToJSON, getAdapter, mergeConfig: axios_mergeConfig } = lib_axios;
|
2862
|
-
// EXTERNAL MODULE: os (ignored)
|
2863
|
-
var os_ignored_ = __webpack_require__("?9caf");
|
2864
|
-
// EXTERNAL MODULE: crypto (ignored)
|
2865
|
-
__webpack_require__("?e272");
|
2866
|
-
// EXTERNAL MODULE: jsonwebtoken (ignored)
|
2867
|
-
__webpack_require__("?5742");
|
2868
|
-
class APIResource {
|
2869
|
-
constructor(client){
|
2870
|
-
this._client = client;
|
2871
|
-
}
|
2872
|
-
}
|
2873
|
-
/* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
|
2874
|
-
/**
|
2875
|
-
* Create a new agent. | 调用接口创建一个新的智能体。
|
2876
|
-
* @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
|
2877
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
|
2878
|
-
* @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
|
2879
|
-
* @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
|
2880
|
-
* @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
|
2881
|
-
* @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
|
2882
|
-
* @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
|
2883
|
-
* @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
|
2884
|
-
* @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
|
2885
|
-
* @returns Information about the created bot. | 创建的 Bot 信息。
|
2886
|
-
*/ async create(params, options) {
|
2887
|
-
const apiUrl = '/v1/bot/create';
|
2888
|
-
const result = await this._client.post(apiUrl, params, false, options);
|
2889
|
-
return result.data;
|
2890
|
-
}
|
2891
|
-
/**
|
2892
|
-
* Update the configuration of an agent. | 调用接口修改智能体的配置。
|
2893
|
-
* @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
|
2894
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
|
2895
|
-
* @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
|
2896
|
-
* @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
|
2897
|
-
* @param params.name - Optional The name of the agent. | Bot 的名称。
|
2898
|
-
* @param params.description - Optional The description of the agent. | Bot 的描述信息。
|
2899
|
-
* @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
|
2900
|
-
* @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
|
2901
|
-
* @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
|
2902
|
-
* @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
|
2903
|
-
* @returns Undefined | 无返回值
|
2904
|
-
*/ async update(params, options) {
|
2905
|
-
const apiUrl = '/v1/bot/update';
|
2906
|
-
const result = await this._client.post(apiUrl, params, false, options);
|
2907
|
-
return result.data;
|
2908
|
-
}
|
2909
|
-
/**
|
2910
|
-
* Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
|
2911
|
-
* @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
|
2912
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
|
2913
|
-
* @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
|
2914
|
-
* @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
|
2915
|
-
* @param params.page_size - Optional Pagination size. | 分页大小。
|
2916
|
-
* @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
|
2917
|
-
* @returns List of published bots. | 已发布的 Bot 列表。
|
2918
|
-
*/ async list(params, options) {
|
2919
|
-
const apiUrl = '/v1/space/published_bots_list';
|
2920
|
-
const result = await this._client.get(apiUrl, params, false, options);
|
2921
|
-
return result.data;
|
2922
|
-
}
|
2923
|
-
/**
|
2924
|
-
* Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
|
2925
|
-
* @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
|
2926
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
|
2927
|
-
* @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
|
2928
|
-
* @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
|
2929
|
-
* @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
|
2930
|
-
* @returns Undefined | 无返回值
|
2931
|
-
*/ async publish(params, options) {
|
2932
|
-
const apiUrl = '/v1/bot/publish';
|
2933
|
-
const result = await this._client.post(apiUrl, params, false, options);
|
2934
|
-
return result.data;
|
2935
|
-
}
|
2936
|
-
/**
|
2937
|
-
* Get the configuration information of the agent. | 获取指定智能体的配置信息。
|
2938
|
-
* @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
|
2939
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
|
2940
|
-
* @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
|
2941
|
-
* @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
|
2942
|
-
* @returns Information about the bot. | Bot 的配置信息。
|
2943
|
-
*/ async retrieve(params, options) {
|
2944
|
-
const apiUrl = '/v1/bot/get_online_info';
|
2945
|
-
const result = await this._client.get(apiUrl, params, false, options);
|
2946
|
-
return result.data;
|
2947
|
-
}
|
2948
|
-
}
|
2949
|
-
/* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
|
2950
|
-
let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
|
2951
|
-
try {
|
2952
|
-
return JSON.parse(jsonString);
|
2953
|
-
} catch (error) {
|
2954
|
-
return defaultValue;
|
2955
|
-
}
|
2956
|
-
}
|
2957
|
-
function sleep(ms) {
|
2958
|
-
return new Promise((resolve)=>{
|
2959
|
-
setTimeout(resolve, ms);
|
2960
|
-
});
|
2961
|
-
}
|
2962
|
-
function isBrowser() {
|
2963
|
-
return 'undefined' != typeof window;
|
2964
|
-
}
|
2965
|
-
function esm_isPlainObject(obj) {
|
2966
|
-
if ('object' != typeof obj || null === obj) return false;
|
2967
|
-
const proto = Object.getPrototypeOf(obj);
|
2968
|
-
if (null === proto) return true;
|
2969
|
-
let baseProto = proto;
|
2970
|
-
while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
|
2971
|
-
return proto === baseProto;
|
2972
|
-
}
|
2973
|
-
function esm_mergeConfig() {
|
2974
|
-
for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
|
2975
|
-
return objects.reduce((result, obj)=>{
|
2976
|
-
if (void 0 === obj) return result || {};
|
2977
|
-
for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
2978
|
-
if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
|
2979
|
-
else result[key] = obj[key];
|
2980
|
-
}
|
2981
|
-
return result;
|
2982
|
-
}, {});
|
2983
|
-
}
|
2984
|
-
function isPersonalAccessToken(token) {
|
2985
|
-
return null == token ? void 0 : token.startsWith('pat_');
|
2986
|
-
}
|
2987
|
-
/* eslint-disable max-params */ class CozeError extends Error {
|
2988
|
-
}
|
2989
|
-
class APIError extends CozeError {
|
2990
|
-
static makeMessage(status, errorBody, message, headers) {
|
2991
|
-
if (!errorBody && message) return message;
|
2992
|
-
if (errorBody) {
|
2993
|
-
const list = [];
|
2994
|
-
const { code, msg, error } = errorBody;
|
2995
|
-
if (code) list.push(`code: ${code}`);
|
2996
|
-
if (msg) list.push(`msg: ${msg}`);
|
2997
|
-
if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
|
2998
|
-
const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
|
2999
|
-
if (logId) list.push(`logid: ${logId}`);
|
3000
|
-
const help_doc = null == error ? void 0 : error.help_doc;
|
3001
|
-
if (help_doc) list.push(`help doc: ${help_doc}`);
|
3002
|
-
return list.join(', ');
|
3003
|
-
}
|
3004
|
-
if (status) return `http status code: ${status} (no body)`;
|
3005
|
-
return '(no status code or body)';
|
3006
|
-
}
|
3007
|
-
static generate(status, errorResponse, message, headers) {
|
3008
|
-
if (!status) return new APIConnectionError({
|
3009
|
-
cause: castToError(errorResponse)
|
3010
|
-
});
|
3011
|
-
const error = errorResponse;
|
3012
|
-
// https://www.coze.cn/docs/developer_guides/coze_error_codes
|
3013
|
-
if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
|
3014
|
-
if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
|
3015
|
-
if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
|
3016
|
-
if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
|
3017
|
-
if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
|
3018
|
-
if (408 === status) return new TimeoutError(status, error, message, headers);
|
3019
|
-
if (502 === status) return new GatewayError(status, error, message, headers);
|
3020
|
-
if (status >= 500) return new InternalServerError(status, error, message, headers);
|
3021
|
-
return new APIError(status, error, message, headers);
|
3022
|
-
}
|
3023
|
-
constructor(status, error, message, headers){
|
3024
|
-
var _error_error, _error_error1;
|
3025
|
-
super(`${APIError.makeMessage(status, error, message, headers)}`);
|
3026
|
-
this.status = status;
|
3027
|
-
this.headers = headers;
|
3028
|
-
this.logid = null == headers ? void 0 : headers['x-tt-logid'];
|
3029
|
-
// this.error = error;
|
3030
|
-
this.code = null == error ? void 0 : error.code;
|
3031
|
-
this.msg = null == error ? void 0 : error.msg;
|
3032
|
-
this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
|
3033
|
-
this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
|
3034
|
-
this.rawError = error;
|
3035
|
-
}
|
3036
|
-
}
|
3037
|
-
class APIConnectionError extends APIError {
|
3038
|
-
constructor({ message, cause }){
|
3039
|
-
super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
|
3040
|
-
// if (cause) {
|
3041
|
-
// this.cause = cause;
|
3042
|
-
// }
|
3043
|
-
}
|
3044
|
-
}
|
3045
|
-
class APIUserAbortError extends APIError {
|
3046
|
-
constructor(message){
|
3047
|
-
super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
|
3048
|
-
}
|
3049
|
-
}
|
3050
|
-
class BadRequestError extends APIError {
|
3051
|
-
constructor(...args){
|
3052
|
-
super(...args), this.name = 'BadRequestError', this.status = 400;
|
3053
|
-
}
|
3054
|
-
}
|
3055
|
-
class AuthenticationError extends APIError {
|
3056
|
-
constructor(...args){
|
3057
|
-
super(...args), this.name = 'AuthenticationError', this.status = 401;
|
3058
|
-
}
|
3059
|
-
}
|
3060
|
-
class PermissionDeniedError extends APIError {
|
3061
|
-
constructor(...args){
|
3062
|
-
super(...args), this.name = 'PermissionDeniedError', this.status = 403;
|
3063
|
-
}
|
3064
|
-
}
|
3065
|
-
class NotFoundError extends APIError {
|
3066
|
-
constructor(...args){
|
3067
|
-
super(...args), this.name = 'NotFoundError', this.status = 404;
|
3068
|
-
}
|
3069
|
-
}
|
3070
|
-
class TimeoutError extends APIError {
|
3071
|
-
constructor(...args){
|
3072
|
-
super(...args), this.name = 'TimeoutError', this.status = 408;
|
3073
|
-
}
|
3074
|
-
}
|
3075
|
-
class RateLimitError extends APIError {
|
3076
|
-
constructor(...args){
|
3077
|
-
super(...args), this.name = 'RateLimitError', this.status = 429;
|
3078
|
-
}
|
3079
|
-
}
|
3080
|
-
class InternalServerError extends APIError {
|
3081
|
-
constructor(...args){
|
3082
|
-
super(...args), this.name = 'InternalServerError', this.status = 500;
|
3083
|
-
}
|
3084
|
-
}
|
3085
|
-
class GatewayError extends APIError {
|
3086
|
-
constructor(...args){
|
3087
|
-
super(...args), this.name = 'GatewayError', this.status = 502;
|
3088
|
-
}
|
3089
|
-
}
|
3090
|
-
const castToError = (err)=>{
|
3091
|
-
if (err instanceof Error) return err;
|
3092
|
-
return new Error(err);
|
3093
|
-
};
|
3094
|
-
class Messages extends APIResource {
|
3095
|
-
/**
|
3096
|
-
* Get the list of messages in a chat. | 获取对话中的消息列表。
|
3097
|
-
* @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
|
3098
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
|
3099
|
-
* @param conversation_id - Required The ID of the conversation. | 会话 ID。
|
3100
|
-
* @param chat_id - Required The ID of the chat. | 对话 ID。
|
3101
|
-
* @returns An array of chat messages. | 对话消息数组。
|
3102
|
-
*/ async list(conversation_id, chat_id, options) {
|
3103
|
-
const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
|
3104
|
-
const result = await this._client.get(apiUrl, void 0, false, options);
|
3105
|
-
return result.data;
|
3106
|
-
}
|
3107
|
-
}
|
3108
|
-
const uuid = ()=>(Math.random() * new Date().getTime()).toString();
|
3109
|
-
const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
|
3110
|
-
...i,
|
3111
|
-
content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
|
3112
|
-
}));
|
3113
|
-
class Chat extends APIResource {
|
3114
|
-
/**
|
3115
|
-
* Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
|
3116
|
-
* @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
|
3117
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
|
3118
|
-
* @param params - Required The parameters for creating a chat session. | 创建会话的参数。
|
3119
|
-
* @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
|
3120
|
-
* @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
|
3121
|
-
* @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
|
3122
|
-
* @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
|
3123
|
-
* @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
|
3124
|
-
* @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
|
3125
|
-
* @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
|
3126
|
-
* @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
|
3127
|
-
* @returns The data of the created chat. | 创建的对话数据。
|
3128
|
-
*/ async create(params, options) {
|
3129
|
-
if (!params.user_id) params.user_id = uuid();
|
3130
|
-
const { conversation_id, ...rest } = params;
|
3131
|
-
const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
|
3132
|
-
const payload = {
|
3133
|
-
...rest,
|
3134
|
-
additional_messages: handleAdditionalMessages(params.additional_messages),
|
3135
|
-
stream: false
|
3136
|
-
};
|
3137
|
-
const result = await this._client.post(apiUrl, payload, false, options);
|
3138
|
-
return result.data;
|
3139
|
-
}
|
3140
|
-
/**
|
3141
|
-
* Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
|
3142
|
-
* @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
|
3143
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
|
3144
|
-
* @param params - Required The parameters for creating a chat session. | 创建会话的参数。
|
3145
|
-
* @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
|
3146
|
-
* @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
|
3147
|
-
* @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
|
3148
|
-
* @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
|
3149
|
-
* @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
|
3150
|
-
* @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
|
3151
|
-
* @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
|
3152
|
-
* @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
|
3153
|
-
* @returns
|
3154
|
-
*/ async createAndPoll(params, options) {
|
3155
|
-
if (!params.user_id) params.user_id = uuid();
|
3156
|
-
const { conversation_id, ...rest } = params;
|
3157
|
-
const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
|
3158
|
-
const payload = {
|
3159
|
-
...rest,
|
3160
|
-
additional_messages: handleAdditionalMessages(params.additional_messages),
|
3161
|
-
stream: false
|
3162
|
-
};
|
3163
|
-
const result = await this._client.post(apiUrl, payload, false, options);
|
3164
|
-
const chatId = result.data.id;
|
3165
|
-
const conversationId = result.data.conversation_id;
|
3166
|
-
let chat;
|
3167
|
-
while(true){
|
3168
|
-
await sleep(100);
|
3169
|
-
chat = await this.retrieve(conversationId, chatId);
|
3170
|
-
if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
|
3171
|
-
}
|
3172
|
-
const messageList = await this.messages.list(conversationId, chatId);
|
3173
|
-
return {
|
3174
|
-
chat,
|
3175
|
-
messages: messageList
|
3176
|
-
};
|
3177
|
-
}
|
3178
|
-
/**
|
3179
|
-
* Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
|
3180
|
-
* @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
|
3181
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
|
3182
|
-
* @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
|
3183
|
-
* @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
|
3184
|
-
* @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
|
3185
|
-
* @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
|
3186
|
-
* @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
|
3187
|
-
* @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
|
3188
|
-
* @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
|
3189
|
-
* @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
|
3190
|
-
* @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
|
3191
|
-
* @returns A stream of chat data. | 对话数据流。
|
3192
|
-
*/ async *stream(params, options) {
|
3193
|
-
if (!params.user_id) params.user_id = uuid();
|
3194
|
-
const { conversation_id, ...rest } = params;
|
3195
|
-
const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
|
3196
|
-
const payload = {
|
3197
|
-
...rest,
|
3198
|
-
additional_messages: handleAdditionalMessages(params.additional_messages),
|
3199
|
-
stream: true
|
3200
|
-
};
|
3201
|
-
const result = await this._client.post(apiUrl, payload, true, options);
|
3202
|
-
for await (const message of result)if ("done" === message.event) {
|
3203
|
-
const ret = {
|
3204
|
-
event: message.event,
|
3205
|
-
data: '[DONE]'
|
3206
|
-
};
|
3207
|
-
yield ret;
|
3208
|
-
} else try {
|
3209
|
-
const ret = {
|
3210
|
-
event: message.event,
|
3211
|
-
data: JSON.parse(message.data)
|
3212
|
-
};
|
3213
|
-
yield ret;
|
3214
|
-
} catch (error) {
|
3215
|
-
throw new CozeError(`Could not parse message into JSON:${message.data}`);
|
3216
|
-
}
|
3217
|
-
}
|
3218
|
-
/**
|
3219
|
-
* Get the detailed information of the chat. | 查看对话的详细信息。
|
3220
|
-
* @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
|
3221
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
|
3222
|
-
* @param conversation_id - Required The ID of the conversation. | 会话 ID。
|
3223
|
-
* @param chat_id - Required The ID of the chat. | 对话 ID。
|
3224
|
-
* @returns The data of the retrieved chat. | 检索到的对话数据。
|
3225
|
-
*/ async retrieve(conversation_id, chat_id, options) {
|
3226
|
-
const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
|
3227
|
-
const result = await this._client.post(apiUrl, void 0, false, options);
|
3228
|
-
return result.data;
|
3229
|
-
}
|
3230
|
-
/**
|
3231
|
-
* Cancel a chat session. | 取消对话会话。
|
3232
|
-
* @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
|
3233
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
|
3234
|
-
* @param conversation_id - Required The ID of the conversation. | 会话 ID。
|
3235
|
-
* @param chat_id - Required The ID of the chat. | 对话 ID。
|
3236
|
-
* @returns The data of the canceled chat. | 取消的对话数据。
|
3237
|
-
*/ async cancel(conversation_id, chat_id, options) {
|
3238
|
-
const apiUrl = '/v3/chat/cancel';
|
3239
|
-
const payload = {
|
3240
|
-
conversation_id,
|
3241
|
-
chat_id
|
3242
|
-
};
|
3243
|
-
const result = await this._client.post(apiUrl, payload, false, options);
|
3244
|
-
return result.data;
|
3245
|
-
}
|
3246
|
-
/**
|
3247
|
-
* Submit tool outputs for a chat session. | 提交对话会话的工具输出。
|
3248
|
-
* @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
|
3249
|
-
* @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
|
3250
|
-
* @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
|
3251
|
-
* @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
|
3252
|
-
* @param params.chat_id - Required The ID of the chat. | 对话 ID。
|
3253
|
-
* @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
|
3254
|
-
* @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
|
3255
|
-
* @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
|
3256
|
-
*/ async *submitToolOutputs(params, options) {
|
3257
|
-
const { conversation_id, chat_id, ...rest } = params;
|
3258
|
-
const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
|
3259
|
-
const payload = {
|
3260
|
-
...rest
|
3261
|
-
};
|
3262
|
-
if (false === params.stream) {
|
3263
|
-
const response = await this._client.post(apiUrl, payload, false, options);
|
3264
|
-
return response.data;
|
3265
|
-
}
|
3266
|
-
{
|
3267
|
-
const result = await this._client.post(apiUrl, payload, true, options);
|
3268
|
-
for await (const message of result)if ("done" === message.event) {
|
3269
|
-
const ret = {
|
3270
|
-
event: message.event,
|
3271
|
-
data: '[DONE]'
|
3272
|
-
};
|
3273
|
-
yield ret;
|
3274
|
-
} else try {
|
3275
|
-
const ret = {
|
3276
|
-
event: message.event,
|
3277
|
-
data: JSON.parse(message.data)
|
3278
|
-
};
|
3279
|
-
yield ret;
|
3280
|
-
} catch (error) {
|
3281
|
-
throw new CozeError(`Could not parse message into JSON:${message.data}`);
|
3282
|
-
}
|
3283
|
-
}
|
3284
|
-
}
|
3285
|
-
constructor(...args){
|
3286
|
-
super(...args), this.messages = new Messages(this._client);
|
3287
|
-
}
|
3288
|
-
}
|
3289
|
-
var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
|
3290
|
-
ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
|
3291
|
-
ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
|
3292
|
-
ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
|
3293
|
-
ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
|
3294
|
-
ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
|
3295
|
-
ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
|
3296
|
-
ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
|
3297
|
-
ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
|
3298
|
-
ChatEventType["DONE"] = "done";
|
3299
|
-
ChatEventType["ERROR"] = "error";
|
3300
|
-
return ChatEventType;
|
3301
|
-
}({});
|
3302
|
-
class messages_Messages extends APIResource {
|
3303
|
-
/**
|
3304
|
-
* Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
|
3305
|
-
* @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
|
3306
|
-
* @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
|
3307
|
-
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
3308
|
-
* @param params - Required The parameters for creating a message | 创建消息所需的参数
|
3309
|
-
* @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
|
3310
|
-
* @param params.content - Required The content of the message. | 消息的内容。
|
3311
|
-
* @param params.content_type - Required The type of the message content. | 消息内容的类型。
|
3312
|
-
* @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
|
3313
|
-
* @returns Information about the new message. | 消息详情。
|
3314
|
-
*/ async create(conversation_id, params, options) {
|
3315
|
-
const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
|
3316
|
-
const response = await this._client.post(apiUrl, params, false, options);
|
3317
|
-
return response.data;
|
3318
|
-
}
|
3319
|
-
/**
|
3320
|
-
* Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
|
3321
|
-
* @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
|
3322
|
-
* @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
|
3323
|
-
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
3324
|
-
* @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
|
3325
|
-
* @param params - Required The parameters for modifying a message | 修改消息所需的参数
|
3326
|
-
* @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
|
3327
|
-
* @param params.content - Optional The content of the message. | 消息的内容。
|
3328
|
-
* @param params.content_type - Optional The type of the message content. | 消息内容的类型。
|
3329
|
-
* @returns Information about the modified message. | 消息详情。
|
3330
|
-
*/ // eslint-disable-next-line max-params
|
3331
|
-
async update(conversation_id, message_id, params, options) {
|
3332
|
-
const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
|
3333
|
-
const response = await this._client.post(apiUrl, params, false, options);
|
3334
|
-
return response.message;
|
3335
|
-
}
|
3336
|
-
/**
|
3337
|
-
* Get the detailed information of specified message. | 查看指定消息的详细信息。
|
3338
|
-
* @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
|
3339
|
-
* @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
|
3340
|
-
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
3341
|
-
* @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
|
3342
|
-
* @returns Information about the message. | 消息详情。
|
3343
|
-
*/ async retrieve(conversation_id, message_id, options) {
|
3344
|
-
const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
|
3345
|
-
const response = await this._client.get(apiUrl, null, false, options);
|
3346
|
-
return response.data;
|
3347
|
-
}
|
3348
|
-
/**
|
3349
|
-
* List messages in a conversation. | 列出会话中的消息。
|
3350
|
-
* @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
|
3351
|
-
* @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
|
3352
|
-
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
3353
|
-
* @param params - Optional The parameters for listing messages | 列出消息所需的参数
|
3354
|
-
* @param params.order - Optional The order of the messages. | 消息的顺序。
|
3355
|
-
* @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
|
3356
|
-
* @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
|
3357
|
-
* @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
|
3358
|
-
* @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
|
3359
|
-
* @returns A list of messages. | 消息列表。
|
3360
|
-
*/ async list(conversation_id, params, options) {
|
3361
|
-
const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
|
3362
|
-
const response = await this._client.post(apiUrl, params, false, options);
|
3363
|
-
return response;
|
3147
|
+
len = responseInterceptorChain.length;
|
3148
|
+
while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
|
3149
|
+
return promise;
|
3364
3150
|
}
|
3365
|
-
|
3366
|
-
|
3367
|
-
|
3368
|
-
|
3369
|
-
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
3370
|
-
* @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
|
3371
|
-
* @returns Details of the deleted message. | 已删除的消息详情。
|
3372
|
-
*/ async delete(conversation_id, message_id, options) {
|
3373
|
-
const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
|
3374
|
-
const response = await this._client.post(apiUrl, void 0, false, options);
|
3375
|
-
return response.data;
|
3151
|
+
getUri(config) {
|
3152
|
+
config = mergeConfig_mergeConfig(this.defaults, config);
|
3153
|
+
const fullPath = buildFullPath(config.baseURL, config.url);
|
3154
|
+
return buildURL(fullPath, config.params, config.paramsSerializer);
|
3376
3155
|
}
|
3377
3156
|
}
|
3378
|
-
|
3379
|
-
|
3380
|
-
|
3381
|
-
|
3382
|
-
|
3383
|
-
|
3384
|
-
|
3385
|
-
|
3386
|
-
|
3387
|
-
|
3388
|
-
|
3389
|
-
|
3390
|
-
|
3391
|
-
|
3157
|
+
// Provide aliases for supported request methods
|
3158
|
+
utils.forEach([
|
3159
|
+
'delete',
|
3160
|
+
'get',
|
3161
|
+
'head',
|
3162
|
+
'options'
|
3163
|
+
], function(method) {
|
3164
|
+
/*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
|
3165
|
+
return this.request(mergeConfig_mergeConfig(config || {}, {
|
3166
|
+
method,
|
3167
|
+
url,
|
3168
|
+
data: (config || {}).data
|
3169
|
+
}));
|
3170
|
+
};
|
3171
|
+
});
|
3172
|
+
utils.forEach([
|
3173
|
+
'post',
|
3174
|
+
'put',
|
3175
|
+
'patch'
|
3176
|
+
], function(method) {
|
3177
|
+
/*eslint func-names:0*/ function generateHTTPMethod(isForm) {
|
3178
|
+
return function(url, data, config) {
|
3179
|
+
return this.request(mergeConfig_mergeConfig(config || {}, {
|
3180
|
+
method,
|
3181
|
+
headers: isForm ? {
|
3182
|
+
'Content-Type': 'multipart/form-data'
|
3183
|
+
} : {},
|
3184
|
+
url,
|
3185
|
+
data
|
3186
|
+
}));
|
3187
|
+
};
|
3188
|
+
}
|
3189
|
+
Axios_Axios.prototype[method] = generateHTTPMethod();
|
3190
|
+
Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
|
3191
|
+
});
|
3192
|
+
/* ESM default export */ const Axios = Axios_Axios;
|
3193
|
+
/**
|
3194
|
+
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
3195
|
+
*
|
3196
|
+
* @param {Function} executor The executor function.
|
3197
|
+
*
|
3198
|
+
* @returns {CancelToken}
|
3199
|
+
*/ class CancelToken_CancelToken {
|
3200
|
+
constructor(executor){
|
3201
|
+
if ('function' != typeof executor) throw new TypeError('executor must be a function.');
|
3202
|
+
let resolvePromise;
|
3203
|
+
this.promise = new Promise(function(resolve) {
|
3204
|
+
resolvePromise = resolve;
|
3205
|
+
});
|
3206
|
+
const token = this;
|
3207
|
+
// eslint-disable-next-line func-names
|
3208
|
+
this.promise.then((cancel)=>{
|
3209
|
+
if (!token._listeners) return;
|
3210
|
+
let i = token._listeners.length;
|
3211
|
+
while(i-- > 0)token._listeners[i](cancel);
|
3212
|
+
token._listeners = null;
|
3213
|
+
});
|
3214
|
+
// eslint-disable-next-line func-names
|
3215
|
+
this.promise.then = (onfulfilled)=>{
|
3216
|
+
let _resolve;
|
3217
|
+
// eslint-disable-next-line func-names
|
3218
|
+
const promise = new Promise((resolve)=>{
|
3219
|
+
token.subscribe(resolve);
|
3220
|
+
_resolve = resolve;
|
3221
|
+
}).then(onfulfilled);
|
3222
|
+
promise.cancel = function() {
|
3223
|
+
token.unsubscribe(_resolve);
|
3224
|
+
};
|
3225
|
+
return promise;
|
3226
|
+
};
|
3227
|
+
executor(function(message, config, request) {
|
3228
|
+
if (token.reason) // Cancellation has already been requested
|
3229
|
+
return;
|
3230
|
+
token.reason = new CanceledError(message, config, request);
|
3231
|
+
resolvePromise(token.reason);
|
3232
|
+
});
|
3392
3233
|
}
|
3393
3234
|
/**
|
3394
|
-
*
|
3395
|
-
|
3396
|
-
|
3397
|
-
* @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
|
3398
|
-
* @returns Information about the conversation. | 会话的基础信息。
|
3399
|
-
*/ async retrieve(conversation_id, options) {
|
3400
|
-
const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
|
3401
|
-
const response = await this._client.get(apiUrl, null, false, options);
|
3402
|
-
return response.data;
|
3235
|
+
* Throws a `CanceledError` if cancellation has been requested.
|
3236
|
+
*/ throwIfRequested() {
|
3237
|
+
if (this.reason) throw this.reason;
|
3403
3238
|
}
|
3404
3239
|
/**
|
3405
|
-
*
|
3406
|
-
|
3407
|
-
|
3408
|
-
|
3409
|
-
|
3410
|
-
|
3411
|
-
|
3412
|
-
|
3413
|
-
|
3414
|
-
|
3240
|
+
* Subscribe to the cancel signal
|
3241
|
+
*/ subscribe(listener) {
|
3242
|
+
if (this.reason) {
|
3243
|
+
listener(this.reason);
|
3244
|
+
return;
|
3245
|
+
}
|
3246
|
+
if (this._listeners) this._listeners.push(listener);
|
3247
|
+
else this._listeners = [
|
3248
|
+
listener
|
3249
|
+
];
|
3415
3250
|
}
|
3416
3251
|
/**
|
3417
|
-
*
|
3418
|
-
|
3419
|
-
|
3420
|
-
|
3421
|
-
|
3422
|
-
const response = await this._client.post(apiUrl, null, false, options);
|
3423
|
-
return response.data;
|
3252
|
+
* Unsubscribe from the cancel signal
|
3253
|
+
*/ unsubscribe(listener) {
|
3254
|
+
if (!this._listeners) return;
|
3255
|
+
const index = this._listeners.indexOf(listener);
|
3256
|
+
if (-1 !== index) this._listeners.splice(index, 1);
|
3424
3257
|
}
|
3425
|
-
|
3426
|
-
|
3258
|
+
toAbortSignal() {
|
3259
|
+
const controller = new AbortController();
|
3260
|
+
const abort = (err)=>{
|
3261
|
+
controller.abort(err);
|
3262
|
+
};
|
3263
|
+
this.subscribe(abort);
|
3264
|
+
controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
|
3265
|
+
return controller.signal;
|
3266
|
+
}
|
3267
|
+
/**
|
3268
|
+
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
3269
|
+
* cancels the `CancelToken`.
|
3270
|
+
*/ static source() {
|
3271
|
+
let cancel;
|
3272
|
+
const token = new CancelToken_CancelToken(function(c) {
|
3273
|
+
cancel = c;
|
3274
|
+
});
|
3275
|
+
return {
|
3276
|
+
token,
|
3277
|
+
cancel
|
3278
|
+
};
|
3427
3279
|
}
|
3428
3280
|
}
|
3281
|
+
/* ESM default export */ const CancelToken = CancelToken_CancelToken;
|
3282
|
+
/**
|
3283
|
+
* Syntactic sugar for invoking a function and expanding an array for arguments.
|
3284
|
+
*
|
3285
|
+
* Common use case would be to use `Function.prototype.apply`.
|
3286
|
+
*
|
3287
|
+
* ```js
|
3288
|
+
* function f(x, y, z) {}
|
3289
|
+
* var args = [1, 2, 3];
|
3290
|
+
* f.apply(null, args);
|
3291
|
+
* ```
|
3292
|
+
*
|
3293
|
+
* With `spread` this example can be re-written.
|
3294
|
+
*
|
3295
|
+
* ```js
|
3296
|
+
* spread(function(x, y, z) {})([1, 2, 3]);
|
3297
|
+
* ```
|
3298
|
+
*
|
3299
|
+
* @param {Function} callback
|
3300
|
+
*
|
3301
|
+
* @returns {Function}
|
3302
|
+
*/ function spread(callback) {
|
3303
|
+
return function(arr) {
|
3304
|
+
return callback.apply(null, arr);
|
3305
|
+
};
|
3306
|
+
}
|
3307
|
+
/**
|
3308
|
+
* Determines whether the payload is an error thrown by Axios
|
3309
|
+
*
|
3310
|
+
* @param {*} payload The value to test
|
3311
|
+
*
|
3312
|
+
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
|
3313
|
+
*/ function isAxiosError(payload) {
|
3314
|
+
return utils.isObject(payload) && true === payload.isAxiosError;
|
3315
|
+
}
|
3316
|
+
const HttpStatusCode = {
|
3317
|
+
Continue: 100,
|
3318
|
+
SwitchingProtocols: 101,
|
3319
|
+
Processing: 102,
|
3320
|
+
EarlyHints: 103,
|
3321
|
+
Ok: 200,
|
3322
|
+
Created: 201,
|
3323
|
+
Accepted: 202,
|
3324
|
+
NonAuthoritativeInformation: 203,
|
3325
|
+
NoContent: 204,
|
3326
|
+
ResetContent: 205,
|
3327
|
+
PartialContent: 206,
|
3328
|
+
MultiStatus: 207,
|
3329
|
+
AlreadyReported: 208,
|
3330
|
+
ImUsed: 226,
|
3331
|
+
MultipleChoices: 300,
|
3332
|
+
MovedPermanently: 301,
|
3333
|
+
Found: 302,
|
3334
|
+
SeeOther: 303,
|
3335
|
+
NotModified: 304,
|
3336
|
+
UseProxy: 305,
|
3337
|
+
Unused: 306,
|
3338
|
+
TemporaryRedirect: 307,
|
3339
|
+
PermanentRedirect: 308,
|
3340
|
+
BadRequest: 400,
|
3341
|
+
Unauthorized: 401,
|
3342
|
+
PaymentRequired: 402,
|
3343
|
+
Forbidden: 403,
|
3344
|
+
NotFound: 404,
|
3345
|
+
MethodNotAllowed: 405,
|
3346
|
+
NotAcceptable: 406,
|
3347
|
+
ProxyAuthenticationRequired: 407,
|
3348
|
+
RequestTimeout: 408,
|
3349
|
+
Conflict: 409,
|
3350
|
+
Gone: 410,
|
3351
|
+
LengthRequired: 411,
|
3352
|
+
PreconditionFailed: 412,
|
3353
|
+
PayloadTooLarge: 413,
|
3354
|
+
UriTooLong: 414,
|
3355
|
+
UnsupportedMediaType: 415,
|
3356
|
+
RangeNotSatisfiable: 416,
|
3357
|
+
ExpectationFailed: 417,
|
3358
|
+
ImATeapot: 418,
|
3359
|
+
MisdirectedRequest: 421,
|
3360
|
+
UnprocessableEntity: 422,
|
3361
|
+
Locked: 423,
|
3362
|
+
FailedDependency: 424,
|
3363
|
+
TooEarly: 425,
|
3364
|
+
UpgradeRequired: 426,
|
3365
|
+
PreconditionRequired: 428,
|
3366
|
+
TooManyRequests: 429,
|
3367
|
+
RequestHeaderFieldsTooLarge: 431,
|
3368
|
+
UnavailableForLegalReasons: 451,
|
3369
|
+
InternalServerError: 500,
|
3370
|
+
NotImplemented: 501,
|
3371
|
+
BadGateway: 502,
|
3372
|
+
ServiceUnavailable: 503,
|
3373
|
+
GatewayTimeout: 504,
|
3374
|
+
HttpVersionNotSupported: 505,
|
3375
|
+
VariantAlsoNegotiates: 506,
|
3376
|
+
InsufficientStorage: 507,
|
3377
|
+
LoopDetected: 508,
|
3378
|
+
NotExtended: 510,
|
3379
|
+
NetworkAuthenticationRequired: 511
|
3380
|
+
};
|
3381
|
+
Object.entries(HttpStatusCode).forEach(([key, value])=>{
|
3382
|
+
HttpStatusCode[value] = key;
|
3383
|
+
});
|
3384
|
+
/* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
|
3385
|
+
/**
|
3386
|
+
* Create an instance of Axios
|
3387
|
+
*
|
3388
|
+
* @param {Object} defaultConfig The default config for the instance
|
3389
|
+
*
|
3390
|
+
* @returns {Axios} A new instance of Axios
|
3391
|
+
*/ function createInstance(defaultConfig) {
|
3392
|
+
const context = new Axios(defaultConfig);
|
3393
|
+
const instance = bind(Axios.prototype.request, context);
|
3394
|
+
// Copy axios.prototype to instance
|
3395
|
+
utils.extend(instance, Axios.prototype, context, {
|
3396
|
+
allOwnKeys: true
|
3397
|
+
});
|
3398
|
+
// Copy context to instance
|
3399
|
+
utils.extend(instance, context, null, {
|
3400
|
+
allOwnKeys: true
|
3401
|
+
});
|
3402
|
+
// Factory for creating new instances
|
3403
|
+
instance.create = function(instanceConfig) {
|
3404
|
+
return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
|
3405
|
+
};
|
3406
|
+
return instance;
|
3407
|
+
}
|
3408
|
+
// Create the default instance to be exported
|
3409
|
+
const axios = createInstance(defaults);
|
3410
|
+
// Expose Axios class to allow class inheritance
|
3411
|
+
axios.Axios = Axios;
|
3412
|
+
// Expose Cancel & CancelToken
|
3413
|
+
axios.CanceledError = CanceledError;
|
3414
|
+
axios.CancelToken = CancelToken;
|
3415
|
+
axios.isCancel = isCancel;
|
3416
|
+
axios.VERSION = VERSION;
|
3417
|
+
axios.toFormData = toFormData;
|
3418
|
+
// Expose AxiosError class
|
3419
|
+
axios.AxiosError = core_AxiosError;
|
3420
|
+
// alias for CanceledError for backward compatibility
|
3421
|
+
axios.Cancel = axios.CanceledError;
|
3422
|
+
// Expose all/spread
|
3423
|
+
axios.all = function(promises) {
|
3424
|
+
return Promise.all(promises);
|
3425
|
+
};
|
3426
|
+
axios.spread = spread;
|
3427
|
+
// Expose isAxiosError
|
3428
|
+
axios.isAxiosError = isAxiosError;
|
3429
|
+
// Expose mergeConfig
|
3430
|
+
axios.mergeConfig = mergeConfig_mergeConfig;
|
3431
|
+
axios.AxiosHeaders = AxiosHeaders;
|
3432
|
+
axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
|
3433
|
+
axios.getAdapter = adapters_adapters.getAdapter;
|
3434
|
+
axios.HttpStatusCode = helpers_HttpStatusCode;
|
3435
|
+
axios.default = axios;
|
3436
|
+
// this module should only have a default export
|
3437
|
+
/* ESM default export */ const lib_axios = axios;
|
3438
|
+
// This module is intended to unwrap Axios default export as named.
|
3439
|
+
// Keep top-level export same with static properties
|
3440
|
+
// so that it can keep same with es module or cjs
|
3441
|
+
const { Axios: axios_Axios, AxiosError: axios_AxiosError, CanceledError: axios_CanceledError, isCancel: axios_isCancel, CancelToken: axios_CancelToken, VERSION: axios_VERSION, all: axios_all, Cancel, isAxiosError: axios_isAxiosError, spread: axios_spread, toFormData: axios_toFormData, AxiosHeaders: axios_AxiosHeaders, HttpStatusCode: axios_HttpStatusCode, formToJSON, getAdapter, mergeConfig: axios_mergeConfig } = lib_axios;
|
3429
3442
|
class Files extends APIResource {
|
3430
3443
|
/**
|
3431
3444
|
* Upload files to Coze platform. | 调用接口上传文件到扣子。
|
@@ -3588,7 +3601,7 @@ class Documents extends APIResource {
|
|
3588
3601
|
* @returns ListDocumentData | 知识库文件列表
|
3589
3602
|
*/ list(params, options) {
|
3590
3603
|
const apiUrl = '/open_api/knowledge/document/list';
|
3591
|
-
const response = this._client.get(apiUrl, params, false,
|
3604
|
+
const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
|
3592
3605
|
headers: documents_headers
|
3593
3606
|
}));
|
3594
3607
|
return response;
|
@@ -3606,7 +3619,7 @@ class Documents extends APIResource {
|
|
3606
3619
|
* @returns DocumentInfo[] | 已上传文件的基本信息
|
3607
3620
|
*/ async create(params, options) {
|
3608
3621
|
const apiUrl = '/open_api/knowledge/document/create';
|
3609
|
-
const response = await this._client.post(apiUrl, params, false,
|
3622
|
+
const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
|
3610
3623
|
headers: documents_headers
|
3611
3624
|
}));
|
3612
3625
|
return response.document_infos;
|
@@ -3622,7 +3635,7 @@ class Documents extends APIResource {
|
|
3622
3635
|
* @returns void | 无返回
|
3623
3636
|
*/ async delete(params, options) {
|
3624
3637
|
const apiUrl = '/open_api/knowledge/document/delete';
|
3625
|
-
await this._client.post(apiUrl, params, false,
|
3638
|
+
await this._client.post(apiUrl, params, false, mergeConfig(options, {
|
3626
3639
|
headers: documents_headers
|
3627
3640
|
}));
|
3628
3641
|
}
|
@@ -3638,7 +3651,7 @@ class Documents extends APIResource {
|
|
3638
3651
|
* @returns void | 无返回
|
3639
3652
|
*/ async update(params, options) {
|
3640
3653
|
const apiUrl = '/open_api/knowledge/document/update';
|
3641
|
-
await this._client.post(apiUrl, params, false,
|
3654
|
+
await this._client.post(apiUrl, params, false, mergeConfig(options, {
|
3642
3655
|
headers: documents_headers
|
3643
3656
|
}));
|
3644
3657
|
}
|
@@ -3666,7 +3679,7 @@ class documents_Documents extends APIResource {
|
|
3666
3679
|
* @returns ListDocumentData | 知识库文件列表
|
3667
3680
|
*/ async list(params, options) {
|
3668
3681
|
const apiUrl = '/open_api/knowledge/document/list';
|
3669
|
-
const response = await this._client.get(apiUrl, params, false,
|
3682
|
+
const response = await this._client.get(apiUrl, params, false, mergeConfig(options, {
|
3670
3683
|
headers: documents_documents_headers
|
3671
3684
|
}));
|
3672
3685
|
return response;
|
@@ -3682,7 +3695,7 @@ class documents_Documents extends APIResource {
|
|
3682
3695
|
* @returns DocumentInfo[] | 已上传文件的基本信息
|
3683
3696
|
*/ async create(params, options) {
|
3684
3697
|
const apiUrl = '/open_api/knowledge/document/create';
|
3685
|
-
const response = await this._client.post(apiUrl, params, false,
|
3698
|
+
const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
|
3686
3699
|
headers: documents_documents_headers
|
3687
3700
|
}));
|
3688
3701
|
return response.document_infos;
|
@@ -3696,7 +3709,7 @@ class documents_Documents extends APIResource {
|
|
3696
3709
|
* @returns void | 无返回
|
3697
3710
|
*/ async delete(params, options) {
|
3698
3711
|
const apiUrl = '/open_api/knowledge/document/delete';
|
3699
|
-
await this._client.post(apiUrl, params, false,
|
3712
|
+
await this._client.post(apiUrl, params, false, mergeConfig(options, {
|
3700
3713
|
headers: documents_documents_headers
|
3701
3714
|
}));
|
3702
3715
|
}
|
@@ -3710,7 +3723,7 @@ class documents_Documents extends APIResource {
|
|
3710
3723
|
* @returns void | 无返回
|
3711
3724
|
*/ async update(params, options) {
|
3712
3725
|
const apiUrl = '/open_api/knowledge/document/update';
|
3713
|
-
await this._client.post(apiUrl, params, false,
|
3726
|
+
await this._client.post(apiUrl, params, false, mergeConfig(options, {
|
3714
3727
|
headers: documents_documents_headers
|
3715
3728
|
}));
|
3716
3729
|
}
|
@@ -3832,6 +3845,8 @@ class Voices extends APIResource {
|
|
3832
3845
|
* | 如果传入会基于该文本生成预览音频,否则使用默认的文本
|
3833
3846
|
* @param params.text - Optional. Users can read this text, service will compare audio with text. Returns error if difference is too large
|
3834
3847
|
* | 可以让用户按照该文本念诵,服务会对比音频与该文本的差异。若差异过大会返回错误
|
3848
|
+
* @param params.space_id - Optional. The space id of the voice. | 空间ID
|
3849
|
+
* @param params.description- Optional. The description of the voice. | 音色描述
|
3835
3850
|
* @param options - Request options
|
3836
3851
|
* @returns Clone voice data
|
3837
3852
|
*/ async clone(params, options) {
|
@@ -3856,6 +3871,17 @@ class Voices extends APIResource {
|
|
3856
3871
|
return response.data;
|
3857
3872
|
}
|
3858
3873
|
}
|
3874
|
+
class Transcriptions extends APIResource {
|
3875
|
+
/**
|
3876
|
+
* ASR voice to text | ASR 语音转文本
|
3877
|
+
* @param params - Required The parameters for file upload | 上传文件所需的参数
|
3878
|
+
* @param params.file - Required The audio file to be uploaded. | 需要上传的音频文件。
|
3879
|
+
*/ async create(params, options) {
|
3880
|
+
const apiUrl = '/v1/audio/transcriptions';
|
3881
|
+
const response = await this._client.post(apiUrl, axios_toFormData(params), false, options);
|
3882
|
+
return response.data;
|
3883
|
+
}
|
3884
|
+
}
|
3859
3885
|
class Speech extends APIResource {
|
3860
3886
|
/**
|
3861
3887
|
* @description Speech synthesis | 语音合成
|
@@ -3872,7 +3898,7 @@ class Speech extends APIResource {
|
|
3872
3898
|
const response = await this._client.post(apiUrl, {
|
3873
3899
|
...params,
|
3874
3900
|
sample_rate: params.sample_rate || 24000
|
3875
|
-
}, false,
|
3901
|
+
}, false, mergeConfig(options, {
|
3876
3902
|
responseType: 'arraybuffer'
|
3877
3903
|
}));
|
3878
3904
|
return response;
|
@@ -3885,9 +3911,9 @@ class Rooms extends APIResource {
|
|
3885
3911
|
return response.data;
|
3886
3912
|
}
|
3887
3913
|
}
|
3888
|
-
class
|
3914
|
+
class audio_Audio extends APIResource {
|
3889
3915
|
constructor(...args){
|
3890
|
-
super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
|
3916
|
+
super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client), this.transcriptions = new Transcriptions(this._client);
|
3891
3917
|
}
|
3892
3918
|
}
|
3893
3919
|
class Templates extends APIResource {
|
@@ -3904,18 +3930,716 @@ class Templates extends APIResource {
|
|
3904
3930
|
return response.data;
|
3905
3931
|
}
|
3906
3932
|
}
|
3907
|
-
|
3908
|
-
|
3933
|
+
class chat_Chat extends APIResource {
|
3934
|
+
async create(botId, options) {
|
3935
|
+
const apiUrl = `/v1/chat?bot_id=${botId}`;
|
3936
|
+
return await this._client.makeWebsocket(apiUrl, options);
|
3937
|
+
}
|
3938
|
+
}
|
3939
|
+
class transcriptions_Transcriptions extends APIResource {
|
3940
|
+
async create(options) {
|
3941
|
+
const apiUrl = '/v1/audio/transcriptions';
|
3942
|
+
return await this._client.makeWebsocket(apiUrl, options);
|
3943
|
+
}
|
3944
|
+
}
|
3945
|
+
class speech_Speech extends APIResource {
|
3946
|
+
async create(options) {
|
3947
|
+
const apiUrl = '/v1/audio/speech';
|
3948
|
+
return await this._client.makeWebsocket(apiUrl, options);
|
3949
|
+
}
|
3950
|
+
}
|
3951
|
+
class websockets_audio_Audio extends APIResource {
|
3952
|
+
constructor(...args){
|
3953
|
+
super(...args), this.speech = new speech_Speech(this._client), this.transcriptions = new transcriptions_Transcriptions(this._client);
|
3954
|
+
}
|
3955
|
+
}
|
3956
|
+
class Websockets extends APIResource {
|
3957
|
+
constructor(...args){
|
3958
|
+
super(...args), this.audio = new websockets_audio_Audio(this._client), this.chat = new chat_Chat(this._client);
|
3959
|
+
}
|
3960
|
+
}
|
3961
|
+
// EXTERNAL MODULE: ../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js
|
3962
|
+
var ws_browser = __webpack_require__("../../common/temp/default/node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js");
|
3963
|
+
var browser_default = /*#__PURE__*/ __webpack_require__.n(ws_browser);
|
3964
|
+
/*! *****************************************************************************
|
3965
|
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
3966
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
3967
|
+
this file except in compliance with the License. You may obtain a copy of the
|
3968
|
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
3969
|
+
|
3970
|
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
3971
|
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
3972
|
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
3973
|
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
3974
|
+
|
3975
|
+
See the Apache Version 2.0 License for specific language governing permissions
|
3976
|
+
and limitations under the License.
|
3977
|
+
***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) {
|
3978
|
+
extendStatics = Object.setPrototypeOf || ({
|
3979
|
+
__proto__: []
|
3980
|
+
}) instanceof Array && function(d, b) {
|
3981
|
+
d.__proto__ = b;
|
3982
|
+
} || function(d, b) {
|
3983
|
+
for(var p in b)if (b.hasOwnProperty(p)) d[p] = b[p];
|
3984
|
+
};
|
3985
|
+
return extendStatics(d, b);
|
3986
|
+
};
|
3987
|
+
function __extends(d, b) {
|
3988
|
+
extendStatics(d, b);
|
3989
|
+
function __() {
|
3990
|
+
this.constructor = d;
|
3991
|
+
}
|
3992
|
+
d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __());
|
3993
|
+
}
|
3994
|
+
function __values(o) {
|
3995
|
+
var m = "function" == typeof Symbol && o[Symbol.iterator], i = 0;
|
3996
|
+
if (m) return m.call(o);
|
3997
|
+
return {
|
3998
|
+
next: function() {
|
3999
|
+
if (o && i >= o.length) o = void 0;
|
4000
|
+
return {
|
4001
|
+
value: o && o[i++],
|
4002
|
+
done: !o
|
4003
|
+
};
|
4004
|
+
}
|
4005
|
+
};
|
4006
|
+
}
|
4007
|
+
function __read(o, n) {
|
4008
|
+
var m = "function" == typeof Symbol && o[Symbol.iterator];
|
4009
|
+
if (!m) return o;
|
4010
|
+
var i = m.call(o), r, ar = [], e;
|
4011
|
+
try {
|
4012
|
+
while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value);
|
4013
|
+
} catch (error) {
|
4014
|
+
e = {
|
4015
|
+
error: error
|
4016
|
+
};
|
4017
|
+
} finally{
|
4018
|
+
try {
|
4019
|
+
if (r && !r.done && (m = i["return"])) m.call(i);
|
4020
|
+
} finally{
|
4021
|
+
if (e) throw e.error;
|
4022
|
+
}
|
4023
|
+
}
|
4024
|
+
return ar;
|
4025
|
+
}
|
4026
|
+
function __spread() {
|
4027
|
+
for(var ar = [], i = 0; i < arguments.length; i++)ar = ar.concat(__read(arguments[i]));
|
4028
|
+
return ar;
|
4029
|
+
}
|
4030
|
+
var reconnecting_websocket_mjs_Event = /** @class */ function() {
|
4031
|
+
function Event1(type, target) {
|
4032
|
+
this.target = target;
|
4033
|
+
this.type = type;
|
4034
|
+
}
|
4035
|
+
return Event1;
|
4036
|
+
}();
|
4037
|
+
var reconnecting_websocket_mjs_ErrorEvent = /** @class */ function(_super) {
|
4038
|
+
__extends(ErrorEvent, _super);
|
4039
|
+
function ErrorEvent(error, target) {
|
4040
|
+
var _this = _super.call(this, 'error', target) || this;
|
4041
|
+
_this.message = error.message;
|
4042
|
+
_this.error = error;
|
4043
|
+
return _this;
|
4044
|
+
}
|
4045
|
+
return ErrorEvent;
|
4046
|
+
}(reconnecting_websocket_mjs_Event);
|
4047
|
+
var reconnecting_websocket_mjs_CloseEvent = /** @class */ function(_super) {
|
4048
|
+
__extends(CloseEvent, _super);
|
4049
|
+
function CloseEvent(code, reason, target) {
|
4050
|
+
if (void 0 === code) code = 1000;
|
4051
|
+
if (void 0 === reason) reason = '';
|
4052
|
+
var _this = _super.call(this, 'close', target) || this;
|
4053
|
+
_this.wasClean = true;
|
4054
|
+
_this.code = code;
|
4055
|
+
_this.reason = reason;
|
4056
|
+
return _this;
|
4057
|
+
}
|
4058
|
+
return CloseEvent;
|
4059
|
+
}(reconnecting_websocket_mjs_Event);
|
4060
|
+
/*!
|
4061
|
+
* Reconnecting WebSocket
|
4062
|
+
* by Pedro Ladaria <pedro.ladaria@gmail.com>
|
4063
|
+
* https://github.com/pladaria/reconnecting-websocket
|
4064
|
+
* License MIT
|
4065
|
+
*/ var getGlobalWebSocket = function() {
|
4066
|
+
if ('undefined' != typeof WebSocket) // @ts-ignore
|
4067
|
+
return WebSocket;
|
4068
|
+
};
|
4069
|
+
/**
|
4070
|
+
* Returns true if given argument looks like a WebSocket class
|
4071
|
+
*/ var isWebSocket = function(w) {
|
4072
|
+
return void 0 !== w && !!w && 2 === w.CLOSING;
|
4073
|
+
};
|
4074
|
+
var DEFAULT = {
|
4075
|
+
maxReconnectionDelay: 10000,
|
4076
|
+
minReconnectionDelay: 1000 + 4000 * Math.random(),
|
4077
|
+
minUptime: 5000,
|
4078
|
+
reconnectionDelayGrowFactor: 1.3,
|
4079
|
+
connectionTimeout: 4000,
|
4080
|
+
maxRetries: 1 / 0,
|
4081
|
+
maxEnqueuedMessages: 1 / 0,
|
4082
|
+
startClosed: false,
|
4083
|
+
debug: false
|
4084
|
+
};
|
4085
|
+
var reconnecting_websocket_mjs_ReconnectingWebSocket = /** @class */ function() {
|
4086
|
+
function ReconnectingWebSocket(url, protocols, options) {
|
4087
|
+
var _this = this;
|
4088
|
+
if (void 0 === options) options = {};
|
4089
|
+
this._listeners = {
|
4090
|
+
error: [],
|
4091
|
+
message: [],
|
4092
|
+
open: [],
|
4093
|
+
close: []
|
4094
|
+
};
|
4095
|
+
this._retryCount = -1;
|
4096
|
+
this._shouldReconnect = true;
|
4097
|
+
this._connectLock = false;
|
4098
|
+
this._binaryType = 'blob';
|
4099
|
+
this._closeCalled = false;
|
4100
|
+
this._messageQueue = [];
|
4101
|
+
/**
|
4102
|
+
* An event listener to be called when the WebSocket connection's readyState changes to CLOSED
|
4103
|
+
*/ this.onclose = null;
|
4104
|
+
/**
|
4105
|
+
* An event listener to be called when an error occurs
|
4106
|
+
*/ this.onerror = null;
|
4107
|
+
/**
|
4108
|
+
* An event listener to be called when a message is received from the server
|
4109
|
+
*/ this.onmessage = null;
|
4110
|
+
/**
|
4111
|
+
* An event listener to be called when the WebSocket connection's readyState changes to OPEN;
|
4112
|
+
* this indicates that the connection is ready to send and receive data
|
4113
|
+
*/ this.onopen = null;
|
4114
|
+
this._handleOpen = function(event) {
|
4115
|
+
_this._debug('open event');
|
4116
|
+
var _a = _this._options.minUptime, minUptime = void 0 === _a ? DEFAULT.minUptime : _a;
|
4117
|
+
clearTimeout(_this._connectTimeout);
|
4118
|
+
_this._uptimeTimeout = setTimeout(function() {
|
4119
|
+
return _this._acceptOpen();
|
4120
|
+
}, minUptime);
|
4121
|
+
_this._ws.binaryType = _this._binaryType;
|
4122
|
+
// send enqueued messages (messages sent before websocket open event)
|
4123
|
+
_this._messageQueue.forEach(function(message) {
|
4124
|
+
return _this._ws.send(message);
|
4125
|
+
});
|
4126
|
+
_this._messageQueue = [];
|
4127
|
+
if (_this.onopen) _this.onopen(event);
|
4128
|
+
_this._listeners.open.forEach(function(listener) {
|
4129
|
+
return _this._callEventListener(event, listener);
|
4130
|
+
});
|
4131
|
+
};
|
4132
|
+
this._handleMessage = function(event) {
|
4133
|
+
_this._debug('message event');
|
4134
|
+
if (_this.onmessage) _this.onmessage(event);
|
4135
|
+
_this._listeners.message.forEach(function(listener) {
|
4136
|
+
return _this._callEventListener(event, listener);
|
4137
|
+
});
|
4138
|
+
};
|
4139
|
+
this._handleError = function(event) {
|
4140
|
+
_this._debug('error event', event.message);
|
4141
|
+
_this._disconnect(void 0, 'TIMEOUT' === event.message ? 'timeout' : void 0);
|
4142
|
+
if (_this.onerror) _this.onerror(event);
|
4143
|
+
_this._debug('exec error listeners');
|
4144
|
+
_this._listeners.error.forEach(function(listener) {
|
4145
|
+
return _this._callEventListener(event, listener);
|
4146
|
+
});
|
4147
|
+
_this._connect();
|
4148
|
+
};
|
4149
|
+
this._handleClose = function(event) {
|
4150
|
+
_this._debug('close event');
|
4151
|
+
_this._clearTimeouts();
|
4152
|
+
if (_this._shouldReconnect) _this._connect();
|
4153
|
+
if (_this.onclose) _this.onclose(event);
|
4154
|
+
_this._listeners.close.forEach(function(listener) {
|
4155
|
+
return _this._callEventListener(event, listener);
|
4156
|
+
});
|
4157
|
+
};
|
4158
|
+
this._url = url;
|
4159
|
+
this._protocols = protocols;
|
4160
|
+
this._options = options;
|
4161
|
+
if (this._options.startClosed) this._shouldReconnect = false;
|
4162
|
+
this._connect();
|
4163
|
+
}
|
4164
|
+
Object.defineProperty(ReconnectingWebSocket, "CONNECTING", {
|
4165
|
+
get: function() {
|
4166
|
+
return 0;
|
4167
|
+
},
|
4168
|
+
enumerable: true,
|
4169
|
+
configurable: true
|
4170
|
+
});
|
4171
|
+
Object.defineProperty(ReconnectingWebSocket, "OPEN", {
|
4172
|
+
get: function() {
|
4173
|
+
return 1;
|
4174
|
+
},
|
4175
|
+
enumerable: true,
|
4176
|
+
configurable: true
|
4177
|
+
});
|
4178
|
+
Object.defineProperty(ReconnectingWebSocket, "CLOSING", {
|
4179
|
+
get: function() {
|
4180
|
+
return 2;
|
4181
|
+
},
|
4182
|
+
enumerable: true,
|
4183
|
+
configurable: true
|
4184
|
+
});
|
4185
|
+
Object.defineProperty(ReconnectingWebSocket, "CLOSED", {
|
4186
|
+
get: function() {
|
4187
|
+
return 3;
|
4188
|
+
},
|
4189
|
+
enumerable: true,
|
4190
|
+
configurable: true
|
4191
|
+
});
|
4192
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "CONNECTING", {
|
4193
|
+
get: function() {
|
4194
|
+
return ReconnectingWebSocket.CONNECTING;
|
4195
|
+
},
|
4196
|
+
enumerable: true,
|
4197
|
+
configurable: true
|
4198
|
+
});
|
4199
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "OPEN", {
|
4200
|
+
get: function() {
|
4201
|
+
return ReconnectingWebSocket.OPEN;
|
4202
|
+
},
|
4203
|
+
enumerable: true,
|
4204
|
+
configurable: true
|
4205
|
+
});
|
4206
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSING", {
|
4207
|
+
get: function() {
|
4208
|
+
return ReconnectingWebSocket.CLOSING;
|
4209
|
+
},
|
4210
|
+
enumerable: true,
|
4211
|
+
configurable: true
|
4212
|
+
});
|
4213
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSED", {
|
4214
|
+
get: function() {
|
4215
|
+
return ReconnectingWebSocket.CLOSED;
|
4216
|
+
},
|
4217
|
+
enumerable: true,
|
4218
|
+
configurable: true
|
4219
|
+
});
|
4220
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "binaryType", {
|
4221
|
+
get: function() {
|
4222
|
+
return this._ws ? this._ws.binaryType : this._binaryType;
|
4223
|
+
},
|
4224
|
+
set: function(value) {
|
4225
|
+
this._binaryType = value;
|
4226
|
+
if (this._ws) this._ws.binaryType = value;
|
4227
|
+
},
|
4228
|
+
enumerable: true,
|
4229
|
+
configurable: true
|
4230
|
+
});
|
4231
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "retryCount", {
|
4232
|
+
/**
|
4233
|
+
* Returns the number or connection retries
|
4234
|
+
*/ get: function() {
|
4235
|
+
return Math.max(this._retryCount, 0);
|
4236
|
+
},
|
4237
|
+
enumerable: true,
|
4238
|
+
configurable: true
|
4239
|
+
});
|
4240
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "bufferedAmount", {
|
4241
|
+
/**
|
4242
|
+
* The number of bytes of data that have been queued using calls to send() but not yet
|
4243
|
+
* transmitted to the network. This value resets to zero once all queued data has been sent.
|
4244
|
+
* This value does not reset to zero when the connection is closed; if you keep calling send(),
|
4245
|
+
* this will continue to climb. Read only
|
4246
|
+
*/ get: function() {
|
4247
|
+
var bytes = this._messageQueue.reduce(function(acc, message) {
|
4248
|
+
if ('string' == typeof message) acc += message.length; // not byte size
|
4249
|
+
else if (message instanceof Blob) acc += message.size;
|
4250
|
+
else acc += message.byteLength;
|
4251
|
+
return acc;
|
4252
|
+
}, 0);
|
4253
|
+
return bytes + (this._ws ? this._ws.bufferedAmount : 0);
|
4254
|
+
},
|
4255
|
+
enumerable: true,
|
4256
|
+
configurable: true
|
4257
|
+
});
|
4258
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "extensions", {
|
4259
|
+
/**
|
4260
|
+
* The extensions selected by the server. This is currently only the empty string or a list of
|
4261
|
+
* extensions as negotiated by the connection
|
4262
|
+
*/ get: function() {
|
4263
|
+
return this._ws ? this._ws.extensions : '';
|
4264
|
+
},
|
4265
|
+
enumerable: true,
|
4266
|
+
configurable: true
|
4267
|
+
});
|
4268
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "protocol", {
|
4269
|
+
/**
|
4270
|
+
* A string indicating the name of the sub-protocol the server selected;
|
4271
|
+
* this will be one of the strings specified in the protocols parameter when creating the
|
4272
|
+
* WebSocket object
|
4273
|
+
*/ get: function() {
|
4274
|
+
return this._ws ? this._ws.protocol : '';
|
4275
|
+
},
|
4276
|
+
enumerable: true,
|
4277
|
+
configurable: true
|
4278
|
+
});
|
4279
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "readyState", {
|
4280
|
+
/**
|
4281
|
+
* The current state of the connection; this is one of the Ready state constants
|
4282
|
+
*/ get: function() {
|
4283
|
+
if (this._ws) return this._ws.readyState;
|
4284
|
+
return this._options.startClosed ? ReconnectingWebSocket.CLOSED : ReconnectingWebSocket.CONNECTING;
|
4285
|
+
},
|
4286
|
+
enumerable: true,
|
4287
|
+
configurable: true
|
4288
|
+
});
|
4289
|
+
Object.defineProperty(ReconnectingWebSocket.prototype, "url", {
|
4290
|
+
/**
|
4291
|
+
* The URL as resolved by the constructor
|
4292
|
+
*/ get: function() {
|
4293
|
+
return this._ws ? this._ws.url : '';
|
4294
|
+
},
|
4295
|
+
enumerable: true,
|
4296
|
+
configurable: true
|
4297
|
+
});
|
4298
|
+
/**
|
4299
|
+
* Closes the WebSocket connection or connection attempt, if any. If the connection is already
|
4300
|
+
* CLOSED, this method does nothing
|
4301
|
+
*/ ReconnectingWebSocket.prototype.close = function(code, reason) {
|
4302
|
+
if (void 0 === code) code = 1000;
|
4303
|
+
this._closeCalled = true;
|
4304
|
+
this._shouldReconnect = false;
|
4305
|
+
this._clearTimeouts();
|
4306
|
+
if (!this._ws) {
|
4307
|
+
this._debug('close enqueued: no ws instance');
|
4308
|
+
return;
|
4309
|
+
}
|
4310
|
+
if (this._ws.readyState === this.CLOSED) {
|
4311
|
+
this._debug('close: already closed');
|
4312
|
+
return;
|
4313
|
+
}
|
4314
|
+
this._ws.close(code, reason);
|
4315
|
+
};
|
4316
|
+
/**
|
4317
|
+
* Closes the WebSocket connection or connection attempt and connects again.
|
4318
|
+
* Resets retry counter;
|
4319
|
+
*/ ReconnectingWebSocket.prototype.reconnect = function(code, reason) {
|
4320
|
+
this._shouldReconnect = true;
|
4321
|
+
this._closeCalled = false;
|
4322
|
+
this._retryCount = -1;
|
4323
|
+
if (this._ws && this._ws.readyState !== this.CLOSED) {
|
4324
|
+
this._disconnect(code, reason);
|
4325
|
+
this._connect();
|
4326
|
+
} else this._connect();
|
4327
|
+
};
|
4328
|
+
/**
|
4329
|
+
* Enqueue specified data to be transmitted to the server over the WebSocket connection
|
4330
|
+
*/ ReconnectingWebSocket.prototype.send = function(data) {
|
4331
|
+
if (this._ws && this._ws.readyState === this.OPEN) {
|
4332
|
+
this._debug('send', data);
|
4333
|
+
this._ws.send(data);
|
4334
|
+
} else {
|
4335
|
+
var _a = this._options.maxEnqueuedMessages, maxEnqueuedMessages = void 0 === _a ? DEFAULT.maxEnqueuedMessages : _a;
|
4336
|
+
if (this._messageQueue.length < maxEnqueuedMessages) {
|
4337
|
+
this._debug('enqueue', data);
|
4338
|
+
this._messageQueue.push(data);
|
4339
|
+
}
|
4340
|
+
}
|
4341
|
+
};
|
4342
|
+
/**
|
4343
|
+
* Register an event handler of a specific event type
|
4344
|
+
*/ ReconnectingWebSocket.prototype.addEventListener = function(type, listener) {
|
4345
|
+
if (this._listeners[type]) // @ts-ignore
|
4346
|
+
this._listeners[type].push(listener);
|
4347
|
+
};
|
4348
|
+
ReconnectingWebSocket.prototype.dispatchEvent = function(event) {
|
4349
|
+
var e_1, _a;
|
4350
|
+
var listeners = this._listeners[event.type];
|
4351
|
+
if (listeners) try {
|
4352
|
+
for(var listeners_1 = __values(listeners), listeners_1_1 = listeners_1.next(); !listeners_1_1.done; listeners_1_1 = listeners_1.next()){
|
4353
|
+
var listener = listeners_1_1.value;
|
4354
|
+
this._callEventListener(event, listener);
|
4355
|
+
}
|
4356
|
+
} catch (e_1_1) {
|
4357
|
+
e_1 = {
|
4358
|
+
error: e_1_1
|
4359
|
+
};
|
4360
|
+
} finally{
|
4361
|
+
try {
|
4362
|
+
if (listeners_1_1 && !listeners_1_1.done && (_a = listeners_1.return)) _a.call(listeners_1);
|
4363
|
+
} finally{
|
4364
|
+
if (e_1) throw e_1.error;
|
4365
|
+
}
|
4366
|
+
}
|
4367
|
+
return true;
|
4368
|
+
};
|
4369
|
+
/**
|
4370
|
+
* Removes an event listener
|
4371
|
+
*/ ReconnectingWebSocket.prototype.removeEventListener = function(type, listener) {
|
4372
|
+
if (this._listeners[type]) // @ts-ignore
|
4373
|
+
this._listeners[type] = this._listeners[type].filter(function(l) {
|
4374
|
+
return l !== listener;
|
4375
|
+
});
|
4376
|
+
};
|
4377
|
+
ReconnectingWebSocket.prototype._debug = function() {
|
4378
|
+
var args = [];
|
4379
|
+
for(var _i = 0; _i < arguments.length; _i++)args[_i] = arguments[_i];
|
4380
|
+
if (this._options.debug) // not using spread because compiled version uses Symbols
|
4381
|
+
// tslint:disable-next-line
|
4382
|
+
console.log.apply(console, __spread([
|
4383
|
+
'RWS>'
|
4384
|
+
], args));
|
4385
|
+
};
|
4386
|
+
ReconnectingWebSocket.prototype._getNextDelay = function() {
|
4387
|
+
var _a = this._options, _b = _a.reconnectionDelayGrowFactor, reconnectionDelayGrowFactor = void 0 === _b ? DEFAULT.reconnectionDelayGrowFactor : _b, _c = _a.minReconnectionDelay, minReconnectionDelay = void 0 === _c ? DEFAULT.minReconnectionDelay : _c, _d = _a.maxReconnectionDelay, maxReconnectionDelay = void 0 === _d ? DEFAULT.maxReconnectionDelay : _d;
|
4388
|
+
var delay = 0;
|
4389
|
+
if (this._retryCount > 0) {
|
4390
|
+
delay = minReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, this._retryCount - 1);
|
4391
|
+
if (delay > maxReconnectionDelay) delay = maxReconnectionDelay;
|
4392
|
+
}
|
4393
|
+
this._debug('next delay', delay);
|
4394
|
+
return delay;
|
4395
|
+
};
|
4396
|
+
ReconnectingWebSocket.prototype._wait = function() {
|
4397
|
+
var _this = this;
|
4398
|
+
return new Promise(function(resolve) {
|
4399
|
+
setTimeout(resolve, _this._getNextDelay());
|
4400
|
+
});
|
4401
|
+
};
|
4402
|
+
ReconnectingWebSocket.prototype._getNextUrl = function(urlProvider) {
|
4403
|
+
if ('string' == typeof urlProvider) return Promise.resolve(urlProvider);
|
4404
|
+
if ('function' == typeof urlProvider) {
|
4405
|
+
var url = urlProvider();
|
4406
|
+
if ('string' == typeof url) return Promise.resolve(url);
|
4407
|
+
if (!!url.then) return url;
|
4408
|
+
}
|
4409
|
+
throw Error('Invalid URL');
|
4410
|
+
};
|
4411
|
+
ReconnectingWebSocket.prototype._connect = function() {
|
4412
|
+
var _this = this;
|
4413
|
+
if (this._connectLock || !this._shouldReconnect) return;
|
4414
|
+
this._connectLock = true;
|
4415
|
+
var _a = this._options, _b = _a.maxRetries, maxRetries = void 0 === _b ? DEFAULT.maxRetries : _b, _c = _a.connectionTimeout, connectionTimeout = void 0 === _c ? DEFAULT.connectionTimeout : _c, _d = _a.WebSocket, WebSocket1 = void 0 === _d ? getGlobalWebSocket() : _d;
|
4416
|
+
if (this._retryCount >= maxRetries) {
|
4417
|
+
this._debug('max retries reached', this._retryCount, '>=', maxRetries);
|
4418
|
+
return;
|
4419
|
+
}
|
4420
|
+
this._retryCount++;
|
4421
|
+
this._debug('connect', this._retryCount);
|
4422
|
+
this._removeListeners();
|
4423
|
+
if (!isWebSocket(WebSocket1)) throw Error('No valid WebSocket class provided');
|
4424
|
+
this._wait().then(function() {
|
4425
|
+
return _this._getNextUrl(_this._url);
|
4426
|
+
}).then(function(url) {
|
4427
|
+
// close could be called before creating the ws
|
4428
|
+
if (_this._closeCalled) return;
|
4429
|
+
_this._debug('connect', {
|
4430
|
+
url: url,
|
4431
|
+
protocols: _this._protocols
|
4432
|
+
});
|
4433
|
+
_this._ws = _this._protocols ? new WebSocket1(url, _this._protocols) : new WebSocket1(url);
|
4434
|
+
_this._ws.binaryType = _this._binaryType;
|
4435
|
+
_this._connectLock = false;
|
4436
|
+
_this._addListeners();
|
4437
|
+
_this._connectTimeout = setTimeout(function() {
|
4438
|
+
return _this._handleTimeout();
|
4439
|
+
}, connectionTimeout);
|
4440
|
+
});
|
4441
|
+
};
|
4442
|
+
ReconnectingWebSocket.prototype._handleTimeout = function() {
|
4443
|
+
this._debug('timeout event');
|
4444
|
+
this._handleError(new reconnecting_websocket_mjs_ErrorEvent(Error('TIMEOUT'), this));
|
4445
|
+
};
|
4446
|
+
ReconnectingWebSocket.prototype._disconnect = function(code, reason) {
|
4447
|
+
if (void 0 === code) code = 1000;
|
4448
|
+
this._clearTimeouts();
|
4449
|
+
if (!this._ws) return;
|
4450
|
+
this._removeListeners();
|
4451
|
+
try {
|
4452
|
+
this._ws.close(code, reason);
|
4453
|
+
this._handleClose(new reconnecting_websocket_mjs_CloseEvent(code, reason, this));
|
4454
|
+
} catch (error) {
|
4455
|
+
// ignore
|
4456
|
+
}
|
4457
|
+
};
|
4458
|
+
ReconnectingWebSocket.prototype._acceptOpen = function() {
|
4459
|
+
this._debug('accept open');
|
4460
|
+
this._retryCount = 0;
|
4461
|
+
};
|
4462
|
+
ReconnectingWebSocket.prototype._callEventListener = function(event, listener) {
|
4463
|
+
if ('handleEvent' in listener) // @ts-ignore
|
4464
|
+
listener.handleEvent(event);
|
4465
|
+
else // @ts-ignore
|
4466
|
+
listener(event);
|
4467
|
+
};
|
4468
|
+
ReconnectingWebSocket.prototype._removeListeners = function() {
|
4469
|
+
if (!this._ws) return;
|
4470
|
+
this._debug('removeListeners');
|
4471
|
+
this._ws.removeEventListener('open', this._handleOpen);
|
4472
|
+
this._ws.removeEventListener('close', this._handleClose);
|
4473
|
+
this._ws.removeEventListener('message', this._handleMessage);
|
4474
|
+
// @ts-ignore
|
4475
|
+
this._ws.removeEventListener('error', this._handleError);
|
4476
|
+
};
|
4477
|
+
ReconnectingWebSocket.prototype._addListeners = function() {
|
4478
|
+
if (!this._ws) return;
|
4479
|
+
this._debug('addListeners');
|
4480
|
+
this._ws.addEventListener('open', this._handleOpen);
|
4481
|
+
this._ws.addEventListener('close', this._handleClose);
|
4482
|
+
this._ws.addEventListener('message', this._handleMessage);
|
4483
|
+
// @ts-ignore
|
4484
|
+
this._ws.addEventListener('error', this._handleError);
|
4485
|
+
};
|
4486
|
+
ReconnectingWebSocket.prototype._clearTimeouts = function() {
|
4487
|
+
clearTimeout(this._connectTimeout);
|
4488
|
+
clearTimeout(this._uptimeTimeout);
|
4489
|
+
};
|
4490
|
+
return ReconnectingWebSocket;
|
4491
|
+
}();
|
4492
|
+
/* ESM default export */ const reconnecting_websocket_mjs = reconnecting_websocket_mjs_ReconnectingWebSocket;
|
4493
|
+
// Common types (not exported)
|
4494
|
+
// Keep all existing exports but use the base types where applicable
|
4495
|
+
var types_WebsocketsEventType = /*#__PURE__*/ function(WebsocketsEventType) {
|
4496
|
+
// Common
|
4497
|
+
/** SDK error */ WebsocketsEventType["CLIENT_ERROR"] = "client_error";
|
4498
|
+
/** Connection closed */ WebsocketsEventType["CLOSED"] = "closed";
|
4499
|
+
// Error
|
4500
|
+
/** Received error event */ WebsocketsEventType["ERROR"] = "error";
|
4501
|
+
// v1/audio/speech
|
4502
|
+
/** Send text to server */ WebsocketsEventType["INPUT_TEXT_BUFFER_APPEND"] = "input_text_buffer.append";
|
4503
|
+
/** No text to send, after audio all received, can close connection */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETE"] = "input_text_buffer.complete";
|
4504
|
+
/** Send speech config to server */ WebsocketsEventType["SPEECH_UPDATE"] = "speech.update";
|
4505
|
+
/** Received `speech.updated` event */ WebsocketsEventType["SPEECH_UPDATED"] = "speech.updated";
|
4506
|
+
/** After speech created */ WebsocketsEventType["SPEECH_CREATED"] = "speech.created";
|
4507
|
+
/** Received `input_text_buffer.complete` event */ WebsocketsEventType["INPUT_TEXT_BUFFER_COMPLETED"] = "input_text_buffer.completed";
|
4508
|
+
/** Received `speech.update` event */ WebsocketsEventType["SPEECH_AUDIO_UPDATE"] = "speech.audio.update";
|
4509
|
+
/** All audio received, can close connection */ WebsocketsEventType["SPEECH_AUDIO_COMPLETED"] = "speech.audio.completed";
|
4510
|
+
// v1/audio/transcriptions
|
4511
|
+
/** Send audio to server */ WebsocketsEventType["INPUT_AUDIO_BUFFER_APPEND"] = "input_audio_buffer.append";
|
4512
|
+
/** No audio to send, after text all received, can close connection */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETE"] = "input_audio_buffer.complete";
|
4513
|
+
/** Send transcriptions config to server */ WebsocketsEventType["TRANSCRIPTIONS_UPDATE"] = "transcriptions.update";
|
4514
|
+
/** Send `input_audio_buffer.clear` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEAR"] = "input_audio_buffer.clear";
|
4515
|
+
/** After transcriptions created */ WebsocketsEventType["TRANSCRIPTIONS_CREATED"] = "transcriptions.created";
|
4516
|
+
/** Received `input_audio_buffer.complete` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_COMPLETED"] = "input_audio_buffer.completed";
|
4517
|
+
/** Received `transcriptions.update` event */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_UPDATE"] = "transcriptions.message.update";
|
4518
|
+
/** All audio received, can close connection */ WebsocketsEventType["TRANSCRIPTIONS_MESSAGE_COMPLETED"] = "transcriptions.message.completed";
|
4519
|
+
/** Received `input_audio_buffer.cleared` event */ WebsocketsEventType["INPUT_AUDIO_BUFFER_CLEARED"] = "input_audio_buffer.cleared";
|
4520
|
+
/** Received `transcriptions.updated` event */ WebsocketsEventType["TRANSCRIPTIONS_UPDATED"] = "transcriptions.updated";
|
4521
|
+
// v1/chat
|
4522
|
+
/** Send chat config to server */ WebsocketsEventType["CHAT_UPDATE"] = "chat.update";
|
4523
|
+
/** Send tool outputs to server */ WebsocketsEventType["CONVERSATION_CHAT_SUBMIT_TOOL_OUTPUTS"] = "conversation.chat.submit_tool_outputs";
|
4524
|
+
/** After chat created */ WebsocketsEventType["CHAT_CREATED"] = "chat.created";
|
4525
|
+
/** After chat updated */ WebsocketsEventType["CHAT_UPDATED"] = "chat.updated";
|
4526
|
+
/** Audio AST completed, chat started */ WebsocketsEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
|
4527
|
+
/** Message created */ WebsocketsEventType["CONVERSATION_MESSAGE_CREATE"] = "conversation.message.create";
|
4528
|
+
/** Clear conversation */ WebsocketsEventType["CONVERSATION_CLEAR"] = "conversation.clear";
|
4529
|
+
/** Chat in progress */ WebsocketsEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
|
4530
|
+
/** Get agent text message update */ WebsocketsEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
|
4531
|
+
/** Need plugin submit */ WebsocketsEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
|
4532
|
+
/** Message completed */ WebsocketsEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
|
4533
|
+
/** Get agent audio message update */ WebsocketsEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
|
4534
|
+
/** Audio message completed */ WebsocketsEventType["CONVERSATION_AUDIO_COMPLETED"] = "conversation.audio.completed";
|
4535
|
+
/** All message received, can close connection */ WebsocketsEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
|
4536
|
+
/** Chat failed */ WebsocketsEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
|
4537
|
+
/** Received `conversation.cleared` event */ WebsocketsEventType["CONVERSATION_CLEARED"] = "conversation.cleared";
|
4538
|
+
return WebsocketsEventType;
|
4539
|
+
}({});
|
4540
|
+
class WebSocketAPI {
|
4541
|
+
// Standard WebSocket properties
|
4542
|
+
get readyState() {
|
4543
|
+
return this.rws.readyState;
|
4544
|
+
}
|
4545
|
+
// Standard WebSocket methods
|
4546
|
+
send(data) {
|
4547
|
+
return this.rws.send(JSON.stringify(data));
|
4548
|
+
}
|
4549
|
+
close(code, reason) {
|
4550
|
+
return this.rws.close(code, reason);
|
4551
|
+
}
|
4552
|
+
reconnect(code, reason) {
|
4553
|
+
return this.rws.reconnect(code, reason);
|
4554
|
+
}
|
4555
|
+
// Event listener methods
|
4556
|
+
addEventListener(type, listener) {
|
4557
|
+
this.rws.addEventListener(type, listener);
|
4558
|
+
}
|
4559
|
+
removeEventListener(type, listener) {
|
4560
|
+
this.rws.removeEventListener(type, listener);
|
4561
|
+
}
|
4562
|
+
constructor(url, options = {}){
|
4563
|
+
// Event handler methods
|
4564
|
+
this.onmessage = null;
|
4565
|
+
this.onopen = null;
|
4566
|
+
this.onclose = null;
|
4567
|
+
this.onerror = null;
|
4568
|
+
const separator = url.includes('?') ? '&' : '?';
|
4569
|
+
const { authorization } = options.headers || {};
|
4570
|
+
this.rws = new reconnecting_websocket_mjs(`${url}${separator}authorization=${authorization}`, [], {
|
4571
|
+
WebSocket: utils_isBrowser() ? window.WebSocket : class extends browser_default() {
|
4572
|
+
constructor(url2, protocols){
|
4573
|
+
super(url2, protocols, {
|
4574
|
+
headers: options.headers
|
4575
|
+
});
|
4576
|
+
}
|
4577
|
+
},
|
4578
|
+
...options
|
4579
|
+
});
|
4580
|
+
this.rws.addEventListener('message', (event)=>{
|
4581
|
+
try {
|
4582
|
+
var _this_onmessage, _this;
|
4583
|
+
const data = JSON.parse(event.data);
|
4584
|
+
null === (_this_onmessage = (_this = this).onmessage) || void 0 === _this_onmessage || _this_onmessage.call(_this, data, event);
|
4585
|
+
} catch (error) {
|
4586
|
+
console.error('WebSocketAPI onmessage error', error);
|
4587
|
+
}
|
4588
|
+
});
|
4589
|
+
this.rws.addEventListener('open', (event)=>{
|
4590
|
+
var _this_onopen, _this;
|
4591
|
+
null === (_this_onopen = (_this = this).onopen) || void 0 === _this_onopen || _this_onopen.call(_this, event);
|
4592
|
+
});
|
4593
|
+
this.rws.addEventListener('close', (event)=>{
|
4594
|
+
var _this_onclose, _this;
|
4595
|
+
null === (_this_onclose = (_this = this).onclose) || void 0 === _this_onclose || _this_onclose.call(_this, event);
|
4596
|
+
});
|
4597
|
+
this.rws.addEventListener('error', (event)=>{
|
4598
|
+
var _event_target__req_res, _event_target__req, _event_target, _event_target__req_res1, _event_target__req1, _event_target1, _this_onerror, _this;
|
4599
|
+
const statusCode = null === (_event_target = event.target) || void 0 === _event_target ? void 0 : null === (_event_target__req = _event_target._req) || void 0 === _event_target__req ? void 0 : null === (_event_target__req_res = _event_target__req.res) || void 0 === _event_target__req_res ? void 0 : _event_target__req_res.statusCode;
|
4600
|
+
const rawHeaders = (null === (_event_target1 = event.target) || void 0 === _event_target1 ? void 0 : null === (_event_target__req1 = _event_target1._req) || void 0 === _event_target__req1 ? void 0 : null === (_event_target__req_res1 = _event_target__req1.res) || void 0 === _event_target__req_res1 ? void 0 : _event_target__req_res1.rawHeaders) || [];
|
4601
|
+
const logidIndex = rawHeaders.findIndex((header)=>'X-Tt-Logid' === header);
|
4602
|
+
const logid = -1 !== logidIndex ? rawHeaders[logidIndex + 1] : void 0;
|
4603
|
+
const error = {
|
4604
|
+
id: '0',
|
4605
|
+
event_type: types_WebsocketsEventType.ERROR,
|
4606
|
+
data: {
|
4607
|
+
code: -1,
|
4608
|
+
msg: 'WebSocket error'
|
4609
|
+
},
|
4610
|
+
detail: {
|
4611
|
+
logid
|
4612
|
+
}
|
4613
|
+
};
|
4614
|
+
if (401 === statusCode) {
|
4615
|
+
error.data.code = 401;
|
4616
|
+
error.data.msg = 'Unauthorized';
|
4617
|
+
} else if (403 === statusCode) {
|
4618
|
+
error.data.code = 403;
|
4619
|
+
error.data.msg = 'Forbidden';
|
4620
|
+
} else {
|
4621
|
+
error.data.code = 500;
|
4622
|
+
error.data.msg = String(null == event ? void 0 : event.error) || 'WebSocket error';
|
4623
|
+
}
|
4624
|
+
null === (_this_onerror = (_this = this).onerror) || void 0 === _this_onerror || _this_onerror.call(_this, error, event);
|
4625
|
+
});
|
4626
|
+
}
|
4627
|
+
}
|
4628
|
+
// EXTERNAL MODULE: os (ignored)
|
4629
|
+
var os_ignored_ = __webpack_require__("?9050");
|
4630
|
+
var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
|
4631
|
+
var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.20","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":"./src/index.ts"},"main":"src/index.ts","module":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false,"node-fetch":false},"types":"src/index.ts","files":["dist","LICENSE","README.md","README.zh-CN.md"],"scripts":{"build":"rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2","node-fetch":"^2.x","reconnecting-websocket":"^4.4.0","ws":"^8.11.0"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/node-fetch":"^2.x","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@types/ws":"^8.5.1","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"},"cozePublishConfig":{"exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
|
4632
|
+
const { version: version_version } = package_namespaceObject;
|
3909
4633
|
const getEnv = ()=>{
|
3910
4634
|
const nodeVersion = process.version.slice(1); // Remove 'v' prefix
|
3911
4635
|
const { platform } = process;
|
3912
4636
|
let osName = platform.toLowerCase();
|
3913
|
-
let osVersion =
|
4637
|
+
let osVersion = os_ignored_default().release();
|
3914
4638
|
if ('darwin' === platform) {
|
3915
4639
|
osName = 'macos';
|
3916
4640
|
// Try to parse the macOS version
|
3917
4641
|
try {
|
3918
|
-
const darwinVersion =
|
4642
|
+
const darwinVersion = os_ignored_default().release().split('.');
|
3919
4643
|
if (darwinVersion.length >= 2) {
|
3920
4644
|
const majorVersion = parseInt(darwinVersion[0], 10);
|
3921
4645
|
if (!isNaN(majorVersion) && majorVersion >= 9) {
|
@@ -3928,10 +4652,10 @@ const getEnv = ()=>{
|
|
3928
4652
|
}
|
3929
4653
|
} else if ('win32' === platform) {
|
3930
4654
|
osName = 'windows';
|
3931
|
-
osVersion =
|
4655
|
+
osVersion = os_ignored_default().release();
|
3932
4656
|
} else if ('linux' === platform) {
|
3933
4657
|
osName = 'linux';
|
3934
|
-
osVersion =
|
4658
|
+
osVersion = os_ignored_default().release();
|
3935
4659
|
}
|
3936
4660
|
return {
|
3937
4661
|
osName,
|
@@ -3941,12 +4665,12 @@ const getEnv = ()=>{
|
|
3941
4665
|
};
|
3942
4666
|
const getUserAgent = ()=>{
|
3943
4667
|
const { nodeVersion, osName, osVersion } = getEnv();
|
3944
|
-
return `coze-js/${
|
4668
|
+
return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
|
3945
4669
|
};
|
3946
4670
|
const getNodeClientUserAgent = ()=>{
|
3947
4671
|
const { osVersion, nodeVersion, osName } = getEnv();
|
3948
4672
|
const ua = {
|
3949
|
-
version:
|
4673
|
+
version: version_version,
|
3950
4674
|
lang: 'node',
|
3951
4675
|
lang_version: nodeVersion,
|
3952
4676
|
os_name: osName,
|
@@ -3995,7 +4719,7 @@ const getBrowserClientUserAgent = ()=>{
|
|
3995
4719
|
browserInfo.version = (null === (_userAgent_match5 = userAgent.match(/Version\/([0-9.]+)/)) || void 0 === _userAgent_match5 ? void 0 : _userAgent_match5[1]) || 'unknown';
|
3996
4720
|
}
|
3997
4721
|
const ua = {
|
3998
|
-
version:
|
4722
|
+
version: version_version,
|
3999
4723
|
browser: browserInfo.name,
|
4000
4724
|
browser_version: browserInfo.version,
|
4001
4725
|
os_name: osInfo.name,
|
@@ -4003,15 +4727,37 @@ const getBrowserClientUserAgent = ()=>{
|
|
4003
4727
|
};
|
4004
4728
|
return JSON.stringify(ua);
|
4005
4729
|
};
|
4006
|
-
|
4730
|
+
// EXTERNAL MODULE: node-fetch (ignored)
|
4731
|
+
var node_fetch_ignored_ = __webpack_require__("?8dee");
|
4732
|
+
var node_fetch_ignored_default = /*#__PURE__*/ __webpack_require__.n(node_fetch_ignored_);
|
4733
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
|
4007
4734
|
if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
|
4008
4735
|
if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
|
4009
4736
|
var _error_response;
|
4010
4737
|
return new TimeoutError(408, void 0, `Request timed out: ${error.message}`, null === (_error_response = error.response) || void 0 === _error_response ? void 0 : _error_response.headers);
|
4011
4738
|
}
|
4012
4739
|
if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
|
4013
|
-
|
4014
|
-
|
4740
|
+
else {
|
4741
|
+
var _error_response1, _error_response2, _error_response3;
|
4742
|
+
return error_APIError.generate((null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : _error_response1.status) || 500, null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : _error_response2.data, error.message, null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.headers);
|
4743
|
+
}
|
4744
|
+
};
|
4745
|
+
// node-fetch is used for streaming requests
|
4746
|
+
const adapterFetch = async (options)=>{
|
4747
|
+
const response = await node_fetch_ignored_default()(options.url, {
|
4748
|
+
body: options.data,
|
4749
|
+
...options
|
4750
|
+
});
|
4751
|
+
return {
|
4752
|
+
data: response.body,
|
4753
|
+
...response
|
4754
|
+
};
|
4755
|
+
};
|
4756
|
+
const isSupportNativeFetch = ()=>{
|
4757
|
+
if (utils_isBrowser()) return true;
|
4758
|
+
// native fetch is supported in node 18.0.0 or higher
|
4759
|
+
const version = process.version.slice(1);
|
4760
|
+
return compareVersions(version, '18.0.0') >= 0;
|
4015
4761
|
};
|
4016
4762
|
async function fetchAPI(url) {
|
4017
4763
|
let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
|
@@ -4024,10 +4770,10 @@ async function fetchAPI(url) {
|
|
4024
4770
|
const response = await axiosInstance({
|
4025
4771
|
url,
|
4026
4772
|
responseType: options.isStreaming ? 'stream' : 'json',
|
4027
|
-
adapter: options.isStreaming ? 'fetch' : void 0,
|
4773
|
+
adapter: options.isStreaming ? isSupportNativeFetch() ? 'fetch' : adapterFetch : void 0,
|
4028
4774
|
...options
|
4029
4775
|
}).catch((error)=>{
|
4030
|
-
throw
|
4776
|
+
throw fetcher_handleError(error);
|
4031
4777
|
});
|
4032
4778
|
return {
|
4033
4779
|
async *stream () {
|
@@ -4065,7 +4811,7 @@ async function fetchAPI(url) {
|
|
4065
4811
|
buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
|
4066
4812
|
}
|
4067
4813
|
} catch (error) {
|
4068
|
-
|
4814
|
+
fetcher_handleError(error);
|
4069
4815
|
}
|
4070
4816
|
},
|
4071
4817
|
json: ()=>response.data,
|
@@ -4089,8 +4835,11 @@ function isAxiosStatic(instance) {
|
|
4089
4835
|
}
|
4090
4836
|
/**
|
4091
4837
|
* default coze base URL is api.coze.com
|
4092
|
-
*/ const
|
4093
|
-
|
4838
|
+
*/ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
|
4839
|
+
/**
|
4840
|
+
* default base websocket URL is wss://ws.coze.com
|
4841
|
+
*/ const COZE_COM_BASE_WS_URL = 'wss://ws.coze.com';
|
4842
|
+
/* eslint-disable max-params */ class core_APIClient {
|
4094
4843
|
async getToken() {
|
4095
4844
|
if ('function' == typeof this.token) return await this.token();
|
4096
4845
|
return this.token;
|
@@ -4100,28 +4849,50 @@ function isAxiosStatic(instance) {
|
|
4100
4849
|
const headers = {
|
4101
4850
|
authorization: `Bearer ${token}`
|
4102
4851
|
};
|
4103
|
-
if (
|
4852
|
+
if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
|
4104
4853
|
else {
|
4105
4854
|
headers['User-Agent'] = getUserAgent();
|
4106
4855
|
headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
|
4107
4856
|
}
|
4108
|
-
const config =
|
4857
|
+
const config = mergeConfig(this.axiosOptions, options, {
|
4109
4858
|
headers
|
4859
|
+
}, {
|
4860
|
+
headers: this.headers || {}
|
4110
4861
|
});
|
4111
4862
|
config.method = method;
|
4112
4863
|
config.data = body;
|
4113
4864
|
return config;
|
4114
4865
|
}
|
4866
|
+
async buildWebsocketOptions(options) {
|
4867
|
+
const token = await this.getToken();
|
4868
|
+
const headers = {
|
4869
|
+
authorization: `Bearer ${token}`
|
4870
|
+
};
|
4871
|
+
if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
|
4872
|
+
else {
|
4873
|
+
headers['User-Agent'] = getUserAgent();
|
4874
|
+
headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
|
4875
|
+
}
|
4876
|
+
var _this__config_debug;
|
4877
|
+
const config = mergeConfig({
|
4878
|
+
debug: null !== (_this__config_debug = this._config.debug) && void 0 !== _this__config_debug && _this__config_debug
|
4879
|
+
}, this._config.websocketOptions, options, {
|
4880
|
+
headers
|
4881
|
+
}, {
|
4882
|
+
headers: this.headers || {}
|
4883
|
+
});
|
4884
|
+
return config;
|
4885
|
+
}
|
4115
4886
|
async makeRequest(apiUrl, method, body, isStream, options) {
|
4116
4887
|
const fullUrl = `${this.baseURL}${apiUrl}`;
|
4117
4888
|
const fetchOptions = await this.buildOptions(method, body, options);
|
4118
4889
|
fetchOptions.isStreaming = isStream;
|
4119
4890
|
fetchOptions.axiosInstance = this.axiosInstance;
|
4120
|
-
this.debugLog(`--- request url: ${fullUrl}`);
|
4121
|
-
this.debugLog('--- request options:', fetchOptions);
|
4891
|
+
this.debugLog(null == options ? void 0 : options.debug, `--- request url: ${fullUrl}`);
|
4892
|
+
this.debugLog(null == options ? void 0 : options.debug, '--- request options:', fetchOptions);
|
4122
4893
|
const { response, stream, json } = await fetchAPI(fullUrl, fetchOptions);
|
4123
|
-
this.debugLog(`--- response status: ${response.status}`);
|
4124
|
-
this.debugLog('--- response headers: ', response.headers);
|
4894
|
+
this.debugLog(null == options ? void 0 : options.debug, `--- response status: ${response.status}`);
|
4895
|
+
this.debugLog(null == options ? void 0 : options.debug, '--- response headers: ', response.headers);
|
4125
4896
|
var _response_headers;
|
4126
4897
|
// Taro use `header`
|
4127
4898
|
const contentType = (null !== (_response_headers = response.headers) && void 0 !== _response_headers ? _response_headers : response.header)['content-type'];
|
@@ -4129,7 +4900,7 @@ function isAxiosStatic(instance) {
|
|
4129
4900
|
if (contentType && contentType.includes('application/json')) {
|
4130
4901
|
const result = await json();
|
4131
4902
|
const { code, msg } = result;
|
4132
|
-
if (0 !== code && void 0 !== code) throw
|
4903
|
+
if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
|
4133
4904
|
}
|
4134
4905
|
return stream();
|
4135
4906
|
}
|
@@ -4137,7 +4908,7 @@ function isAxiosStatic(instance) {
|
|
4137
4908
|
{
|
4138
4909
|
const result = await json();
|
4139
4910
|
const { code, msg } = result;
|
4140
|
-
if (0 !== code && void 0 !== code) throw
|
4911
|
+
if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
|
4141
4912
|
return result;
|
4142
4913
|
}
|
4143
4914
|
}
|
@@ -4159,41 +4930,55 @@ function isAxiosStatic(instance) {
|
|
4159
4930
|
async delete(apiUrl, isStream, options) {
|
4160
4931
|
return this.makeRequest(apiUrl, 'DELETE', void 0, isStream, options);
|
4161
4932
|
}
|
4933
|
+
async makeWebsocket(apiUrl, options) {
|
4934
|
+
const fullUrl = `${this.baseWsURL}${apiUrl}`;
|
4935
|
+
const websocketOptions = await this.buildWebsocketOptions(options);
|
4936
|
+
this.debugLog(null == options ? void 0 : options.debug, `--- websocket url: ${fullUrl}`);
|
4937
|
+
this.debugLog(null == options ? void 0 : options.debug, '--- websocket options:', websocketOptions);
|
4938
|
+
const ws = new WebSocketAPI(fullUrl, websocketOptions);
|
4939
|
+
return ws;
|
4940
|
+
}
|
4162
4941
|
getConfig() {
|
4163
4942
|
return this._config;
|
4164
4943
|
}
|
4165
4944
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
4166
4945
|
debugLog() {
|
4167
|
-
|
4168
|
-
|
4946
|
+
let forceDebug = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
|
4947
|
+
for(var _len = arguments.length, msgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++)msgs[_key - 1] = arguments[_key];
|
4948
|
+
if (this.debug || forceDebug) console.debug(...msgs);
|
4169
4949
|
}
|
4170
4950
|
constructor(config){
|
4171
4951
|
this._config = config;
|
4172
|
-
this.baseURL = config.baseURL ||
|
4952
|
+
this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
|
4953
|
+
this.baseWsURL = config.baseWsURL || COZE_COM_BASE_WS_URL;
|
4173
4954
|
this.token = config.token;
|
4174
4955
|
this.axiosOptions = config.axiosOptions || {};
|
4175
4956
|
this.axiosInstance = config.axiosInstance;
|
4176
4957
|
this.debug = config.debug || false;
|
4177
4958
|
this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
|
4178
4959
|
this.headers = config.headers;
|
4179
|
-
if (
|
4180
|
-
}
|
4181
|
-
}
|
4182
|
-
|
4183
|
-
|
4184
|
-
|
4185
|
-
|
4186
|
-
|
4187
|
-
|
4188
|
-
|
4189
|
-
|
4190
|
-
|
4191
|
-
|
4192
|
-
|
4960
|
+
if (utils_isBrowser() && 'function' != typeof this.token && isPersonalAccessToken(this.token) && !this.allowPersonalAccessTokenInBrowser) throw new CozeError('Browser environments do not support authentication using Personal Access Token (PAT) by default.\nas it may expose secret API keys. \n\nPlease use OAuth2.0 authentication mechanism. see:\nhttps://www.coze.com/docs/developer_guides/oauth_apps?_lang=en \n\nIf you need to force use, please set the `allowPersonalAccessTokenInBrowser` option to `true`. \n\ne.g new CozeAPI({ token, allowPersonalAccessTokenInBrowser: true });\n\n');
|
4961
|
+
}
|
4962
|
+
}
|
4963
|
+
core_APIClient.APIError = error_APIError;
|
4964
|
+
core_APIClient.BadRequestError = BadRequestError;
|
4965
|
+
core_APIClient.AuthenticationError = AuthenticationError;
|
4966
|
+
core_APIClient.PermissionDeniedError = PermissionDeniedError;
|
4967
|
+
core_APIClient.NotFoundError = NotFoundError;
|
4968
|
+
core_APIClient.RateLimitError = RateLimitError;
|
4969
|
+
core_APIClient.InternalServerError = InternalServerError;
|
4970
|
+
core_APIClient.GatewayError = GatewayError;
|
4971
|
+
core_APIClient.TimeoutError = TimeoutError;
|
4972
|
+
core_APIClient.UserAbortError = APIUserAbortError;
|
4973
|
+
// EXTERNAL MODULE: crypto (ignored)
|
4974
|
+
__webpack_require__("?666e");
|
4975
|
+
// EXTERNAL MODULE: jsonwebtoken (ignored)
|
4976
|
+
__webpack_require__("?79fd");
|
4977
|
+
class CozeAPI extends core_APIClient {
|
4193
4978
|
constructor(...args){
|
4194
4979
|
super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
|
4195
4980
|
* @deprecated
|
4196
|
-
*/ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new
|
4981
|
+
*/ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new audio_Audio(this), this.templates = new Templates(this), this.websockets = new Websockets(this);
|
4197
4982
|
}
|
4198
4983
|
}
|
4199
4984
|
/**
|
@@ -38578,7 +39363,7 @@ var VERTC = _createClass(function e() {
|
|
38578
39363
|
+ * @param milliseconds The time to sleep in milliseconds
|
38579
39364
|
+ * @throws {Error} If milliseconds is negative
|
38580
39365
|
+ * @returns Promise that resolves after the specified duration
|
38581
|
-
+ */ const
|
39366
|
+
+ */ const src_utils_sleep = (milliseconds)=>{
|
38582
39367
|
if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
|
38583
39368
|
return new Promise((resolve)=>setTimeout(resolve, milliseconds));
|
38584
39369
|
};
|
@@ -42310,6 +43095,9 @@ class EngineClient extends RealtimeEventHandler {
|
|
42310
43095
|
throw e;
|
42311
43096
|
}
|
42312
43097
|
}
|
43098
|
+
getRtcEngine() {
|
43099
|
+
return this.engine;
|
43100
|
+
}
|
42313
43101
|
// eslint-disable-next-line max-params
|
42314
43102
|
constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false, videoConfig){
|
42315
43103
|
super(debug), this.joinUserId = '', this._AIAnsExtension = null, this._isSupportVideo = false;
|
@@ -42342,9 +43130,11 @@ class RealtimeClient extends RealtimeEventHandler {
|
|
42342
43130
|
// Step1 get token
|
42343
43131
|
roomInfo = await this._api.audio.rooms.create({
|
42344
43132
|
bot_id: botId,
|
42345
|
-
conversation_id: conversationId,
|
43133
|
+
conversation_id: conversationId || void 0,
|
42346
43134
|
voice_id: voiceId && voiceId.length > 0 ? voiceId : void 0,
|
42347
|
-
connector_id: this._config.connectorId
|
43135
|
+
connector_id: this._config.connectorId,
|
43136
|
+
uid: this._config.userId || void 0,
|
43137
|
+
workflow_id: this._config.workflowId || void 0
|
42348
43138
|
});
|
42349
43139
|
} catch (error) {
|
42350
43140
|
this.dispatch(event_handler_EventNames.ERROR, error);
|
@@ -42495,6 +43285,14 @@ class RealtimeClient extends RealtimeEventHandler {
|
|
42495
43285
|
});
|
42496
43286
|
}
|
42497
43287
|
/**
|
43288
|
+
* en: Get the RTC engine instance, for detail visit https://www.volcengine.com/docs/6348/104481
|
43289
|
+
*
|
43290
|
+
* zh: 获取 RTC 引擎实例,详情请访问 https://www.volcengine.com/docs/6348/104481
|
43291
|
+
*/ getRtcEngine() {
|
43292
|
+
var _this__client;
|
43293
|
+
return null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.getRtcEngine();
|
43294
|
+
}
|
43295
|
+
/**
|
42498
43296
|
* Constructor for initializing a RealtimeClient instance.
|
42499
43297
|
*
|
42500
43298
|
* 构造函数,初始化RealtimeClient实例。
|
@@ -42508,6 +43306,8 @@ class RealtimeClient extends RealtimeEventHandler {
|
|
42508
43306
|
* 可选,音色Id。
|
42509
43307
|
* @param config.conversationId - Optional, Conversation Id. |
|
42510
43308
|
* 可选,会话Id。
|
43309
|
+
* @param config.userId - Optional, User Id. |
|
43310
|
+
* 可选,用户Id。
|
42511
43311
|
* @param config.baseURL - Optional, defaults to "https://api.coze.cn". |
|
42512
43312
|
* 可选,默认值为 "https://api.coze.cn"。
|
42513
43313
|
* @param config.debug - Optional, defaults to false.
|