@coze/realtime-api 1.0.3 → 1.0.4-alpha.2d8e39

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/dist/umd/index.js CHANGED
@@ -7,11 +7,11 @@
7
7
  })(self, ()=>(()=>{
8
8
  "use strict";
9
9
  var __webpack_modules__ = {
10
- "?c628": function() {
10
+ "?666e": function() {
11
11
  /* (ignored) */ },
12
- "?9452": function() {
12
+ "?79fd": function() {
13
13
  /* (ignored) */ },
14
- "?e2b1": function() {
14
+ "?9050": function() {
15
15
  /* (ignored) */ }
16
16
  };
17
17
  /************************************************************************/ // The module cache
@@ -30,7 +30,22 @@
30
30
  // Return the exports of the module
31
31
  return module1.exports;
32
32
  }
33
- /************************************************************************/ // webpack/runtime/define_property_getters
33
+ /************************************************************************/ // webpack/runtime/compat_get_default_export
34
+ (()=>{
35
+ // getDefaultExport function for compatibility with non-ESM modules
36
+ __webpack_require__.n = function(module1) {
37
+ var getter = module1 && module1.__esModule ? function() {
38
+ return module1['default'];
39
+ } : function() {
40
+ return module1;
41
+ };
42
+ __webpack_require__.d(getter, {
43
+ a: getter
44
+ });
45
+ return getter;
46
+ };
47
+ })();
48
+ // webpack/runtime/define_property_getters
34
49
  (()=>{
35
50
  __webpack_require__.d = function(exports1, definition) {
36
51
  for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
@@ -86,7 +101,7 @@
86
101
  hasBrowserEnv: ()=>hasBrowserEnv,
87
102
  hasStandardBrowserEnv: ()=>hasStandardBrowserEnv,
88
103
  hasStandardBrowserWebWorkerEnv: ()=>hasStandardBrowserWebWorkerEnv,
89
- navigator: ()=>_navigator,
104
+ navigator: ()=>utils_navigator,
90
105
  origin: ()=>origin
91
106
  });
92
107
  // NAMESPACE OBJECT: ./src/utils.ts
@@ -96,480 +111,1043 @@
96
111
  checkDevicePermission: ()=>checkDevicePermission,
97
112
  checkPermission: ()=>checkPermission,
98
113
  getAudioDevices: ()=>getAudioDevices,
99
- sleep: ()=>utils_sleep
114
+ isScreenShareDevice: ()=>isScreenShareDevice,
115
+ isScreenShareSupported: ()=>isScreenShareSupported,
116
+ sleep: ()=>src_utils_sleep
100
117
  });
101
- function bind(fn, thisArg) {
102
- return function() {
103
- return fn.apply(thisArg, arguments);
104
- };
118
+ class APIResource {
119
+ constructor(client){
120
+ this._client = client;
121
+ }
105
122
  }
106
- // utils is a library of generic helper functions non-specific to axios
107
- const { toString: utils_toString } = Object.prototype;
108
- const { getPrototypeOf } = Object;
109
- const kindOf = ((cache)=>(thing)=>{
110
- const str = utils_toString.call(thing);
111
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
112
- })(Object.create(null));
113
- const kindOfTest = (type)=>{
114
- type = type.toLowerCase();
115
- return (thing)=>kindOf(thing) === type;
116
- };
117
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
118
- /**
119
- * Determine if a value is an Array
120
- *
121
- * @param {Object} val The value to test
122
- *
123
- * @returns {boolean} True if value is an Array, otherwise false
124
- */ const { isArray } = Array;
125
- /**
126
- * Determine if a value is undefined
127
- *
128
- * @param {*} val The value to test
129
- *
130
- * @returns {boolean} True if the value is undefined, otherwise false
131
- */ const isUndefined = typeOfTest('undefined');
132
- /**
133
- * Determine if a value is a Buffer
134
- *
135
- * @param {*} val The value to test
136
- *
137
- * @returns {boolean} True if value is a Buffer, otherwise false
138
- */ function isBuffer(val) {
139
- return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
123
+ /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
124
+ /**
125
+ * Create a new agent. | 调用接口创建一个新的智能体。
126
+ * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
127
+ * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
128
+ * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
129
+ * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
130
+ * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
131
+ * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
132
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
133
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
134
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
135
+ * @returns Information about the created bot. | 创建的 Bot 信息。
136
+ */ async create(params, options) {
137
+ const apiUrl = '/v1/bot/create';
138
+ const result = await this._client.post(apiUrl, params, false, options);
139
+ return result.data;
140
+ }
141
+ /**
142
+ * Update the configuration of an agent. | 调用接口修改智能体的配置。
143
+ * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
144
+ * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
145
+ * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
146
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
147
+ * @param params.name - Optional The name of the agent. | Bot 的名称。
148
+ * @param params.description - Optional The description of the agent. | Bot 的描述信息。
149
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
150
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
151
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
152
+ * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
153
+ * @returns Undefined | 无返回值
154
+ */ async update(params, options) {
155
+ const apiUrl = '/v1/bot/update';
156
+ const result = await this._client.post(apiUrl, params, false, options);
157
+ return result.data;
158
+ }
159
+ /**
160
+ * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
161
+ * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
162
+ * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
163
+ * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
164
+ * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
165
+ * @param params.page_size - Optional Pagination size. | 分页大小。
166
+ * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
167
+ * @returns List of published bots. | 已发布的 Bot 列表。
168
+ */ async list(params, options) {
169
+ const apiUrl = '/v1/space/published_bots_list';
170
+ const result = await this._client.get(apiUrl, params, false, options);
171
+ return result.data;
172
+ }
173
+ /**
174
+ * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
175
+ * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
176
+ * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
177
+ * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
178
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
179
+ * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
180
+ * @returns Undefined | 无返回值
181
+ */ async publish(params, options) {
182
+ const apiUrl = '/v1/bot/publish';
183
+ const result = await this._client.post(apiUrl, params, false, options);
184
+ return result.data;
185
+ }
186
+ /**
187
+ * Get the configuration information of the agent. | 获取指定智能体的配置信息。
188
+ * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
189
+ * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
190
+ * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
191
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
192
+ * @returns Information about the bot. | Bot 的配置信息。
193
+ */ async retrieve(params, options) {
194
+ const apiUrl = '/v1/bot/get_online_info';
195
+ const result = await this._client.get(apiUrl, params, false, options);
196
+ return result.data;
197
+ }
140
198
  }
141
- /**
142
- * Determine if a value is an ArrayBuffer
143
- *
144
- * @param {*} val The value to test
145
- *
146
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
147
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
148
- /**
149
- * Determine if a value is a view on an ArrayBuffer
150
- *
151
- * @param {*} val The value to test
152
- *
153
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
154
- */ function isArrayBufferView(val) {
155
- let result;
156
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
157
- return result;
199
+ /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
200
+ let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
201
+ try {
202
+ return JSON.parse(jsonString);
203
+ } catch (error) {
204
+ return defaultValue;
205
+ }
158
206
  }
159
- /**
160
- * Determine if a value is a String
161
- *
162
- * @param {*} val The value to test
163
- *
164
- * @returns {boolean} True if value is a String, otherwise false
165
- */ const isString = typeOfTest('string');
166
- /**
167
- * Determine if a value is a Function
168
- *
169
- * @param {*} val The value to test
170
- * @returns {boolean} True if value is a Function, otherwise false
171
- */ const isFunction = typeOfTest('function');
172
- /**
173
- * Determine if a value is a Number
174
- *
175
- * @param {*} val The value to test
176
- *
177
- * @returns {boolean} True if value is a Number, otherwise false
178
- */ const isNumber = typeOfTest('number');
179
- /**
180
- * Determine if a value is an Object
181
- *
182
- * @param {*} thing The value to test
183
- *
184
- * @returns {boolean} True if value is an Object, otherwise false
185
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
186
- /**
187
- * Determine if a value is a Boolean
188
- *
189
- * @param {*} thing The value to test
190
- * @returns {boolean} True if value is a Boolean, otherwise false
191
- */ const isBoolean = (thing)=>true === thing || false === thing;
192
- /**
193
- * Determine if a value is a plain Object
194
- *
195
- * @param {*} val The value to test
196
- *
197
- * @returns {boolean} True if value is a plain Object, otherwise false
198
- */ const isPlainObject = (val)=>{
199
- if ('object' !== kindOf(val)) return false;
200
- const prototype = getPrototypeOf(val);
201
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
202
- };
203
- /**
204
- * Determine if a value is a Date
205
- *
206
- * @param {*} val The value to test
207
- *
208
- * @returns {boolean} True if value is a Date, otherwise false
209
- */ const isDate = kindOfTest('Date');
210
- /**
211
- * Determine if a value is a File
212
- *
213
- * @param {*} val The value to test
214
- *
215
- * @returns {boolean} True if value is a File, otherwise false
216
- */ const isFile = kindOfTest('File');
217
- /**
218
- * Determine if a value is a Blob
219
- *
220
- * @param {*} val The value to test
221
- *
222
- * @returns {boolean} True if value is a Blob, otherwise false
223
- */ const isBlob = kindOfTest('Blob');
224
- /**
225
- * Determine if a value is a FileList
226
- *
227
- * @param {*} val The value to test
228
- *
229
- * @returns {boolean} True if value is a File, otherwise false
230
- */ const utils_isFileList = kindOfTest('FileList');
231
- /**
232
- * Determine if a value is a Stream
233
- *
234
- * @param {*} val The value to test
235
- *
236
- * @returns {boolean} True if value is a Stream, otherwise false
237
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
238
- /**
239
- * Determine if a value is a FormData
240
- *
241
- * @param {*} thing The value to test
242
- *
243
- * @returns {boolean} True if value is an FormData, otherwise false
244
- */ const utils_isFormData = (thing)=>{
245
- let kind;
246
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
247
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
248
- };
249
- /**
250
- * Determine if a value is a URLSearchParams object
251
- *
252
- * @param {*} val The value to test
253
- *
254
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
255
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
256
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
257
- 'ReadableStream',
258
- 'Request',
259
- 'Response',
260
- 'Headers'
261
- ].map(kindOfTest);
262
- /**
263
- * Trim excess whitespace off the beginning and end of a string
264
- *
265
- * @param {String} str The String to trim
266
- *
267
- * @returns {String} The String freed of excess whitespace
268
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
269
- /**
270
- * Iterate over an Array or an Object invoking a function for each item.
271
- *
272
- * If `obj` is an Array callback will be called passing
273
- * the value, index, and complete array for each item.
274
- *
275
- * If 'obj' is an Object callback will be called passing
276
- * the value, key, and complete object for each property.
277
- *
278
- * @param {Object|Array} obj The object to iterate
279
- * @param {Function} fn The callback to invoke for each item
280
- *
281
- * @param {Boolean} [allOwnKeys = false]
282
- * @returns {any}
283
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
284
- // Don't bother if no value provided
285
- if (null == obj) return;
286
- let i;
287
- let l;
288
- // Force an array if not already something iterable
289
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
290
- obj
291
- ];
292
- if (isArray(obj)) // Iterate over array values
293
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
294
- else {
295
- // Iterate over object keys
296
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
297
- const len = keys.length;
298
- let key;
299
- for(i = 0; i < len; i++){
300
- key = keys[i];
301
- fn.call(null, obj[key], key, obj);
207
+ function utils_sleep(ms) {
208
+ return new Promise((resolve)=>{
209
+ setTimeout(resolve, ms);
210
+ });
211
+ }
212
+ function utils_isBrowser() {
213
+ return 'undefined' != typeof window;
214
+ }
215
+ function isPlainObject(obj) {
216
+ if ('object' != typeof obj || null === obj) return false;
217
+ const proto = Object.getPrototypeOf(obj);
218
+ if (null === proto) return true;
219
+ let baseProto = proto;
220
+ while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
221
+ return proto === baseProto;
222
+ }
223
+ function mergeConfig() {
224
+ for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
225
+ return objects.reduce((result, obj)=>{
226
+ if (void 0 === obj) return result || {};
227
+ for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
228
+ if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
229
+ else result[key] = obj[key];
230
+ }
231
+ return result;
232
+ }, {});
233
+ }
234
+ function isPersonalAccessToken(token) {
235
+ return null == token ? void 0 : token.startsWith('pat_');
236
+ }
237
+ /* eslint-disable max-params */ class CozeError extends Error {
238
+ }
239
+ class error_APIError extends CozeError {
240
+ static makeMessage(status, errorBody, message, headers) {
241
+ if (!errorBody && message) return message;
242
+ if (errorBody) {
243
+ const list = [];
244
+ const { code, msg, error } = errorBody;
245
+ if (code) list.push(`code: ${code}`);
246
+ if (msg) list.push(`msg: ${msg}`);
247
+ if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
248
+ const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
249
+ if (logId) list.push(`logid: ${logId}`);
250
+ const help_doc = null == error ? void 0 : error.help_doc;
251
+ if (help_doc) list.push(`help doc: ${help_doc}`);
252
+ return list.join(', ');
302
253
  }
254
+ if (status) return `http status code: ${status} (no body)`;
255
+ return '(no status code or body)';
256
+ }
257
+ static generate(status, errorResponse, message, headers) {
258
+ if (!status) return new APIConnectionError({
259
+ cause: castToError(errorResponse)
260
+ });
261
+ const error = errorResponse;
262
+ // https://www.coze.cn/docs/developer_guides/coze_error_codes
263
+ if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
264
+ if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
265
+ if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
266
+ if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
267
+ if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
268
+ if (408 === status) return new TimeoutError(status, error, message, headers);
269
+ if (502 === status) return new GatewayError(status, error, message, headers);
270
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
271
+ return new error_APIError(status, error, message, headers);
272
+ }
273
+ constructor(status, error, message, headers){
274
+ var _error_error, _error_error1;
275
+ super(`${error_APIError.makeMessage(status, error, message, headers)}`);
276
+ this.status = status;
277
+ this.headers = headers;
278
+ this.logid = null == headers ? void 0 : headers['x-tt-logid'];
279
+ // this.error = error;
280
+ this.code = null == error ? void 0 : error.code;
281
+ this.msg = null == error ? void 0 : error.msg;
282
+ this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
283
+ this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
284
+ this.rawError = error;
303
285
  }
304
286
  }
305
- function findKey(obj, key) {
306
- key = key.toLowerCase();
307
- const keys = Object.keys(obj);
308
- let i = keys.length;
309
- let _key;
310
- while(i-- > 0){
311
- _key = keys[i];
312
- if (key === _key.toLowerCase()) return _key;
287
+ class APIConnectionError extends error_APIError {
288
+ constructor({ message, cause }){
289
+ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
290
+ // if (cause) {
291
+ // this.cause = cause;
292
+ // }
313
293
  }
314
- return null;
315
294
  }
316
- const _global = (()=>{
317
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
318
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
319
- })();
320
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
321
- /**
322
- * Accepts varargs expecting each argument to be an object, then
323
- * immutably merges the properties of each object and returns result.
324
- *
325
- * When multiple objects contain the same key the later object in
326
- * the arguments list will take precedence.
327
- *
328
- * Example:
329
- *
330
- * ```js
331
- * var result = merge({foo: 123}, {foo: 456});
332
- * console.log(result.foo); // outputs 456
333
- * ```
334
- *
335
- * @param {Object} obj1 Object to merge
336
- *
337
- * @returns {Object} Result of all merge properties
338
- */ function utils_merge() {
339
- const { caseless } = isContextDefined(this) && this || {};
340
- const result = {};
341
- const assignValue = (val, key)=>{
342
- const targetKey = caseless && findKey(result, key) || key;
343
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
344
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
345
- else if (isArray(val)) result[targetKey] = val.slice();
346
- else result[targetKey] = val;
347
- };
348
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
349
- return result;
295
+ class APIUserAbortError extends error_APIError {
296
+ constructor(message){
297
+ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
298
+ }
350
299
  }
351
- /**
352
- * Extends object a by mutably adding to it the properties of object b.
353
- *
354
- * @param {Object} a The object to be extended
355
- * @param {Object} b The object to copy properties from
356
- * @param {Object} thisArg The object to bind function to
357
- *
358
- * @param {Boolean} [allOwnKeys]
359
- * @returns {Object} The resulting value of object a
360
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
361
- forEach(b, (val, key)=>{
362
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
363
- else a[key] = val;
364
- }, {
365
- allOwnKeys
366
- });
367
- return a;
368
- };
369
- /**
370
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
371
- *
372
- * @param {string} content with BOM
373
- *
374
- * @returns {string} content value without BOM
375
- */ const stripBOM = (content)=>{
376
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
377
- return content;
378
- };
379
- /**
380
- * Inherit the prototype methods from one constructor into another
381
- * @param {function} constructor
382
- * @param {function} superConstructor
383
- * @param {object} [props]
384
- * @param {object} [descriptors]
385
- *
386
- * @returns {void}
387
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
388
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
389
- constructor.prototype.constructor = constructor;
390
- Object.defineProperty(constructor, 'super', {
391
- value: superConstructor.prototype
392
- });
393
- props && Object.assign(constructor.prototype, props);
300
+ class BadRequestError extends error_APIError {
301
+ constructor(...args){
302
+ super(...args), this.name = 'BadRequestError', this.status = 400;
303
+ }
304
+ }
305
+ class AuthenticationError extends error_APIError {
306
+ constructor(...args){
307
+ super(...args), this.name = 'AuthenticationError', this.status = 401;
308
+ }
309
+ }
310
+ class PermissionDeniedError extends error_APIError {
311
+ constructor(...args){
312
+ super(...args), this.name = 'PermissionDeniedError', this.status = 403;
313
+ }
314
+ }
315
+ class NotFoundError extends error_APIError {
316
+ constructor(...args){
317
+ super(...args), this.name = 'NotFoundError', this.status = 404;
318
+ }
319
+ }
320
+ class TimeoutError extends error_APIError {
321
+ constructor(...args){
322
+ super(...args), this.name = 'TimeoutError', this.status = 408;
323
+ }
324
+ }
325
+ class RateLimitError extends error_APIError {
326
+ constructor(...args){
327
+ super(...args), this.name = 'RateLimitError', this.status = 429;
328
+ }
329
+ }
330
+ class InternalServerError extends error_APIError {
331
+ constructor(...args){
332
+ super(...args), this.name = 'InternalServerError', this.status = 500;
333
+ }
334
+ }
335
+ class GatewayError extends error_APIError {
336
+ constructor(...args){
337
+ super(...args), this.name = 'GatewayError', this.status = 502;
338
+ }
339
+ }
340
+ const castToError = (err)=>{
341
+ if (err instanceof Error) return err;
342
+ return new Error(err);
394
343
  };
395
- /**
396
- * Resolve object with deep prototype chain to a flat object
397
- * @param {Object} sourceObj source object
398
- * @param {Object} [destObj]
399
- * @param {Function|Boolean} [filter]
400
- * @param {Function} [propFilter]
401
- *
402
- * @returns {Object}
403
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
404
- let props;
405
- let i;
406
- let prop;
407
- const merged = {};
408
- destObj = destObj || {};
409
- // eslint-disable-next-line no-eq-null,eqeqeq
410
- if (null == sourceObj) return destObj;
411
- do {
412
- props = Object.getOwnPropertyNames(sourceObj);
413
- i = props.length;
414
- while(i-- > 0){
415
- prop = props[i];
416
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
417
- destObj[prop] = sourceObj[prop];
418
- merged[prop] = true;
419
- }
420
- }
421
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
422
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
423
- return destObj;
344
+ class Messages extends APIResource {
345
+ /**
346
+ * Get the list of messages in a chat. | 获取对话中的消息列表。
347
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
348
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
349
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
350
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
351
+ * @returns An array of chat messages. | 对话消息数组。
352
+ */ async list(conversation_id, chat_id, options) {
353
+ const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
354
+ const result = await this._client.get(apiUrl, void 0, false, options);
355
+ return result.data;
356
+ }
357
+ }
358
+ const uuid = ()=>(Math.random() * new Date().getTime()).toString();
359
+ const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
360
+ ...i,
361
+ content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
362
+ }));
363
+ class Chat extends APIResource {
364
+ /**
365
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
366
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
367
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
368
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
369
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
370
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
371
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
372
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
373
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
374
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
375
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
376
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
377
+ * @returns The data of the created chat. | 创建的对话数据。
378
+ */ async create(params, options) {
379
+ if (!params.user_id) params.user_id = uuid();
380
+ const { conversation_id, ...rest } = params;
381
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
382
+ const payload = {
383
+ ...rest,
384
+ additional_messages: handleAdditionalMessages(params.additional_messages),
385
+ stream: false
386
+ };
387
+ const result = await this._client.post(apiUrl, payload, false, options);
388
+ return result.data;
389
+ }
390
+ /**
391
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
392
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
393
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
394
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
395
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
396
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
397
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
398
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
399
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
400
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
401
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
402
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
403
+ * @returns
404
+ */ async createAndPoll(params, options) {
405
+ if (!params.user_id) params.user_id = uuid();
406
+ const { conversation_id, ...rest } = params;
407
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
408
+ const payload = {
409
+ ...rest,
410
+ additional_messages: handleAdditionalMessages(params.additional_messages),
411
+ stream: false
412
+ };
413
+ const result = await this._client.post(apiUrl, payload, false, options);
414
+ const chatId = result.data.id;
415
+ const conversationId = result.data.conversation_id;
416
+ let chat;
417
+ while(true){
418
+ await utils_sleep(100);
419
+ chat = await this.retrieve(conversationId, chatId);
420
+ if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
421
+ }
422
+ const messageList = await this.messages.list(conversationId, chatId);
423
+ return {
424
+ chat,
425
+ messages: messageList
426
+ };
427
+ }
428
+ /**
429
+ * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
430
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
431
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
432
+ * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
433
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
434
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
435
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
436
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
437
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
438
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
439
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
440
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
441
+ * @returns A stream of chat data. | 对话数据流。
442
+ */ async *stream(params, options) {
443
+ if (!params.user_id) params.user_id = uuid();
444
+ const { conversation_id, ...rest } = params;
445
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
446
+ const payload = {
447
+ ...rest,
448
+ additional_messages: handleAdditionalMessages(params.additional_messages),
449
+ stream: true
450
+ };
451
+ const result = await this._client.post(apiUrl, payload, true, options);
452
+ for await (const message of result)if ("done" === message.event) {
453
+ const ret = {
454
+ event: message.event,
455
+ data: '[DONE]'
456
+ };
457
+ yield ret;
458
+ } else try {
459
+ const ret = {
460
+ event: message.event,
461
+ data: JSON.parse(message.data)
462
+ };
463
+ yield ret;
464
+ } catch (error) {
465
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
466
+ }
467
+ }
468
+ /**
469
+ * Get the detailed information of the chat. | 查看对话的详细信息。
470
+ * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
471
+ * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
472
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
473
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
474
+ * @returns The data of the retrieved chat. | 检索到的对话数据。
475
+ */ async retrieve(conversation_id, chat_id, options) {
476
+ const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
477
+ const result = await this._client.post(apiUrl, void 0, false, options);
478
+ return result.data;
479
+ }
480
+ /**
481
+ * Cancel a chat session. | 取消对话会话。
482
+ * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
483
+ * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
484
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
485
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
486
+ * @returns The data of the canceled chat. | 取消的对话数据。
487
+ */ async cancel(conversation_id, chat_id, options) {
488
+ const apiUrl = '/v3/chat/cancel';
489
+ const payload = {
490
+ conversation_id,
491
+ chat_id
492
+ };
493
+ const result = await this._client.post(apiUrl, payload, false, options);
494
+ return result.data;
495
+ }
496
+ /**
497
+ * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
498
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
499
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
500
+ * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
501
+ * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
502
+ * @param params.chat_id - Required The ID of the chat. | 对话 ID。
503
+ * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
504
+ * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
505
+ * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
506
+ */ async *submitToolOutputs(params, options) {
507
+ const { conversation_id, chat_id, ...rest } = params;
508
+ const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
509
+ const payload = {
510
+ ...rest
511
+ };
512
+ if (false === params.stream) {
513
+ const response = await this._client.post(apiUrl, payload, false, options);
514
+ return response.data;
515
+ }
516
+ {
517
+ const result = await this._client.post(apiUrl, payload, true, options);
518
+ for await (const message of result)if ("done" === message.event) {
519
+ const ret = {
520
+ event: message.event,
521
+ data: '[DONE]'
522
+ };
523
+ yield ret;
524
+ } else try {
525
+ const ret = {
526
+ event: message.event,
527
+ data: JSON.parse(message.data)
528
+ };
529
+ yield ret;
530
+ } catch (error) {
531
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
532
+ }
533
+ }
534
+ }
535
+ constructor(...args){
536
+ super(...args), this.messages = new Messages(this._client);
537
+ }
538
+ }
539
+ var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
540
+ ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
541
+ ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
542
+ ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
543
+ ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
544
+ ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
545
+ ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
546
+ ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
547
+ ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
548
+ ChatEventType["DONE"] = "done";
549
+ ChatEventType["ERROR"] = "error";
550
+ return ChatEventType;
551
+ }({});
552
+ class messages_Messages extends APIResource {
553
+ /**
554
+ * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
555
+ * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
556
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
557
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
558
+ * @param params - Required The parameters for creating a message | 创建消息所需的参数
559
+ * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
560
+ * @param params.content - Required The content of the message. | 消息的内容。
561
+ * @param params.content_type - Required The type of the message content. | 消息内容的类型。
562
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
563
+ * @returns Information about the new message. | 消息详情。
564
+ */ async create(conversation_id, params, options) {
565
+ const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
566
+ const response = await this._client.post(apiUrl, params, false, options);
567
+ return response.data;
568
+ }
569
+ /**
570
+ * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
571
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
572
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
573
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
574
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
575
+ * @param params - Required The parameters for modifying a message | 修改消息所需的参数
576
+ * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
577
+ * @param params.content - Optional The content of the message. | 消息的内容。
578
+ * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
579
+ * @returns Information about the modified message. | 消息详情。
580
+ */ // eslint-disable-next-line max-params
581
+ async update(conversation_id, message_id, params, options) {
582
+ const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
583
+ const response = await this._client.post(apiUrl, params, false, options);
584
+ return response.message;
585
+ }
586
+ /**
587
+ * Get the detailed information of specified message. | 查看指定消息的详细信息。
588
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
589
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
590
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
591
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
592
+ * @returns Information about the message. | 消息详情。
593
+ */ async retrieve(conversation_id, message_id, options) {
594
+ const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
595
+ const response = await this._client.get(apiUrl, null, false, options);
596
+ return response.data;
597
+ }
598
+ /**
599
+ * List messages in a conversation. | 列出会话中的消息。
600
+ * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
601
+ * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
602
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
603
+ * @param params - Optional The parameters for listing messages | 列出消息所需的参数
604
+ * @param params.order - Optional The order of the messages. | 消息的顺序。
605
+ * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
606
+ * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
607
+ * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
608
+ * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
609
+ * @returns A list of messages. | 消息列表。
610
+ */ async list(conversation_id, params, options) {
611
+ const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
612
+ const response = await this._client.post(apiUrl, params, false, options);
613
+ return response;
614
+ }
615
+ /**
616
+ * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
617
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
618
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
619
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
620
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
621
+ * @returns Details of the deleted message. | 已删除的消息详情。
622
+ */ async delete(conversation_id, message_id, options) {
623
+ const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
624
+ const response = await this._client.post(apiUrl, void 0, false, options);
625
+ return response.data;
626
+ }
627
+ }
628
+ class Conversations extends APIResource {
629
+ /**
630
+ * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
631
+ * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
632
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
633
+ * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
634
+ * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
635
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
636
+ * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
637
+ * @returns Information about the created conversation. | 会话的基础信息。
638
+ */ async create(params, options) {
639
+ const apiUrl = '/v1/conversation/create';
640
+ const response = await this._client.post(apiUrl, params, false, options);
641
+ return response.data;
642
+ }
643
+ /**
644
+ * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
645
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
646
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
647
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
648
+ * @returns Information about the conversation. | 会话的基础信息。
649
+ */ async retrieve(conversation_id, options) {
650
+ const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
651
+ const response = await this._client.get(apiUrl, null, false, options);
652
+ return response.data;
653
+ }
654
+ /**
655
+ * List all conversations. | 列出 Bot 下所有会话。
656
+ * @param params
657
+ * @param params.bot_id - Required Bot ID. | Bot ID。
658
+ * @param params.page_num - Optional The page number. | 页码,默认值为 1。
659
+ * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
660
+ * @returns Information about the conversations. | 会话的信息。
661
+ */ async list(params, options) {
662
+ const apiUrl = '/v1/conversations';
663
+ const response = await this._client.get(apiUrl, params, false, options);
664
+ return response.data;
665
+ }
666
+ /**
667
+ * Clear a conversation. | 清空会话。
668
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
669
+ * @returns Information about the conversation session. | 会话的会话 ID。
670
+ */ async clear(conversation_id, options) {
671
+ const apiUrl = `/v1/conversations/${conversation_id}/clear`;
672
+ const response = await this._client.post(apiUrl, null, false, options);
673
+ return response.data;
674
+ }
675
+ constructor(...args){
676
+ super(...args), this.messages = new messages_Messages(this._client);
677
+ }
678
+ }
679
+ function bind(fn, thisArg) {
680
+ return function() {
681
+ return fn.apply(thisArg, arguments);
682
+ };
683
+ }
684
+ // utils is a library of generic helper functions non-specific to axios
685
+ const { toString: utils_toString } = Object.prototype;
686
+ const { getPrototypeOf } = Object;
687
+ const kindOf = ((cache)=>(thing)=>{
688
+ const str = utils_toString.call(thing);
689
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
690
+ })(Object.create(null));
691
+ const kindOfTest = (type)=>{
692
+ type = type.toLowerCase();
693
+ return (thing)=>kindOf(thing) === type;
424
694
  };
695
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
425
696
  /**
426
- * Determines whether a string ends with the characters of a specified string
697
+ * Determine if a value is an Array
427
698
  *
428
- * @param {String} str
429
- * @param {String} searchString
430
- * @param {Number} [position= 0]
699
+ * @param {Object} val The value to test
431
700
  *
432
- * @returns {boolean}
433
- */ const endsWith = (str, searchString, position)=>{
434
- str = String(str);
435
- if (void 0 === position || position > str.length) position = str.length;
436
- position -= searchString.length;
437
- const lastIndex = str.indexOf(searchString, position);
438
- return -1 !== lastIndex && lastIndex === position;
439
- };
701
+ * @returns {boolean} True if value is an Array, otherwise false
702
+ */ const { isArray } = Array;
440
703
  /**
441
- * Returns new array from array like object or null if failed
704
+ * Determine if a value is undefined
442
705
  *
443
- * @param {*} [thing]
706
+ * @param {*} val The value to test
444
707
  *
445
- * @returns {?Array}
446
- */ const toArray = (thing)=>{
447
- if (!thing) return null;
448
- if (isArray(thing)) return thing;
449
- let i = thing.length;
450
- if (!isNumber(i)) return null;
451
- const arr = new Array(i);
452
- while(i-- > 0)arr[i] = thing[i];
453
- return arr;
454
- };
708
+ * @returns {boolean} True if the value is undefined, otherwise false
709
+ */ const isUndefined = typeOfTest('undefined');
455
710
  /**
456
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
457
- * thing passed in is an instance of Uint8Array
711
+ * Determine if a value is a Buffer
458
712
  *
459
- * @param {TypedArray}
713
+ * @param {*} val The value to test
460
714
  *
461
- * @returns {Array}
462
- */ // eslint-disable-next-line func-names
463
- const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
715
+ * @returns {boolean} True if value is a Buffer, otherwise false
716
+ */ function isBuffer(val) {
717
+ return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
718
+ }
464
719
  /**
465
- * For each entry in the object, call the function with the key and value.
720
+ * Determine if a value is an ArrayBuffer
466
721
  *
467
- * @param {Object<any, any>} obj - The object to iterate over.
468
- * @param {Function} fn - The function to call for each entry.
722
+ * @param {*} val The value to test
469
723
  *
470
- * @returns {void}
471
- */ const forEachEntry = (obj, fn)=>{
472
- const generator = obj && obj[Symbol.iterator];
473
- const iterator = generator.call(obj);
474
- let result;
475
- while((result = iterator.next()) && !result.done){
476
- const pair = result.value;
477
- fn.call(obj, pair[0], pair[1]);
478
- }
479
- };
724
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
725
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
480
726
  /**
481
- * It takes a regular expression and a string, and returns an array of all the matches
727
+ * Determine if a value is a view on an ArrayBuffer
482
728
  *
483
- * @param {string} regExp - The regular expression to match against.
484
- * @param {string} str - The string to search.
729
+ * @param {*} val The value to test
485
730
  *
486
- * @returns {Array<boolean>}
487
- */ const matchAll = (regExp, str)=>{
488
- let matches;
489
- const arr = [];
490
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
491
- return arr;
492
- };
493
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
494
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
495
- return p1.toUpperCase() + p2;
496
- });
497
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
731
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
732
+ */ function isArrayBufferView(val) {
733
+ let result;
734
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
735
+ return result;
736
+ }
498
737
  /**
499
- * Determine if a value is a RegExp object
738
+ * Determine if a value is a String
500
739
  *
501
740
  * @param {*} val The value to test
502
741
  *
503
- * @returns {boolean} True if value is a RegExp object, otherwise false
504
- */ const isRegExp = kindOfTest('RegExp');
505
- const reduceDescriptors = (obj, reducer)=>{
506
- const descriptors = Object.getOwnPropertyDescriptors(obj);
507
- const reducedDescriptors = {};
508
- forEach(descriptors, (descriptor, name)=>{
509
- let ret;
510
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
511
- });
512
- Object.defineProperties(obj, reducedDescriptors);
513
- };
742
+ * @returns {boolean} True if value is a String, otherwise false
743
+ */ const isString = typeOfTest('string');
514
744
  /**
515
- * Makes all methods read-only
516
- * @param {Object} obj
517
- */ const freezeMethods = (obj)=>{
518
- reduceDescriptors(obj, (descriptor, name)=>{
519
- // skip restricted props in strict mode
520
- if (isFunction(obj) && -1 !== [
521
- 'arguments',
522
- 'caller',
523
- 'callee'
524
- ].indexOf(name)) return false;
525
- const value = obj[name];
526
- if (!isFunction(value)) return;
527
- descriptor.enumerable = false;
528
- if ('writable' in descriptor) {
529
- descriptor.writable = false;
530
- return;
531
- }
532
- if (!descriptor.set) descriptor.set = ()=>{
533
- throw Error('Can not rewrite read-only method \'' + name + '\'');
534
- };
535
- });
536
- };
537
- const toObjectSet = (arrayOrString, delimiter)=>{
538
- const obj = {};
539
- const define1 = (arr)=>{
540
- arr.forEach((value)=>{
541
- obj[value] = true;
542
- });
543
- };
544
- isArray(arrayOrString) ? define1(arrayOrString) : define1(String(arrayOrString).split(delimiter));
545
- return obj;
546
- };
547
- const noop = ()=>{};
548
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
549
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
550
- const DIGIT = '0123456789';
551
- const ALPHABET = {
552
- DIGIT,
553
- ALPHA,
554
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
555
- };
556
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
557
- let str = '';
558
- const { length } = alphabet;
559
- while(size--)str += alphabet[Math.random() * length | 0];
560
- return str;
561
- };
745
+ * Determine if a value is a Function
746
+ *
747
+ * @param {*} val The value to test
748
+ * @returns {boolean} True if value is a Function, otherwise false
749
+ */ const isFunction = typeOfTest('function');
562
750
  /**
563
- * If the thing is a FormData object, return true, otherwise return false.
751
+ * Determine if a value is a Number
564
752
  *
565
- * @param {unknown} thing - The thing to check.
753
+ * @param {*} val The value to test
566
754
  *
567
- * @returns {boolean}
568
- */ function isSpecCompliantForm(thing) {
569
- return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
570
- }
571
- const toJSONObject = (obj)=>{
572
- const stack = new Array(10);
755
+ * @returns {boolean} True if value is a Number, otherwise false
756
+ */ const isNumber = typeOfTest('number');
757
+ /**
758
+ * Determine if a value is an Object
759
+ *
760
+ * @param {*} thing The value to test
761
+ *
762
+ * @returns {boolean} True if value is an Object, otherwise false
763
+ */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
764
+ /**
765
+ * Determine if a value is a Boolean
766
+ *
767
+ * @param {*} thing The value to test
768
+ * @returns {boolean} True if value is a Boolean, otherwise false
769
+ */ const isBoolean = (thing)=>true === thing || false === thing;
770
+ /**
771
+ * Determine if a value is a plain Object
772
+ *
773
+ * @param {*} val The value to test
774
+ *
775
+ * @returns {boolean} True if value is a plain Object, otherwise false
776
+ */ const utils_isPlainObject = (val)=>{
777
+ if ('object' !== kindOf(val)) return false;
778
+ const prototype = getPrototypeOf(val);
779
+ return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
780
+ };
781
+ /**
782
+ * Determine if a value is a Date
783
+ *
784
+ * @param {*} val The value to test
785
+ *
786
+ * @returns {boolean} True if value is a Date, otherwise false
787
+ */ const isDate = kindOfTest('Date');
788
+ /**
789
+ * Determine if a value is a File
790
+ *
791
+ * @param {*} val The value to test
792
+ *
793
+ * @returns {boolean} True if value is a File, otherwise false
794
+ */ const isFile = kindOfTest('File');
795
+ /**
796
+ * Determine if a value is a Blob
797
+ *
798
+ * @param {*} val The value to test
799
+ *
800
+ * @returns {boolean} True if value is a Blob, otherwise false
801
+ */ const isBlob = kindOfTest('Blob');
802
+ /**
803
+ * Determine if a value is a FileList
804
+ *
805
+ * @param {*} val The value to test
806
+ *
807
+ * @returns {boolean} True if value is a File, otherwise false
808
+ */ const utils_isFileList = kindOfTest('FileList');
809
+ /**
810
+ * Determine if a value is a Stream
811
+ *
812
+ * @param {*} val The value to test
813
+ *
814
+ * @returns {boolean} True if value is a Stream, otherwise false
815
+ */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
816
+ /**
817
+ * Determine if a value is a FormData
818
+ *
819
+ * @param {*} thing The value to test
820
+ *
821
+ * @returns {boolean} True if value is an FormData, otherwise false
822
+ */ const utils_isFormData = (thing)=>{
823
+ let kind;
824
+ return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
825
+ 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
826
+ };
827
+ /**
828
+ * Determine if a value is a URLSearchParams object
829
+ *
830
+ * @param {*} val The value to test
831
+ *
832
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
833
+ */ const isURLSearchParams = kindOfTest('URLSearchParams');
834
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
835
+ 'ReadableStream',
836
+ 'Request',
837
+ 'Response',
838
+ 'Headers'
839
+ ].map(kindOfTest);
840
+ /**
841
+ * Trim excess whitespace off the beginning and end of a string
842
+ *
843
+ * @param {String} str The String to trim
844
+ *
845
+ * @returns {String} The String freed of excess whitespace
846
+ */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
847
+ /**
848
+ * Iterate over an Array or an Object invoking a function for each item.
849
+ *
850
+ * If `obj` is an Array callback will be called passing
851
+ * the value, index, and complete array for each item.
852
+ *
853
+ * If 'obj' is an Object callback will be called passing
854
+ * the value, key, and complete object for each property.
855
+ *
856
+ * @param {Object|Array} obj The object to iterate
857
+ * @param {Function} fn The callback to invoke for each item
858
+ *
859
+ * @param {Boolean} [allOwnKeys = false]
860
+ * @returns {any}
861
+ */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
862
+ // Don't bother if no value provided
863
+ if (null == obj) return;
864
+ let i;
865
+ let l;
866
+ // Force an array if not already something iterable
867
+ if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
868
+ obj
869
+ ];
870
+ if (isArray(obj)) // Iterate over array values
871
+ for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
872
+ else {
873
+ // Iterate over object keys
874
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
875
+ const len = keys.length;
876
+ let key;
877
+ for(i = 0; i < len; i++){
878
+ key = keys[i];
879
+ fn.call(null, obj[key], key, obj);
880
+ }
881
+ }
882
+ }
883
+ function findKey(obj, key) {
884
+ key = key.toLowerCase();
885
+ const keys = Object.keys(obj);
886
+ let i = keys.length;
887
+ let _key;
888
+ while(i-- > 0){
889
+ _key = keys[i];
890
+ if (key === _key.toLowerCase()) return _key;
891
+ }
892
+ return null;
893
+ }
894
+ const _global = (()=>{
895
+ /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
896
+ return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
897
+ })();
898
+ const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
899
+ /**
900
+ * Accepts varargs expecting each argument to be an object, then
901
+ * immutably merges the properties of each object and returns result.
902
+ *
903
+ * When multiple objects contain the same key the later object in
904
+ * the arguments list will take precedence.
905
+ *
906
+ * Example:
907
+ *
908
+ * ```js
909
+ * var result = merge({foo: 123}, {foo: 456});
910
+ * console.log(result.foo); // outputs 456
911
+ * ```
912
+ *
913
+ * @param {Object} obj1 Object to merge
914
+ *
915
+ * @returns {Object} Result of all merge properties
916
+ */ function utils_merge() {
917
+ const { caseless } = isContextDefined(this) && this || {};
918
+ const result = {};
919
+ const assignValue = (val, key)=>{
920
+ const targetKey = caseless && findKey(result, key) || key;
921
+ if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
922
+ else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
923
+ else if (isArray(val)) result[targetKey] = val.slice();
924
+ else result[targetKey] = val;
925
+ };
926
+ for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
927
+ return result;
928
+ }
929
+ /**
930
+ * Extends object a by mutably adding to it the properties of object b.
931
+ *
932
+ * @param {Object} a The object to be extended
933
+ * @param {Object} b The object to copy properties from
934
+ * @param {Object} thisArg The object to bind function to
935
+ *
936
+ * @param {Boolean} [allOwnKeys]
937
+ * @returns {Object} The resulting value of object a
938
+ */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
939
+ forEach(b, (val, key)=>{
940
+ if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
941
+ else a[key] = val;
942
+ }, {
943
+ allOwnKeys
944
+ });
945
+ return a;
946
+ };
947
+ /**
948
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
949
+ *
950
+ * @param {string} content with BOM
951
+ *
952
+ * @returns {string} content value without BOM
953
+ */ const stripBOM = (content)=>{
954
+ if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
955
+ return content;
956
+ };
957
+ /**
958
+ * Inherit the prototype methods from one constructor into another
959
+ * @param {function} constructor
960
+ * @param {function} superConstructor
961
+ * @param {object} [props]
962
+ * @param {object} [descriptors]
963
+ *
964
+ * @returns {void}
965
+ */ const inherits = (constructor, superConstructor, props, descriptors)=>{
966
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
967
+ constructor.prototype.constructor = constructor;
968
+ Object.defineProperty(constructor, 'super', {
969
+ value: superConstructor.prototype
970
+ });
971
+ props && Object.assign(constructor.prototype, props);
972
+ };
973
+ /**
974
+ * Resolve object with deep prototype chain to a flat object
975
+ * @param {Object} sourceObj source object
976
+ * @param {Object} [destObj]
977
+ * @param {Function|Boolean} [filter]
978
+ * @param {Function} [propFilter]
979
+ *
980
+ * @returns {Object}
981
+ */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
982
+ let props;
983
+ let i;
984
+ let prop;
985
+ const merged = {};
986
+ destObj = destObj || {};
987
+ // eslint-disable-next-line no-eq-null,eqeqeq
988
+ if (null == sourceObj) return destObj;
989
+ do {
990
+ props = Object.getOwnPropertyNames(sourceObj);
991
+ i = props.length;
992
+ while(i-- > 0){
993
+ prop = props[i];
994
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
995
+ destObj[prop] = sourceObj[prop];
996
+ merged[prop] = true;
997
+ }
998
+ }
999
+ sourceObj = false !== filter && getPrototypeOf(sourceObj);
1000
+ }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
1001
+ return destObj;
1002
+ };
1003
+ /**
1004
+ * Determines whether a string ends with the characters of a specified string
1005
+ *
1006
+ * @param {String} str
1007
+ * @param {String} searchString
1008
+ * @param {Number} [position= 0]
1009
+ *
1010
+ * @returns {boolean}
1011
+ */ const endsWith = (str, searchString, position)=>{
1012
+ str = String(str);
1013
+ if (void 0 === position || position > str.length) position = str.length;
1014
+ position -= searchString.length;
1015
+ const lastIndex = str.indexOf(searchString, position);
1016
+ return -1 !== lastIndex && lastIndex === position;
1017
+ };
1018
+ /**
1019
+ * Returns new array from array like object or null if failed
1020
+ *
1021
+ * @param {*} [thing]
1022
+ *
1023
+ * @returns {?Array}
1024
+ */ const toArray = (thing)=>{
1025
+ if (!thing) return null;
1026
+ if (isArray(thing)) return thing;
1027
+ let i = thing.length;
1028
+ if (!isNumber(i)) return null;
1029
+ const arr = new Array(i);
1030
+ while(i-- > 0)arr[i] = thing[i];
1031
+ return arr;
1032
+ };
1033
+ /**
1034
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1035
+ * thing passed in is an instance of Uint8Array
1036
+ *
1037
+ * @param {TypedArray}
1038
+ *
1039
+ * @returns {Array}
1040
+ */ // eslint-disable-next-line func-names
1041
+ const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
1042
+ /**
1043
+ * For each entry in the object, call the function with the key and value.
1044
+ *
1045
+ * @param {Object<any, any>} obj - The object to iterate over.
1046
+ * @param {Function} fn - The function to call for each entry.
1047
+ *
1048
+ * @returns {void}
1049
+ */ const forEachEntry = (obj, fn)=>{
1050
+ const generator = obj && obj[Symbol.iterator];
1051
+ const iterator = generator.call(obj);
1052
+ let result;
1053
+ while((result = iterator.next()) && !result.done){
1054
+ const pair = result.value;
1055
+ fn.call(obj, pair[0], pair[1]);
1056
+ }
1057
+ };
1058
+ /**
1059
+ * It takes a regular expression and a string, and returns an array of all the matches
1060
+ *
1061
+ * @param {string} regExp - The regular expression to match against.
1062
+ * @param {string} str - The string to search.
1063
+ *
1064
+ * @returns {Array<boolean>}
1065
+ */ const matchAll = (regExp, str)=>{
1066
+ let matches;
1067
+ const arr = [];
1068
+ while(null !== (matches = regExp.exec(str)))arr.push(matches);
1069
+ return arr;
1070
+ };
1071
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
1072
+ const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
1073
+ return p1.toUpperCase() + p2;
1074
+ });
1075
+ /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
1076
+ /**
1077
+ * Determine if a value is a RegExp object
1078
+ *
1079
+ * @param {*} val The value to test
1080
+ *
1081
+ * @returns {boolean} True if value is a RegExp object, otherwise false
1082
+ */ const isRegExp = kindOfTest('RegExp');
1083
+ const reduceDescriptors = (obj, reducer)=>{
1084
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
1085
+ const reducedDescriptors = {};
1086
+ forEach(descriptors, (descriptor, name)=>{
1087
+ let ret;
1088
+ if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
1089
+ });
1090
+ Object.defineProperties(obj, reducedDescriptors);
1091
+ };
1092
+ /**
1093
+ * Makes all methods read-only
1094
+ * @param {Object} obj
1095
+ */ const freezeMethods = (obj)=>{
1096
+ reduceDescriptors(obj, (descriptor, name)=>{
1097
+ // skip restricted props in strict mode
1098
+ if (isFunction(obj) && -1 !== [
1099
+ 'arguments',
1100
+ 'caller',
1101
+ 'callee'
1102
+ ].indexOf(name)) return false;
1103
+ const value = obj[name];
1104
+ if (!isFunction(value)) return;
1105
+ descriptor.enumerable = false;
1106
+ if ('writable' in descriptor) {
1107
+ descriptor.writable = false;
1108
+ return;
1109
+ }
1110
+ if (!descriptor.set) descriptor.set = ()=>{
1111
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
1112
+ };
1113
+ });
1114
+ };
1115
+ const toObjectSet = (arrayOrString, delimiter)=>{
1116
+ const obj = {};
1117
+ const define1 = (arr)=>{
1118
+ arr.forEach((value)=>{
1119
+ obj[value] = true;
1120
+ });
1121
+ };
1122
+ isArray(arrayOrString) ? define1(arrayOrString) : define1(String(arrayOrString).split(delimiter));
1123
+ return obj;
1124
+ };
1125
+ const noop = ()=>{};
1126
+ const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
1127
+ const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
1128
+ const DIGIT = '0123456789';
1129
+ const ALPHABET = {
1130
+ DIGIT,
1131
+ ALPHA,
1132
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
1133
+ };
1134
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
1135
+ let str = '';
1136
+ const { length } = alphabet;
1137
+ while(size--)str += alphabet[Math.random() * length | 0];
1138
+ return str;
1139
+ };
1140
+ /**
1141
+ * If the thing is a FormData object, return true, otherwise return false.
1142
+ *
1143
+ * @param {unknown} thing - The thing to check.
1144
+ *
1145
+ * @returns {boolean}
1146
+ */ function isSpecCompliantForm(thing) {
1147
+ return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
1148
+ }
1149
+ const toJSONObject = (obj)=>{
1150
+ const stack = new Array(10);
573
1151
  const visit = (source, i)=>{
574
1152
  if (isObject(source)) {
575
1153
  if (stack.indexOf(source) >= 0) return;
@@ -616,7 +1194,7 @@
616
1194
  isNumber,
617
1195
  isBoolean,
618
1196
  isObject,
619
- isPlainObject,
1197
+ isPlainObject: utils_isPlainObject,
620
1198
  isReadableStream,
621
1199
  isRequest,
622
1200
  isResponse,
@@ -1058,7 +1636,7 @@
1058
1636
  ]
1059
1637
  };
1060
1638
  const hasBrowserEnv = 'undefined' != typeof window && 'undefined' != typeof document;
1061
- const _navigator = 'object' == typeof navigator && navigator || void 0;
1639
+ const utils_navigator = 'object' == typeof navigator && navigator || void 0;
1062
1640
  /**
1063
1641
  * Determine if we're running in a standard browser environment
1064
1642
  *
@@ -1075,11 +1653,11 @@
1075
1653
  * navigator.product -> 'NativeScript' or 'NS'
1076
1654
  *
1077
1655
  * @returns {boolean}
1078
- */ const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || [
1656
+ */ const hasStandardBrowserEnv = hasBrowserEnv && (!utils_navigator || [
1079
1657
  'ReactNative',
1080
1658
  'NativeScript',
1081
1659
  'NS'
1082
- ].indexOf(_navigator.product) < 0);
1660
+ ].indexOf(utils_navigator.product) < 0);
1083
1661
  /**
1084
1662
  * Determine if we're running in a standard browser webWorker environment
1085
1663
  *
@@ -1814,7 +2392,7 @@
1814
2392
  * @param {Object} config2
1815
2393
  *
1816
2394
  * @returns {Object} New object resulting from merging config2 to config1
1817
- */ function mergeConfig(config1, config2) {
2395
+ */ function mergeConfig_mergeConfig(config1, config2) {
1818
2396
  // eslint-disable-next-line no-param-reassign
1819
2397
  config2 = config2 || {};
1820
2398
  const config = {};
@@ -1884,7 +2462,7 @@
1884
2462
  return config;
1885
2463
  }
1886
2464
  /* ESM default export */ const resolveConfig = (config)=>{
1887
- const newConfig = mergeConfig({}, config);
2465
+ const newConfig = mergeConfig_mergeConfig({}, config);
1888
2466
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1889
2467
  newConfig.headers = headers = AxiosHeaders.from(headers);
1890
2468
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2490,7 +3068,7 @@
2490
3068
  config = config || {};
2491
3069
  config.url = configOrUrl;
2492
3070
  } else config = configOrUrl || {};
2493
- config = mergeConfig(this.defaults, config);
3071
+ config = mergeConfig_mergeConfig(this.defaults, config);
2494
3072
  const { transitional, paramsSerializer, headers } = config;
2495
3073
  if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2496
3074
  silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
@@ -2539,897 +3117,330 @@
2539
3117
  let len;
2540
3118
  if (!synchronousRequestInterceptors) {
2541
3119
  const chain = [
2542
- dispatchRequest.bind(this),
2543
- void 0
2544
- ];
2545
- chain.unshift.apply(chain, requestInterceptorChain);
2546
- chain.push.apply(chain, responseInterceptorChain);
2547
- len = chain.length;
2548
- promise = Promise.resolve(config);
2549
- while(i < len)promise = promise.then(chain[i++], chain[i++]);
2550
- return promise;
2551
- }
2552
- len = requestInterceptorChain.length;
2553
- let newConfig = config;
2554
- i = 0;
2555
- while(i < len){
2556
- const onFulfilled = requestInterceptorChain[i++];
2557
- const onRejected = requestInterceptorChain[i++];
2558
- try {
2559
- newConfig = onFulfilled(newConfig);
2560
- } catch (error) {
2561
- onRejected.call(this, error);
2562
- break;
2563
- }
2564
- }
2565
- try {
2566
- promise = dispatchRequest.call(this, newConfig);
2567
- } catch (error) {
2568
- return Promise.reject(error);
2569
- }
2570
- i = 0;
2571
- len = responseInterceptorChain.length;
2572
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2573
- return promise;
2574
- }
2575
- getUri(config) {
2576
- config = mergeConfig(this.defaults, config);
2577
- const fullPath = buildFullPath(config.baseURL, config.url);
2578
- return buildURL(fullPath, config.params, config.paramsSerializer);
2579
- }
2580
- }
2581
- // Provide aliases for supported request methods
2582
- utils.forEach([
2583
- 'delete',
2584
- 'get',
2585
- 'head',
2586
- 'options'
2587
- ], function(method) {
2588
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2589
- return this.request(mergeConfig(config || {}, {
2590
- method,
2591
- url,
2592
- data: (config || {}).data
2593
- }));
2594
- };
2595
- });
2596
- utils.forEach([
2597
- 'post',
2598
- 'put',
2599
- 'patch'
2600
- ], function(method) {
2601
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2602
- return function(url, data, config) {
2603
- return this.request(mergeConfig(config || {}, {
2604
- method,
2605
- headers: isForm ? {
2606
- 'Content-Type': 'multipart/form-data'
2607
- } : {},
2608
- url,
2609
- data
2610
- }));
2611
- };
2612
- }
2613
- Axios_Axios.prototype[method] = generateHTTPMethod();
2614
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2615
- });
2616
- /* ESM default export */ const Axios = Axios_Axios;
2617
- /**
2618
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2619
- *
2620
- * @param {Function} executor The executor function.
2621
- *
2622
- * @returns {CancelToken}
2623
- */ class CancelToken_CancelToken {
2624
- constructor(executor){
2625
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2626
- let resolvePromise;
2627
- this.promise = new Promise(function(resolve) {
2628
- resolvePromise = resolve;
2629
- });
2630
- const token = this;
2631
- // eslint-disable-next-line func-names
2632
- this.promise.then((cancel)=>{
2633
- if (!token._listeners) return;
2634
- let i = token._listeners.length;
2635
- while(i-- > 0)token._listeners[i](cancel);
2636
- token._listeners = null;
2637
- });
2638
- // eslint-disable-next-line func-names
2639
- this.promise.then = (onfulfilled)=>{
2640
- let _resolve;
2641
- // eslint-disable-next-line func-names
2642
- const promise = new Promise((resolve)=>{
2643
- token.subscribe(resolve);
2644
- _resolve = resolve;
2645
- }).then(onfulfilled);
2646
- promise.cancel = function() {
2647
- token.unsubscribe(_resolve);
2648
- };
2649
- return promise;
2650
- };
2651
- executor(function(message, config, request) {
2652
- if (token.reason) // Cancellation has already been requested
2653
- return;
2654
- token.reason = new CanceledError(message, config, request);
2655
- resolvePromise(token.reason);
2656
- });
2657
- }
2658
- /**
2659
- * Throws a `CanceledError` if cancellation has been requested.
2660
- */ throwIfRequested() {
2661
- if (this.reason) throw this.reason;
2662
- }
2663
- /**
2664
- * Subscribe to the cancel signal
2665
- */ subscribe(listener) {
2666
- if (this.reason) {
2667
- listener(this.reason);
2668
- return;
2669
- }
2670
- if (this._listeners) this._listeners.push(listener);
2671
- else this._listeners = [
2672
- listener
2673
- ];
2674
- }
2675
- /**
2676
- * Unsubscribe from the cancel signal
2677
- */ unsubscribe(listener) {
2678
- if (!this._listeners) return;
2679
- const index = this._listeners.indexOf(listener);
2680
- if (-1 !== index) this._listeners.splice(index, 1);
2681
- }
2682
- toAbortSignal() {
2683
- const controller = new AbortController();
2684
- const abort = (err)=>{
2685
- controller.abort(err);
2686
- };
2687
- this.subscribe(abort);
2688
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2689
- return controller.signal;
2690
- }
2691
- /**
2692
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2693
- * cancels the `CancelToken`.
2694
- */ static source() {
2695
- let cancel;
2696
- const token = new CancelToken_CancelToken(function(c) {
2697
- cancel = c;
2698
- });
2699
- return {
2700
- token,
2701
- cancel
2702
- };
2703
- }
2704
- }
2705
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2706
- /**
2707
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2708
- *
2709
- * Common use case would be to use `Function.prototype.apply`.
2710
- *
2711
- * ```js
2712
- * function f(x, y, z) {}
2713
- * var args = [1, 2, 3];
2714
- * f.apply(null, args);
2715
- * ```
2716
- *
2717
- * With `spread` this example can be re-written.
2718
- *
2719
- * ```js
2720
- * spread(function(x, y, z) {})([1, 2, 3]);
2721
- * ```
2722
- *
2723
- * @param {Function} callback
2724
- *
2725
- * @returns {Function}
2726
- */ function spread(callback) {
2727
- return function(arr) {
2728
- return callback.apply(null, arr);
2729
- };
2730
- }
2731
- /**
2732
- * Determines whether the payload is an error thrown by Axios
2733
- *
2734
- * @param {*} payload The value to test
2735
- *
2736
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2737
- */ function isAxiosError(payload) {
2738
- return utils.isObject(payload) && true === payload.isAxiosError;
2739
- }
2740
- const HttpStatusCode = {
2741
- Continue: 100,
2742
- SwitchingProtocols: 101,
2743
- Processing: 102,
2744
- EarlyHints: 103,
2745
- Ok: 200,
2746
- Created: 201,
2747
- Accepted: 202,
2748
- NonAuthoritativeInformation: 203,
2749
- NoContent: 204,
2750
- ResetContent: 205,
2751
- PartialContent: 206,
2752
- MultiStatus: 207,
2753
- AlreadyReported: 208,
2754
- ImUsed: 226,
2755
- MultipleChoices: 300,
2756
- MovedPermanently: 301,
2757
- Found: 302,
2758
- SeeOther: 303,
2759
- NotModified: 304,
2760
- UseProxy: 305,
2761
- Unused: 306,
2762
- TemporaryRedirect: 307,
2763
- PermanentRedirect: 308,
2764
- BadRequest: 400,
2765
- Unauthorized: 401,
2766
- PaymentRequired: 402,
2767
- Forbidden: 403,
2768
- NotFound: 404,
2769
- MethodNotAllowed: 405,
2770
- NotAcceptable: 406,
2771
- ProxyAuthenticationRequired: 407,
2772
- RequestTimeout: 408,
2773
- Conflict: 409,
2774
- Gone: 410,
2775
- LengthRequired: 411,
2776
- PreconditionFailed: 412,
2777
- PayloadTooLarge: 413,
2778
- UriTooLong: 414,
2779
- UnsupportedMediaType: 415,
2780
- RangeNotSatisfiable: 416,
2781
- ExpectationFailed: 417,
2782
- ImATeapot: 418,
2783
- MisdirectedRequest: 421,
2784
- UnprocessableEntity: 422,
2785
- Locked: 423,
2786
- FailedDependency: 424,
2787
- TooEarly: 425,
2788
- UpgradeRequired: 426,
2789
- PreconditionRequired: 428,
2790
- TooManyRequests: 429,
2791
- RequestHeaderFieldsTooLarge: 431,
2792
- UnavailableForLegalReasons: 451,
2793
- InternalServerError: 500,
2794
- NotImplemented: 501,
2795
- BadGateway: 502,
2796
- ServiceUnavailable: 503,
2797
- GatewayTimeout: 504,
2798
- HttpVersionNotSupported: 505,
2799
- VariantAlsoNegotiates: 506,
2800
- InsufficientStorage: 507,
2801
- LoopDetected: 508,
2802
- NotExtended: 510,
2803
- NetworkAuthenticationRequired: 511
2804
- };
2805
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2806
- HttpStatusCode[value] = key;
2807
- });
2808
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2809
- /**
2810
- * Create an instance of Axios
2811
- *
2812
- * @param {Object} defaultConfig The default config for the instance
2813
- *
2814
- * @returns {Axios} A new instance of Axios
2815
- */ function createInstance(defaultConfig) {
2816
- const context = new Axios(defaultConfig);
2817
- const instance = bind(Axios.prototype.request, context);
2818
- // Copy axios.prototype to instance
2819
- utils.extend(instance, Axios.prototype, context, {
2820
- allOwnKeys: true
2821
- });
2822
- // Copy context to instance
2823
- utils.extend(instance, context, null, {
2824
- allOwnKeys: true
2825
- });
2826
- // Factory for creating new instances
2827
- instance.create = function(instanceConfig) {
2828
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2829
- };
2830
- return instance;
2831
- }
2832
- // Create the default instance to be exported
2833
- const axios = createInstance(defaults);
2834
- // Expose Axios class to allow class inheritance
2835
- axios.Axios = Axios;
2836
- // Expose Cancel & CancelToken
2837
- axios.CanceledError = CanceledError;
2838
- axios.CancelToken = CancelToken;
2839
- axios.isCancel = isCancel;
2840
- axios.VERSION = VERSION;
2841
- axios.toFormData = toFormData;
2842
- // Expose AxiosError class
2843
- axios.AxiosError = core_AxiosError;
2844
- // alias for CanceledError for backward compatibility
2845
- axios.Cancel = axios.CanceledError;
2846
- // Expose all/spread
2847
- axios.all = function(promises) {
2848
- return Promise.all(promises);
2849
- };
2850
- axios.spread = spread;
2851
- // Expose isAxiosError
2852
- axios.isAxiosError = isAxiosError;
2853
- // Expose mergeConfig
2854
- axios.mergeConfig = mergeConfig;
2855
- axios.AxiosHeaders = AxiosHeaders;
2856
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2857
- axios.getAdapter = adapters_adapters.getAdapter;
2858
- axios.HttpStatusCode = helpers_HttpStatusCode;
2859
- axios.default = axios;
2860
- // this module should only have a default export
2861
- /* ESM default export */ const lib_axios = axios;
2862
- // This module is intended to unwrap Axios default export as named.
2863
- // Keep top-level export same with static properties
2864
- // so that it can keep same with es module or cjs
2865
- 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;
2866
- // EXTERNAL MODULE: os (ignored)
2867
- var os_ignored_ = __webpack_require__("?e2b1");
2868
- // EXTERNAL MODULE: crypto (ignored)
2869
- __webpack_require__("?c628");
2870
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2871
- __webpack_require__("?9452");
2872
- class APIResource {
2873
- constructor(client){
2874
- this._client = client;
2875
- }
2876
- }
2877
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2878
- /**
2879
- * Create a new agent. | 调用接口创建一个新的智能体。
2880
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2881
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2882
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2883
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2884
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2885
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2886
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2887
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2888
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2889
- * @returns Information about the created bot. | 创建的 Bot 信息。
2890
- */ async create(params, options) {
2891
- const apiUrl = '/v1/bot/create';
2892
- const result = await this._client.post(apiUrl, params, false, options);
2893
- return result.data;
2894
- }
2895
- /**
2896
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2897
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2898
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2899
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2900
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2901
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2902
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2903
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2904
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2905
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2906
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2907
- * @returns Undefined | 无返回值
2908
- */ async update(params, options) {
2909
- const apiUrl = '/v1/bot/update';
2910
- const result = await this._client.post(apiUrl, params, false, options);
2911
- return result.data;
2912
- }
2913
- /**
2914
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2915
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2916
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2917
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2918
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2919
- * @param params.page_size - Optional Pagination size. | 分页大小。
2920
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2921
- * @returns List of published bots. | 已发布的 Bot 列表。
2922
- */ async list(params, options) {
2923
- const apiUrl = '/v1/space/published_bots_list';
2924
- const result = await this._client.get(apiUrl, params, false, options);
2925
- return result.data;
2926
- }
2927
- /**
2928
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2929
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2930
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2931
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2932
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2933
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2934
- * @returns Undefined | 无返回值
2935
- */ async publish(params, options) {
2936
- const apiUrl = '/v1/bot/publish';
2937
- const result = await this._client.post(apiUrl, params, false, options);
2938
- return result.data;
2939
- }
2940
- /**
2941
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2942
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2943
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2944
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2945
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2946
- * @returns Information about the bot. | Bot 的配置信息。
2947
- */ async retrieve(params, options) {
2948
- const apiUrl = '/v1/bot/get_online_info';
2949
- const result = await this._client.get(apiUrl, params, false, options);
2950
- return result.data;
2951
- }
2952
- }
2953
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2954
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2955
- try {
2956
- return JSON.parse(jsonString);
2957
- } catch (error) {
2958
- return defaultValue;
2959
- }
2960
- }
2961
- function sleep(ms) {
2962
- return new Promise((resolve)=>{
2963
- setTimeout(resolve, ms);
2964
- });
2965
- }
2966
- function isBrowser() {
2967
- return 'undefined' != typeof window;
2968
- }
2969
- function esm_isPlainObject(obj) {
2970
- if ('object' != typeof obj || null === obj) return false;
2971
- const proto = Object.getPrototypeOf(obj);
2972
- if (null === proto) return true;
2973
- let baseProto = proto;
2974
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2975
- return proto === baseProto;
2976
- }
2977
- function esm_mergeConfig() {
2978
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2979
- return objects.reduce((result, obj)=>{
2980
- if (void 0 === obj) return result || {};
2981
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2982
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2983
- else result[key] = obj[key];
2984
- }
2985
- return result;
2986
- }, {});
2987
- }
2988
- function isPersonalAccessToken(token) {
2989
- return null == token ? void 0 : token.startsWith('pat_');
2990
- }
2991
- /* eslint-disable max-params */ class CozeError extends Error {
2992
- }
2993
- class APIError extends CozeError {
2994
- static makeMessage(status, errorBody, message, headers) {
2995
- if (!errorBody && message) return message;
2996
- if (errorBody) {
2997
- const list = [];
2998
- const { code, msg, error } = errorBody;
2999
- if (code) list.push(`code: ${code}`);
3000
- if (msg) list.push(`msg: ${msg}`);
3001
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
3002
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
3003
- if (logId) list.push(`logid: ${logId}`);
3004
- const help_doc = null == error ? void 0 : error.help_doc;
3005
- if (help_doc) list.push(`help doc: ${help_doc}`);
3006
- return list.join(', ');
3007
- }
3008
- if (status) return `http status code: ${status} (no body)`;
3009
- return '(no status code or body)';
3010
- }
3011
- static generate(status, errorResponse, message, headers) {
3012
- if (!status) return new APIConnectionError({
3013
- cause: castToError(errorResponse)
3014
- });
3015
- const error = errorResponse;
3016
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
3017
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3018
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3019
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3020
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3021
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3022
- if (408 === status) return new TimeoutError(status, error, message, headers);
3023
- if (502 === status) return new GatewayError(status, error, message, headers);
3024
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3025
- return new APIError(status, error, message, headers);
3026
- }
3027
- constructor(status, error, message, headers){
3028
- var _error_error, _error_error1;
3029
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3030
- this.status = status;
3031
- this.headers = headers;
3032
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3033
- // this.error = error;
3034
- this.code = null == error ? void 0 : error.code;
3035
- this.msg = null == error ? void 0 : error.msg;
3036
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3037
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3038
- this.rawError = error;
3039
- }
3040
- }
3041
- class APIConnectionError extends APIError {
3042
- constructor({ message, cause }){
3043
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3044
- // if (cause) {
3045
- // this.cause = cause;
3046
- // }
3047
- }
3048
- }
3049
- class APIUserAbortError extends APIError {
3050
- constructor(message){
3051
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3052
- }
3053
- }
3054
- class BadRequestError extends APIError {
3055
- constructor(...args){
3056
- super(...args), this.name = 'BadRequestError', this.status = 400;
3057
- }
3058
- }
3059
- class AuthenticationError extends APIError {
3060
- constructor(...args){
3061
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3062
- }
3063
- }
3064
- class PermissionDeniedError extends APIError {
3065
- constructor(...args){
3066
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3067
- }
3068
- }
3069
- class NotFoundError extends APIError {
3070
- constructor(...args){
3071
- super(...args), this.name = 'NotFoundError', this.status = 404;
3072
- }
3073
- }
3074
- class TimeoutError extends APIError {
3075
- constructor(...args){
3076
- super(...args), this.name = 'TimeoutError', this.status = 408;
3077
- }
3078
- }
3079
- class RateLimitError extends APIError {
3080
- constructor(...args){
3081
- super(...args), this.name = 'RateLimitError', this.status = 429;
3082
- }
3083
- }
3084
- class InternalServerError extends APIError {
3085
- constructor(...args){
3086
- super(...args), this.name = 'InternalServerError', this.status = 500;
3087
- }
3088
- }
3089
- class GatewayError extends APIError {
3090
- constructor(...args){
3091
- super(...args), this.name = 'GatewayError', this.status = 502;
3092
- }
3093
- }
3094
- const castToError = (err)=>{
3095
- if (err instanceof Error) return err;
3096
- return new Error(err);
3097
- };
3098
- class Messages extends APIResource {
3099
- /**
3100
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3101
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3102
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3103
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3104
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3105
- * @returns An array of chat messages. | 对话消息数组。
3106
- */ async list(conversation_id, chat_id, options) {
3107
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3108
- const result = await this._client.get(apiUrl, void 0, false, options);
3109
- return result.data;
3110
- }
3111
- }
3112
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3113
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3114
- ...i,
3115
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3116
- }));
3117
- class Chat extends APIResource {
3118
- /**
3119
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3120
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3121
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3122
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3123
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3124
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3125
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3126
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3127
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3128
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3129
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3130
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3131
- * @returns The data of the created chat. | 创建的对话数据。
3132
- */ async create(params, options) {
3133
- if (!params.user_id) params.user_id = uuid();
3134
- const { conversation_id, ...rest } = params;
3135
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3136
- const payload = {
3137
- ...rest,
3138
- additional_messages: handleAdditionalMessages(params.additional_messages),
3139
- stream: false
3140
- };
3141
- const result = await this._client.post(apiUrl, payload, false, options);
3142
- return result.data;
3143
- }
3144
- /**
3145
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3146
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3147
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3148
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3149
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3150
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3151
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3152
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3153
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3154
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3155
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3156
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3157
- * @returns
3158
- */ async createAndPoll(params, options) {
3159
- if (!params.user_id) params.user_id = uuid();
3160
- const { conversation_id, ...rest } = params;
3161
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3162
- const payload = {
3163
- ...rest,
3164
- additional_messages: handleAdditionalMessages(params.additional_messages),
3165
- stream: false
3166
- };
3167
- const result = await this._client.post(apiUrl, payload, false, options);
3168
- const chatId = result.data.id;
3169
- const conversationId = result.data.conversation_id;
3170
- let chat;
3171
- while(true){
3172
- await sleep(100);
3173
- chat = await this.retrieve(conversationId, chatId);
3174
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3175
- }
3176
- const messageList = await this.messages.list(conversationId, chatId);
3177
- return {
3178
- chat,
3179
- messages: messageList
3180
- };
3181
- }
3182
- /**
3183
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3184
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3185
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3186
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3187
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3188
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3189
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3190
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3191
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3192
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3193
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3194
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3195
- * @returns A stream of chat data. | 对话数据流。
3196
- */ async *stream(params, options) {
3197
- if (!params.user_id) params.user_id = uuid();
3198
- const { conversation_id, ...rest } = params;
3199
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3200
- const payload = {
3201
- ...rest,
3202
- additional_messages: handleAdditionalMessages(params.additional_messages),
3203
- stream: true
3204
- };
3205
- const result = await this._client.post(apiUrl, payload, true, options);
3206
- for await (const message of result)if ("done" === message.event) {
3207
- const ret = {
3208
- event: message.event,
3209
- data: '[DONE]'
3210
- };
3211
- yield ret;
3212
- } else try {
3213
- const ret = {
3214
- event: message.event,
3215
- data: JSON.parse(message.data)
3216
- };
3217
- yield ret;
3218
- } catch (error) {
3219
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3220
- }
3221
- }
3222
- /**
3223
- * Get the detailed information of the chat. | 查看对话的详细信息。
3224
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3225
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3226
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3227
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3228
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3229
- */ async retrieve(conversation_id, chat_id, options) {
3230
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3231
- const result = await this._client.post(apiUrl, void 0, false, options);
3232
- return result.data;
3233
- }
3234
- /**
3235
- * Cancel a chat session. | 取消对话会话。
3236
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3237
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3238
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3239
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3240
- * @returns The data of the canceled chat. | 取消的对话数据。
3241
- */ async cancel(conversation_id, chat_id, options) {
3242
- const apiUrl = '/v3/chat/cancel';
3243
- const payload = {
3244
- conversation_id,
3245
- chat_id
3246
- };
3247
- const result = await this._client.post(apiUrl, payload, false, options);
3248
- return result.data;
3249
- }
3250
- /**
3251
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3252
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3253
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3254
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3255
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3256
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3257
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3258
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3259
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3260
- */ async *submitToolOutputs(params, options) {
3261
- const { conversation_id, chat_id, ...rest } = params;
3262
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3263
- const payload = {
3264
- ...rest
3265
- };
3266
- if (false === params.stream) {
3267
- const response = await this._client.post(apiUrl, payload, false, options);
3268
- return response.data;
3120
+ dispatchRequest.bind(this),
3121
+ void 0
3122
+ ];
3123
+ chain.unshift.apply(chain, requestInterceptorChain);
3124
+ chain.push.apply(chain, responseInterceptorChain);
3125
+ len = chain.length;
3126
+ promise = Promise.resolve(config);
3127
+ while(i < len)promise = promise.then(chain[i++], chain[i++]);
3128
+ return promise;
3269
3129
  }
3270
- {
3271
- const result = await this._client.post(apiUrl, payload, true, options);
3272
- for await (const message of result)if ("done" === message.event) {
3273
- const ret = {
3274
- event: message.event,
3275
- data: '[DONE]'
3276
- };
3277
- yield ret;
3278
- } else try {
3279
- const ret = {
3280
- event: message.event,
3281
- data: JSON.parse(message.data)
3282
- };
3283
- yield ret;
3130
+ len = requestInterceptorChain.length;
3131
+ let newConfig = config;
3132
+ i = 0;
3133
+ while(i < len){
3134
+ const onFulfilled = requestInterceptorChain[i++];
3135
+ const onRejected = requestInterceptorChain[i++];
3136
+ try {
3137
+ newConfig = onFulfilled(newConfig);
3284
3138
  } catch (error) {
3285
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3139
+ onRejected.call(this, error);
3140
+ break;
3286
3141
  }
3287
3142
  }
3143
+ try {
3144
+ promise = dispatchRequest.call(this, newConfig);
3145
+ } catch (error) {
3146
+ return Promise.reject(error);
3147
+ }
3148
+ i = 0;
3149
+ len = responseInterceptorChain.length;
3150
+ while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3151
+ return promise;
3288
3152
  }
3289
- constructor(...args){
3290
- super(...args), this.messages = new Messages(this._client);
3153
+ getUri(config) {
3154
+ config = mergeConfig_mergeConfig(this.defaults, config);
3155
+ const fullPath = buildFullPath(config.baseURL, config.url);
3156
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3291
3157
  }
3292
3158
  }
3293
- var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
3294
- ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3295
- ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3296
- ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3297
- ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3298
- ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3299
- ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3300
- ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3301
- ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3302
- ChatEventType["DONE"] = "done";
3303
- ChatEventType["ERROR"] = "error";
3304
- return ChatEventType;
3305
- }({});
3306
- class messages_Messages extends APIResource {
3307
- /**
3308
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3309
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3310
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3311
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3312
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3313
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3314
- * @param params.content - Required The content of the message. | 消息的内容。
3315
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3316
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3317
- * @returns Information about the new message. | 消息详情。
3318
- */ async create(conversation_id, params, options) {
3319
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3320
- const response = await this._client.post(apiUrl, params, false, options);
3321
- return response.data;
3322
- }
3323
- /**
3324
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3325
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3326
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3327
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3328
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3329
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3330
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3331
- * @param params.content - Optional The content of the message. | 消息的内容。
3332
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3333
- * @returns Information about the modified message. | 消息详情。
3334
- */ // eslint-disable-next-line max-params
3335
- async update(conversation_id, message_id, params, options) {
3336
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3337
- const response = await this._client.post(apiUrl, params, false, options);
3338
- return response.message;
3339
- }
3340
- /**
3341
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3342
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3343
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3344
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3345
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3346
- * @returns Information about the message. | 消息详情。
3347
- */ async retrieve(conversation_id, message_id, options) {
3348
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3349
- const response = await this._client.get(apiUrl, null, false, options);
3350
- return response.data;
3159
+ // Provide aliases for supported request methods
3160
+ utils.forEach([
3161
+ 'delete',
3162
+ 'get',
3163
+ 'head',
3164
+ 'options'
3165
+ ], function(method) {
3166
+ /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
3167
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3168
+ method,
3169
+ url,
3170
+ data: (config || {}).data
3171
+ }));
3172
+ };
3173
+ });
3174
+ utils.forEach([
3175
+ 'post',
3176
+ 'put',
3177
+ 'patch'
3178
+ ], function(method) {
3179
+ /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
3180
+ return function(url, data, config) {
3181
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3182
+ method,
3183
+ headers: isForm ? {
3184
+ 'Content-Type': 'multipart/form-data'
3185
+ } : {},
3186
+ url,
3187
+ data
3188
+ }));
3189
+ };
3351
3190
  }
3352
- /**
3353
- * List messages in a conversation. | 列出会话中的消息。
3354
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3355
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3356
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3357
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3358
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3359
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3360
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3361
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3362
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3363
- * @returns A list of messages. | 消息列表。
3364
- */ async list(conversation_id, params, options) {
3365
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3366
- const response = await this._client.post(apiUrl, params, false, options);
3367
- return response;
3191
+ Axios_Axios.prototype[method] = generateHTTPMethod();
3192
+ Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3193
+ });
3194
+ /* ESM default export */ const Axios = Axios_Axios;
3195
+ /**
3196
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3197
+ *
3198
+ * @param {Function} executor The executor function.
3199
+ *
3200
+ * @returns {CancelToken}
3201
+ */ class CancelToken_CancelToken {
3202
+ constructor(executor){
3203
+ if ('function' != typeof executor) throw new TypeError('executor must be a function.');
3204
+ let resolvePromise;
3205
+ this.promise = new Promise(function(resolve) {
3206
+ resolvePromise = resolve;
3207
+ });
3208
+ const token = this;
3209
+ // eslint-disable-next-line func-names
3210
+ this.promise.then((cancel)=>{
3211
+ if (!token._listeners) return;
3212
+ let i = token._listeners.length;
3213
+ while(i-- > 0)token._listeners[i](cancel);
3214
+ token._listeners = null;
3215
+ });
3216
+ // eslint-disable-next-line func-names
3217
+ this.promise.then = (onfulfilled)=>{
3218
+ let _resolve;
3219
+ // eslint-disable-next-line func-names
3220
+ const promise = new Promise((resolve)=>{
3221
+ token.subscribe(resolve);
3222
+ _resolve = resolve;
3223
+ }).then(onfulfilled);
3224
+ promise.cancel = function() {
3225
+ token.unsubscribe(_resolve);
3226
+ };
3227
+ return promise;
3228
+ };
3229
+ executor(function(message, config, request) {
3230
+ if (token.reason) // Cancellation has already been requested
3231
+ return;
3232
+ token.reason = new CanceledError(message, config, request);
3233
+ resolvePromise(token.reason);
3234
+ });
3368
3235
  }
3369
3236
  /**
3370
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3371
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3372
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3373
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3374
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3375
- * @returns Details of the deleted message. | 已删除的消息详情。
3376
- */ async delete(conversation_id, message_id, options) {
3377
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3378
- const response = await this._client.post(apiUrl, void 0, false, options);
3379
- return response.data;
3237
+ * Throws a `CanceledError` if cancellation has been requested.
3238
+ */ throwIfRequested() {
3239
+ if (this.reason) throw this.reason;
3380
3240
  }
3381
- }
3382
- class Conversations extends APIResource {
3383
3241
  /**
3384
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3385
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3386
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3387
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3388
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3389
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3390
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3391
- * @returns Information about the created conversation. | 会话的基础信息。
3392
- */ async create(params, options) {
3393
- const apiUrl = '/v1/conversation/create';
3394
- const response = await this._client.post(apiUrl, params, false, options);
3395
- return response.data;
3242
+ * Subscribe to the cancel signal
3243
+ */ subscribe(listener) {
3244
+ if (this.reason) {
3245
+ listener(this.reason);
3246
+ return;
3247
+ }
3248
+ if (this._listeners) this._listeners.push(listener);
3249
+ else this._listeners = [
3250
+ listener
3251
+ ];
3396
3252
  }
3397
3253
  /**
3398
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3399
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3400
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3401
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3402
- * @returns Information about the conversation. | 会话的基础信息。
3403
- */ async retrieve(conversation_id, options) {
3404
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3405
- const response = await this._client.get(apiUrl, null, false, options);
3406
- return response.data;
3254
+ * Unsubscribe from the cancel signal
3255
+ */ unsubscribe(listener) {
3256
+ if (!this._listeners) return;
3257
+ const index = this._listeners.indexOf(listener);
3258
+ if (-1 !== index) this._listeners.splice(index, 1);
3407
3259
  }
3408
- /**
3409
- * List all conversations. | 列出 Bot 下所有会话。
3410
- * @param params
3411
- * @param params.bot_id - Required Bot ID. | Bot ID。
3412
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3413
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3414
- * @returns Information about the conversations. | 会话的信息。
3415
- */ async list(params, options) {
3416
- const apiUrl = '/v1/conversations';
3417
- const response = await this._client.get(apiUrl, params, false, options);
3418
- return response.data;
3260
+ toAbortSignal() {
3261
+ const controller = new AbortController();
3262
+ const abort = (err)=>{
3263
+ controller.abort(err);
3264
+ };
3265
+ this.subscribe(abort);
3266
+ controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
3267
+ return controller.signal;
3419
3268
  }
3420
3269
  /**
3421
- * Clear a conversation. | 清空会话。
3422
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3423
- * @returns Information about the conversation session. | 会话的会话 ID。
3424
- */ async clear(conversation_id, options) {
3425
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3426
- const response = await this._client.post(apiUrl, null, false, options);
3427
- return response.data;
3428
- }
3429
- constructor(...args){
3430
- super(...args), this.messages = new messages_Messages(this._client);
3270
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3271
+ * cancels the `CancelToken`.
3272
+ */ static source() {
3273
+ let cancel;
3274
+ const token = new CancelToken_CancelToken(function(c) {
3275
+ cancel = c;
3276
+ });
3277
+ return {
3278
+ token,
3279
+ cancel
3280
+ };
3431
3281
  }
3432
3282
  }
3283
+ /* ESM default export */ const CancelToken = CancelToken_CancelToken;
3284
+ /**
3285
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3286
+ *
3287
+ * Common use case would be to use `Function.prototype.apply`.
3288
+ *
3289
+ * ```js
3290
+ * function f(x, y, z) {}
3291
+ * var args = [1, 2, 3];
3292
+ * f.apply(null, args);
3293
+ * ```
3294
+ *
3295
+ * With `spread` this example can be re-written.
3296
+ *
3297
+ * ```js
3298
+ * spread(function(x, y, z) {})([1, 2, 3]);
3299
+ * ```
3300
+ *
3301
+ * @param {Function} callback
3302
+ *
3303
+ * @returns {Function}
3304
+ */ function spread(callback) {
3305
+ return function(arr) {
3306
+ return callback.apply(null, arr);
3307
+ };
3308
+ }
3309
+ /**
3310
+ * Determines whether the payload is an error thrown by Axios
3311
+ *
3312
+ * @param {*} payload The value to test
3313
+ *
3314
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3315
+ */ function isAxiosError(payload) {
3316
+ return utils.isObject(payload) && true === payload.isAxiosError;
3317
+ }
3318
+ const HttpStatusCode = {
3319
+ Continue: 100,
3320
+ SwitchingProtocols: 101,
3321
+ Processing: 102,
3322
+ EarlyHints: 103,
3323
+ Ok: 200,
3324
+ Created: 201,
3325
+ Accepted: 202,
3326
+ NonAuthoritativeInformation: 203,
3327
+ NoContent: 204,
3328
+ ResetContent: 205,
3329
+ PartialContent: 206,
3330
+ MultiStatus: 207,
3331
+ AlreadyReported: 208,
3332
+ ImUsed: 226,
3333
+ MultipleChoices: 300,
3334
+ MovedPermanently: 301,
3335
+ Found: 302,
3336
+ SeeOther: 303,
3337
+ NotModified: 304,
3338
+ UseProxy: 305,
3339
+ Unused: 306,
3340
+ TemporaryRedirect: 307,
3341
+ PermanentRedirect: 308,
3342
+ BadRequest: 400,
3343
+ Unauthorized: 401,
3344
+ PaymentRequired: 402,
3345
+ Forbidden: 403,
3346
+ NotFound: 404,
3347
+ MethodNotAllowed: 405,
3348
+ NotAcceptable: 406,
3349
+ ProxyAuthenticationRequired: 407,
3350
+ RequestTimeout: 408,
3351
+ Conflict: 409,
3352
+ Gone: 410,
3353
+ LengthRequired: 411,
3354
+ PreconditionFailed: 412,
3355
+ PayloadTooLarge: 413,
3356
+ UriTooLong: 414,
3357
+ UnsupportedMediaType: 415,
3358
+ RangeNotSatisfiable: 416,
3359
+ ExpectationFailed: 417,
3360
+ ImATeapot: 418,
3361
+ MisdirectedRequest: 421,
3362
+ UnprocessableEntity: 422,
3363
+ Locked: 423,
3364
+ FailedDependency: 424,
3365
+ TooEarly: 425,
3366
+ UpgradeRequired: 426,
3367
+ PreconditionRequired: 428,
3368
+ TooManyRequests: 429,
3369
+ RequestHeaderFieldsTooLarge: 431,
3370
+ UnavailableForLegalReasons: 451,
3371
+ InternalServerError: 500,
3372
+ NotImplemented: 501,
3373
+ BadGateway: 502,
3374
+ ServiceUnavailable: 503,
3375
+ GatewayTimeout: 504,
3376
+ HttpVersionNotSupported: 505,
3377
+ VariantAlsoNegotiates: 506,
3378
+ InsufficientStorage: 507,
3379
+ LoopDetected: 508,
3380
+ NotExtended: 510,
3381
+ NetworkAuthenticationRequired: 511
3382
+ };
3383
+ Object.entries(HttpStatusCode).forEach(([key, value])=>{
3384
+ HttpStatusCode[value] = key;
3385
+ });
3386
+ /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
3387
+ /**
3388
+ * Create an instance of Axios
3389
+ *
3390
+ * @param {Object} defaultConfig The default config for the instance
3391
+ *
3392
+ * @returns {Axios} A new instance of Axios
3393
+ */ function createInstance(defaultConfig) {
3394
+ const context = new Axios(defaultConfig);
3395
+ const instance = bind(Axios.prototype.request, context);
3396
+ // Copy axios.prototype to instance
3397
+ utils.extend(instance, Axios.prototype, context, {
3398
+ allOwnKeys: true
3399
+ });
3400
+ // Copy context to instance
3401
+ utils.extend(instance, context, null, {
3402
+ allOwnKeys: true
3403
+ });
3404
+ // Factory for creating new instances
3405
+ instance.create = function(instanceConfig) {
3406
+ return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
3407
+ };
3408
+ return instance;
3409
+ }
3410
+ // Create the default instance to be exported
3411
+ const axios = createInstance(defaults);
3412
+ // Expose Axios class to allow class inheritance
3413
+ axios.Axios = Axios;
3414
+ // Expose Cancel & CancelToken
3415
+ axios.CanceledError = CanceledError;
3416
+ axios.CancelToken = CancelToken;
3417
+ axios.isCancel = isCancel;
3418
+ axios.VERSION = VERSION;
3419
+ axios.toFormData = toFormData;
3420
+ // Expose AxiosError class
3421
+ axios.AxiosError = core_AxiosError;
3422
+ // alias for CanceledError for backward compatibility
3423
+ axios.Cancel = axios.CanceledError;
3424
+ // Expose all/spread
3425
+ axios.all = function(promises) {
3426
+ return Promise.all(promises);
3427
+ };
3428
+ axios.spread = spread;
3429
+ // Expose isAxiosError
3430
+ axios.isAxiosError = isAxiosError;
3431
+ // Expose mergeConfig
3432
+ axios.mergeConfig = mergeConfig_mergeConfig;
3433
+ axios.AxiosHeaders = AxiosHeaders;
3434
+ axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3435
+ axios.getAdapter = adapters_adapters.getAdapter;
3436
+ axios.HttpStatusCode = helpers_HttpStatusCode;
3437
+ axios.default = axios;
3438
+ // this module should only have a default export
3439
+ /* ESM default export */ const lib_axios = axios;
3440
+ // This module is intended to unwrap Axios default export as named.
3441
+ // Keep top-level export same with static properties
3442
+ // so that it can keep same with es module or cjs
3443
+ 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;
3433
3444
  class Files extends APIResource {
3434
3445
  /**
3435
3446
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3592,7 +3603,7 @@
3592
3603
  * @returns ListDocumentData | 知识库文件列表
3593
3604
  */ list(params, options) {
3594
3605
  const apiUrl = '/open_api/knowledge/document/list';
3595
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3606
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3596
3607
  headers: documents_headers
3597
3608
  }));
3598
3609
  return response;
@@ -3610,7 +3621,7 @@
3610
3621
  * @returns DocumentInfo[] | 已上传文件的基本信息
3611
3622
  */ async create(params, options) {
3612
3623
  const apiUrl = '/open_api/knowledge/document/create';
3613
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3624
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3614
3625
  headers: documents_headers
3615
3626
  }));
3616
3627
  return response.document_infos;
@@ -3626,7 +3637,7 @@
3626
3637
  * @returns void | 无返回
3627
3638
  */ async delete(params, options) {
3628
3639
  const apiUrl = '/open_api/knowledge/document/delete';
3629
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3640
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3630
3641
  headers: documents_headers
3631
3642
  }));
3632
3643
  }
@@ -3642,7 +3653,7 @@
3642
3653
  * @returns void | 无返回
3643
3654
  */ async update(params, options) {
3644
3655
  const apiUrl = '/open_api/knowledge/document/update';
3645
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3656
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3646
3657
  headers: documents_headers
3647
3658
  }));
3648
3659
  }
@@ -3668,9 +3679,9 @@
3668
3679
  * @param params.page - Optional The page number for paginated queries. Default is 1. | 可选 分页查询时的页码。默认为 1。
3669
3680
  * @param params.page_size - Optional The size of pagination. Default is 10. | 可选 分页大小。默认为 10。
3670
3681
  * @returns ListDocumentData | 知识库文件列表
3671
- */ list(params, options) {
3682
+ */ async list(params, options) {
3672
3683
  const apiUrl = '/open_api/knowledge/document/list';
3673
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3684
+ const response = await this._client.get(apiUrl, params, false, mergeConfig(options, {
3674
3685
  headers: documents_documents_headers
3675
3686
  }));
3676
3687
  return response;
@@ -3686,7 +3697,7 @@
3686
3697
  * @returns DocumentInfo[] | 已上传文件的基本信息
3687
3698
  */ async create(params, options) {
3688
3699
  const apiUrl = '/open_api/knowledge/document/create';
3689
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3700
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3690
3701
  headers: documents_documents_headers
3691
3702
  }));
3692
3703
  return response.document_infos;
@@ -3700,7 +3711,7 @@
3700
3711
  * @returns void | 无返回
3701
3712
  */ async delete(params, options) {
3702
3713
  const apiUrl = '/open_api/knowledge/document/delete';
3703
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3714
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3704
3715
  headers: documents_documents_headers
3705
3716
  }));
3706
3717
  }
@@ -3714,14 +3725,109 @@
3714
3725
  * @returns void | 无返回
3715
3726
  */ async update(params, options) {
3716
3727
  const apiUrl = '/open_api/knowledge/document/update';
3717
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3728
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3718
3729
  headers: documents_documents_headers
3719
3730
  }));
3720
3731
  }
3721
3732
  }
3733
+ class Images extends APIResource {
3734
+ /**
3735
+ * Update the description of an image in the knowledge base | 更新知识库中的图片描述
3736
+ * @docs en: https://www.coze.com/docs/developer_guides/developer_guides/update_image_caption?_lang=en
3737
+ * @docs zh: https://www.coze.cn/docs/developer_guides/developer_guides/update_image_caption?_lang=zh
3738
+ * @param datasetId - The ID of the dataset | 必选 知识库 ID
3739
+ * @param documentId - The ID of the document | 必选 知识库文件 ID
3740
+ * @param params - The parameters for updating the image
3741
+ * @param params.caption - Required. The description of the image | 必选 图片的描述信息
3742
+ * @returns undefined
3743
+ */ // eslint-disable-next-line max-params
3744
+ async update(datasetId, documentId, params, options) {
3745
+ const apiUrl = `/v1/datasets/${datasetId}/images/${documentId}`;
3746
+ await this._client.put(apiUrl, params, false, options);
3747
+ }
3748
+ /**
3749
+ * List images in the knowledge base | 列出知识库中的图片
3750
+ * @docs en: https://www.coze.com/docs/developer_guides/developer_guides/get_images?_lang=en
3751
+ * @docs zh: https://www.coze.cn/docs/developer_guides/developer_guides/get_images?_lang=zh
3752
+ * @param datasetId - The ID of the dataset | 必选 知识库 ID
3753
+ * @param params - The parameters for listing images
3754
+ * @param params.page_num - Optional. Page number for pagination, minimum value is 1, defaults to 1 | 可选 分页查询时的页码。默认为 1。
3755
+ * @param params.page_size - Optional. Number of items per page, range 1-299, defaults to 10 | 可选 分页大小。默认为 10。
3756
+ * @param params.keyword - Optional. Search keyword for image descriptions | 可选 图片描述的搜索关键词。
3757
+ * @param params.has_caption - Optional. Filter for images with/without captions | 可选 是否过滤有/无描述的图片。
3758
+ */ async list(datasetId, params, options) {
3759
+ const apiUrl = `/v1/datasets/${datasetId}/images`;
3760
+ const response = await this._client.get(apiUrl, params, false, options);
3761
+ return response.data;
3762
+ }
3763
+ }
3722
3764
  class Datasets extends APIResource {
3765
+ /**
3766
+ * Creates a new dataset | 创建数据集
3767
+ * @docs en: https://www.coze.com/docs/developer_guides/create_dataset?_lang=en
3768
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_dataset?_lang=zh
3769
+ * @param params - The parameters for creating a dataset
3770
+ * @param {string} params.name - Required. Dataset name, maximum length of 100 characters | 必选 数据集名称,最大长度为 100 个字符
3771
+ * @param {string} params.space_id - Required. Space ID where the dataset belongs | 必选 数据集所属的空间 ID
3772
+ * @param {number} params.format_type - Required. Dataset type (0: Text type, 2: Image type) | 必选 数据集类型 (0: 文本类型, 2: 图片类型)
3773
+ * @param {string} [params.description] - Optional. Dataset description | 可选 数据集描述
3774
+ * @param {string} [params.file_id] - Optional. Dataset icon file ID from file upload
3775
+ */ async create(params, options) {
3776
+ const apiUrl = '/v1/datasets';
3777
+ const response = await this._client.post(apiUrl, params, false, options);
3778
+ return response.data;
3779
+ }
3780
+ /**
3781
+ * Lists all datasets in a space | 列出空间中的所有数据集
3782
+ * @docs en: https://www.coze.com/docs/developer_guides/list_dataset?_lang=en
3783
+ * @docs zh: https://www.coze.cn/docs/developer_guides/list_dataset?_lang=zh
3784
+ * @param params - The parameters for listing datasets | 列出数据集的参数
3785
+ * @param {string} params.space_id - Required. Space ID where the datasets belong | 必选 数据集所属的空间 ID
3786
+ * @param {string} [params.name] - Optional. Dataset name for fuzzy search | 可选 数据集名称用于模糊搜索
3787
+ * @param {number} [params.format_type] - Optional. Dataset type (0: Text type, 2: Image type) | 可选 数据集类型 (0: 文本类型, 2: 图片类型)
3788
+ * @param {number} [params.page_num] - Optional. Page number for pagination (default: 1) | 可选 分页查询时的页码。默认为 1。
3789
+ * @param {number} [params.page_size] - Optional. Number of items per page (default: 10) | 可选 分页大小。默认为 10。
3790
+ */ async list(params, options) {
3791
+ const apiUrl = '/v1/datasets';
3792
+ const response = await this._client.get(apiUrl, params, false, options);
3793
+ return response.data;
3794
+ }
3795
+ /**
3796
+ * Updates a dataset | 更新数据集
3797
+ * @docs en: https://www.coze.com/docs/developer_guides/update_dataset?_lang=en
3798
+ * @docs zh: https://www.coze.cn/docs/developer_guides/update_dataset?_lang=zh
3799
+ * @param dataset_id - Required. The ID of the dataset to update | 必选 数据集 ID
3800
+ * @param params - Required. The parameters for updating the dataset | 必选 更新数据集的参数
3801
+ * @param params.name - Required. Dataset name, maximum length of 100 characters. | 必选 数据集名称,最大长度为 100 个字符。
3802
+ * @param params.file_id - Optional. Dataset icon, should pass the file_id obtained from the file upload interface. | 可选 数据集图标,应传递从文件上传接口获取的 file_id。
3803
+ * @param params.description - Optional. Dataset description. | 可选 数据集描述。
3804
+ */ async update(dataset_id, params, options) {
3805
+ const apiUrl = `/v1/datasets/${dataset_id}`;
3806
+ await this._client.put(apiUrl, params, false, options);
3807
+ }
3808
+ /**
3809
+ * Deletes a dataset | 删除数据集
3810
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_dataset?_lang=en
3811
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_dataset?_lang=zh
3812
+ * @param dataset_id - Required. The ID of the dataset to delete | 必选 数据集 ID
3813
+ */ async delete(dataset_id, options) {
3814
+ const apiUrl = `/v1/datasets/${dataset_id}`;
3815
+ await this._client.delete(apiUrl, false, options);
3816
+ }
3817
+ /**
3818
+ * Views the progress of dataset upload | 查看数据集上传进度
3819
+ * @docs en: https://www.coze.com/docs/developer_guides/get_dataset_progress?_lang=en
3820
+ * @docs zh: https://www.coze.cn/docs/developer_guides/get_dataset_progress?_lang=zh
3821
+ * @param dataset_id - Required. The ID of the dataset to process | 必选 数据集 ID
3822
+ * @param params - Required. The parameters for processing the dataset | 必选 处理数据集的参数
3823
+ * @param params.dataset_ids - Required. List of dataset IDs | 必选 数据集 ID 列表
3824
+ */ async process(dataset_id, params, options) {
3825
+ const apiUrl = `/v1/datasets/${dataset_id}/process`;
3826
+ const response = await this._client.post(apiUrl, params, false, options);
3827
+ return response.data;
3828
+ }
3723
3829
  constructor(...args){
3724
- super(...args), this.documents = new documents_Documents(this._client);
3830
+ super(...args), this.documents = new documents_Documents(this._client), this.images = new Images(this._client);
3725
3831
  }
3726
3832
  }
3727
3833
  class Voices extends APIResource {
@@ -3778,7 +3884,10 @@
3778
3884
  * @returns Speech synthesis data
3779
3885
  */ async create(params, options) {
3780
3886
  const apiUrl = '/v1/audio/speech';
3781
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3887
+ const response = await this._client.post(apiUrl, {
3888
+ ...params,
3889
+ sample_rate: params.sample_rate || 24000
3890
+ }, false, mergeConfig(options, {
3782
3891
  responseType: 'arraybuffer'
3783
3892
  }));
3784
3893
  return response;
@@ -3791,23 +3900,40 @@
3791
3900
  return response.data;
3792
3901
  }
3793
3902
  }
3794
- class esm_Audio extends APIResource {
3903
+ class audio_Audio extends APIResource {
3795
3904
  constructor(...args){
3796
3905
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3797
3906
  }
3798
3907
  }
3799
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.15","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":{".":{"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","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"dist/types/index.d.ts","files":["dist","LICENSE","README.md","!**/*.tsbuildinfo"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","prepublishOnly":"npm run build","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"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/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"}}'); // CONCATENATED MODULE: ./src/version.ts
3800
- const { version: esm_version } = package_namespaceObject;
3908
+ class Templates extends APIResource {
3909
+ /**
3910
+ * Duplicate a template. | 复制一个模板。
3911
+ * @param templateId - Required. The ID of the template to duplicate. | 要复制的模板的 ID。
3912
+ * @param params - Optional. The parameters for the duplicate operation. | 可选参数,用于复制操作。
3913
+ * @param params.workspace_id - Required. The ID of the workspace to duplicate the template into. | 要复制到的目标工作空间的 ID。
3914
+ * @param params.name - Optional. The name of the new template. | 新模板的名称。
3915
+ * @returns TemplateDuplicateRes | 复制模板结果
3916
+ */ async duplicate(templateId, params, options) {
3917
+ const apiUrl = `/v1/templates/${templateId}/duplicate`;
3918
+ const response = await this._client.post(apiUrl, params, false, options);
3919
+ return response.data;
3920
+ }
3921
+ }
3922
+ // EXTERNAL MODULE: os (ignored)
3923
+ var os_ignored_ = __webpack_require__("?9050");
3924
+ var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
3925
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.16-alpha.2d8e39","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},"types":"src/index.ts","files":["dist","LICENSE","README.md","README.zh-CN.md"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"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/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"},"botPublishConfig":{"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
3926
+ const { version: version_version } = package_namespaceObject;
3801
3927
  const getEnv = ()=>{
3802
3928
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3803
3929
  const { platform } = process;
3804
3930
  let osName = platform.toLowerCase();
3805
- let osVersion = os_ignored_.release();
3931
+ let osVersion = os_ignored_default().release();
3806
3932
  if ('darwin' === platform) {
3807
3933
  osName = 'macos';
3808
3934
  // Try to parse the macOS version
3809
3935
  try {
3810
- const darwinVersion = os_ignored_.release().split('.');
3936
+ const darwinVersion = os_ignored_default().release().split('.');
3811
3937
  if (darwinVersion.length >= 2) {
3812
3938
  const majorVersion = parseInt(darwinVersion[0], 10);
3813
3939
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3820,10 +3946,10 @@
3820
3946
  }
3821
3947
  } else if ('win32' === platform) {
3822
3948
  osName = 'windows';
3823
- osVersion = os_ignored_.release();
3949
+ osVersion = os_ignored_default().release();
3824
3950
  } else if ('linux' === platform) {
3825
3951
  osName = 'linux';
3826
- osVersion = os_ignored_.release();
3952
+ osVersion = os_ignored_default().release();
3827
3953
  }
3828
3954
  return {
3829
3955
  osName,
@@ -3833,12 +3959,12 @@
3833
3959
  };
3834
3960
  const getUserAgent = ()=>{
3835
3961
  const { nodeVersion, osName, osVersion } = getEnv();
3836
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3962
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3837
3963
  };
3838
3964
  const getNodeClientUserAgent = ()=>{
3839
3965
  const { osVersion, nodeVersion, osName } = getEnv();
3840
3966
  const ua = {
3841
- version: esm_version,
3967
+ version: version_version,
3842
3968
  lang: 'node',
3843
3969
  lang_version: nodeVersion,
3844
3970
  os_name: osName,
@@ -3846,15 +3972,66 @@
3846
3972
  };
3847
3973
  return JSON.stringify(ua);
3848
3974
  };
3849
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3975
+ const getBrowserClientUserAgent = ()=>{
3976
+ const browserInfo = {
3977
+ name: 'unknown',
3978
+ version: 'unknown'
3979
+ };
3980
+ const osInfo = {
3981
+ name: 'unknown',
3982
+ version: 'unknown'
3983
+ };
3984
+ const { userAgent } = navigator;
3985
+ // 检测操作系统及版本
3986
+ if (userAgent.indexOf('Windows') > -1) {
3987
+ var _userAgent_match;
3988
+ osInfo.name = 'windows';
3989
+ const windowsVersion = (null === (_userAgent_match = userAgent.match(/Windows NT ([0-9.]+)/)) || void 0 === _userAgent_match ? void 0 : _userAgent_match[1]) || 'unknown';
3990
+ osInfo.version = windowsVersion;
3991
+ } else if (userAgent.indexOf('Mac OS X') > -1) {
3992
+ var _userAgent_match1;
3993
+ osInfo.name = 'macos';
3994
+ // 将 10_15_7 格式转换为 10.15.7
3995
+ osInfo.version = ((null === (_userAgent_match1 = userAgent.match(/Mac OS X ([0-9_]+)/)) || void 0 === _userAgent_match1 ? void 0 : _userAgent_match1[1]) || 'unknown').replace(/_/g, '.');
3996
+ } else if (userAgent.indexOf('Linux') > -1) {
3997
+ var _userAgent_match2;
3998
+ osInfo.name = 'linux';
3999
+ osInfo.version = (null === (_userAgent_match2 = userAgent.match(/Linux ([0-9.]+)/)) || void 0 === _userAgent_match2 ? void 0 : _userAgent_match2[1]) || 'unknown';
4000
+ }
4001
+ // 检测浏览器及版本
4002
+ if (userAgent.indexOf('Chrome') > -1) {
4003
+ var _userAgent_match3;
4004
+ browserInfo.name = 'chrome';
4005
+ browserInfo.version = (null === (_userAgent_match3 = userAgent.match(/Chrome\/([0-9.]+)/)) || void 0 === _userAgent_match3 ? void 0 : _userAgent_match3[1]) || 'unknown';
4006
+ } else if (userAgent.indexOf('Firefox') > -1) {
4007
+ var _userAgent_match4;
4008
+ browserInfo.name = 'firefox';
4009
+ browserInfo.version = (null === (_userAgent_match4 = userAgent.match(/Firefox\/([0-9.]+)/)) || void 0 === _userAgent_match4 ? void 0 : _userAgent_match4[1]) || 'unknown';
4010
+ } else if (userAgent.indexOf('Safari') > -1) {
4011
+ var _userAgent_match5;
4012
+ browserInfo.name = 'safari';
4013
+ browserInfo.version = (null === (_userAgent_match5 = userAgent.match(/Version\/([0-9.]+)/)) || void 0 === _userAgent_match5 ? void 0 : _userAgent_match5[1]) || 'unknown';
4014
+ }
4015
+ const ua = {
4016
+ version: version_version,
4017
+ browser: browserInfo.name,
4018
+ browser_version: browserInfo.version,
4019
+ os_name: osInfo.name,
4020
+ os_version: osInfo.version
4021
+ };
4022
+ return JSON.stringify(ua);
4023
+ };
4024
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3850
4025
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3851
4026
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3852
4027
  var _error_response;
3853
4028
  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);
3854
4029
  }
3855
4030
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3856
- var _error_response1, _error_response2, _error_response3;
3857
- return 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);
4031
+ else {
4032
+ var _error_response1, _error_response2, _error_response3;
4033
+ 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);
4034
+ }
3858
4035
  };
3859
4036
  async function fetchAPI(url) {
3860
4037
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -3870,7 +4047,7 @@
3870
4047
  adapter: options.isStreaming ? 'fetch' : void 0,
3871
4048
  ...options
3872
4049
  }).catch((error)=>{
3873
- throw esm_handleError(error);
4050
+ throw fetcher_handleError(error);
3874
4051
  });
3875
4052
  return {
3876
4053
  async *stream () {
@@ -3908,7 +4085,7 @@
3908
4085
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3909
4086
  }
3910
4087
  } catch (error) {
3911
- esm_handleError(error);
4088
+ fetcher_handleError(error);
3912
4089
  }
3913
4090
  },
3914
4091
  json: ()=>response.data,
@@ -3932,8 +4109,8 @@
3932
4109
  }
3933
4110
  /**
3934
4111
  * default coze base URL is api.coze.com
3935
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
3936
- /* eslint-disable max-params */ class APIClient {
4112
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
4113
+ /* eslint-disable max-params */ class core_APIClient {
3937
4114
  async getToken() {
3938
4115
  if ('function' == typeof this.token) return await this.token();
3939
4116
  return this.token;
@@ -3943,11 +4120,12 @@
3943
4120
  const headers = {
3944
4121
  authorization: `Bearer ${token}`
3945
4122
  };
3946
- if (!isBrowser()) {
4123
+ if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4124
+ else {
3947
4125
  headers['User-Agent'] = getUserAgent();
3948
4126
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3949
4127
  }
3950
- const config = esm_mergeConfig(this.axiosOptions, options, {
4128
+ const config = mergeConfig(this.axiosOptions, options, {
3951
4129
  headers
3952
4130
  });
3953
4131
  config.method = method;
@@ -3971,7 +4149,7 @@
3971
4149
  if (contentType && contentType.includes('application/json')) {
3972
4150
  const result = await json();
3973
4151
  const { code, msg } = result;
3974
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
4152
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3975
4153
  }
3976
4154
  return stream();
3977
4155
  }
@@ -3979,7 +4157,7 @@
3979
4157
  {
3980
4158
  const result = await json();
3981
4159
  const { code, msg } = result;
3982
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
4160
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3983
4161
  return result;
3984
4162
  }
3985
4163
  }
@@ -4011,31 +4189,35 @@
4011
4189
  }
4012
4190
  constructor(config){
4013
4191
  this._config = config;
4014
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4192
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
4015
4193
  this.token = config.token;
4016
4194
  this.axiosOptions = config.axiosOptions || {};
4017
4195
  this.axiosInstance = config.axiosInstance;
4018
4196
  this.debug = config.debug || false;
4019
4197
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
4020
4198
  this.headers = config.headers;
4021
- if (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');
4022
- }
4023
- }
4024
- APIClient.APIError = APIError;
4025
- APIClient.BadRequestError = BadRequestError;
4026
- APIClient.AuthenticationError = AuthenticationError;
4027
- APIClient.PermissionDeniedError = PermissionDeniedError;
4028
- APIClient.NotFoundError = NotFoundError;
4029
- APIClient.RateLimitError = RateLimitError;
4030
- APIClient.InternalServerError = InternalServerError;
4031
- APIClient.GatewayError = GatewayError;
4032
- APIClient.TimeoutError = TimeoutError;
4033
- APIClient.UserAbortError = APIUserAbortError;
4034
- class CozeAPI extends APIClient {
4199
+ 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');
4200
+ }
4201
+ }
4202
+ core_APIClient.APIError = error_APIError;
4203
+ core_APIClient.BadRequestError = BadRequestError;
4204
+ core_APIClient.AuthenticationError = AuthenticationError;
4205
+ core_APIClient.PermissionDeniedError = PermissionDeniedError;
4206
+ core_APIClient.NotFoundError = NotFoundError;
4207
+ core_APIClient.RateLimitError = RateLimitError;
4208
+ core_APIClient.InternalServerError = InternalServerError;
4209
+ core_APIClient.GatewayError = GatewayError;
4210
+ core_APIClient.TimeoutError = TimeoutError;
4211
+ core_APIClient.UserAbortError = APIUserAbortError;
4212
+ // EXTERNAL MODULE: crypto (ignored)
4213
+ __webpack_require__("?666e");
4214
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
4215
+ __webpack_require__("?79fd");
4216
+ class CozeAPI extends core_APIClient {
4035
4217
  constructor(...args){
4036
4218
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4037
4219
  * @deprecated
4038
- */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new esm_Audio(this);
4220
+ */ 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);
4039
4221
  }
4040
4222
  }
4041
4223
  /**
@@ -9267,7 +9449,7 @@
9267
9449
  }, stringPad = {
9268
9450
  start: createMethod(!1),
9269
9451
  end: createMethod(!0)
9270
- }, userAgent = engineUserAgent, stringPadWebkitBug = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent), $$F = _export, $padEnd = stringPad.end, WEBKIT_BUG$1 = stringPadWebkitBug;
9452
+ }, index_esm_min_userAgent = engineUserAgent, stringPadWebkitBug = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(index_esm_min_userAgent), $$F = _export, $padEnd = stringPad.end, WEBKIT_BUG$1 = stringPadWebkitBug;
9271
9453
  $$F({
9272
9454
  target: "String",
9273
9455
  proto: !0,
@@ -38420,7 +38602,7 @@
38420
38602
  + * @param milliseconds The time to sleep in milliseconds
38421
38603
  + * @throws {Error} If milliseconds is negative
38422
38604
  + * @returns Promise that resolves after the specified duration
38423
- + */ const utils_sleep = (milliseconds)=>{
38605
+ + */ const src_utils_sleep = (milliseconds)=>{
38424
38606
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38425
38607
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38426
38608
  };
@@ -38440,7 +38622,11 @@
38440
38622
  return false;
38441
38623
  }
38442
38624
  };
38443
- const checkDevicePermission = async function() {
38625
+ /**
38626
+ * Checks device permissions for audio and video
38627
+ * @param checkVideo Whether to check video permissions (default: false)
38628
+ * @returns Promise that resolves with the device permission status
38629
+ */ const checkDevicePermission = async function() {
38444
38630
  let checkVideo = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
38445
38631
  return await index_esm_min_index.enableDevices({
38446
38632
  audio: true,
@@ -38453,7 +38639,16 @@
38453
38639
  */ const getAudioDevices = async function() {
38454
38640
  let { video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
38455
38641
  let devices = [];
38456
- devices = video ? await index_esm_min_index.enumerateDevices() : await [
38642
+ if (video) {
38643
+ devices = await index_esm_min_index.enumerateDevices();
38644
+ if (isScreenShareSupported()) // @ts-expect-error - add screenShare device to devices
38645
+ devices.push({
38646
+ deviceId: 'screenShare',
38647
+ kind: 'videoinput',
38648
+ label: 'Screen Share',
38649
+ groupId: 'screenShare'
38650
+ });
38651
+ } else devices = await [
38457
38652
  ...await index_esm_min_index.enumerateAudioCaptureDevices(),
38458
38653
  ...await index_esm_min_index.enumerateAudioPlaybackDevices()
38459
38654
  ];
@@ -38468,6 +38663,14 @@
38468
38663
  videoInputs: devices.filter((i)=>i.deviceId && 'videoinput' === i.kind)
38469
38664
  };
38470
38665
  };
38666
+ const isScreenShareDevice = (deviceId)=>'screenShare' === deviceId;
38667
+ /**
38668
+ * Check if browser supports screen sharing
38669
+ * 检查浏览器是否支持屏幕共享
38670
+ */ function isScreenShareSupported() {
38671
+ var _navigator_mediaDevices, _navigator;
38672
+ return !!(null === (_navigator = navigator) || void 0 === _navigator ? void 0 : null === (_navigator_mediaDevices = _navigator.mediaDevices) || void 0 === _navigator_mediaDevices ? void 0 : _navigator_mediaDevices.getDisplayMedia);
38673
+ }
38471
38674
  var error_RealtimeError = /*#__PURE__*/ function(RealtimeError) {
38472
38675
  RealtimeError["DEVICE_ACCESS_ERROR"] = "DEVICE_ACCESS_ERROR";
38473
38676
  RealtimeError["STREAM_CREATION_ERROR"] = "STREAM_CREATION_ERROR";
@@ -38561,6 +38764,10 @@
38561
38764
  * zh: 音频输出设备改变
38562
38765
  */ EventNames["AUDIO_OUTPUT_DEVICE_CHANGED"] = "client.output.device.changed";
38563
38766
  /**
38767
+ * en: Video input device changed
38768
+ * zh: 视频输入设备改变
38769
+ */ EventNames["VIDEO_INPUT_DEVICE_CHANGED"] = "client.video.input.device.changed";
38770
+ /**
38564
38771
  * en: Bot joined
38565
38772
  * zh: Bot 加入
38566
38773
  */ EventNames["BOT_JOIN"] = "server.bot.join";
@@ -41978,23 +42185,47 @@
41978
42185
  if (-1 === devices.audioOutputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Audio output device not found: ${deviceId}`);
41979
42186
  await this.engine.setAudioPlaybackDevice(deviceId);
41980
42187
  }
42188
+ async setVideoInputDevice(deviceId) {
42189
+ let isAutoCapture = !(arguments.length > 1) || void 0 === arguments[1] || arguments[1];
42190
+ var _this__videoConfig;
42191
+ const devices = await getAudioDevices({
42192
+ video: true
42193
+ });
42194
+ if (-1 === devices.videoInputs.findIndex((i)=>i.deviceId === deviceId)) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, `Video input device not found: ${deviceId}`);
42195
+ await this.changeVideoState(false);
42196
+ if (isScreenShareDevice(deviceId)) {
42197
+ if (this._streamIndex === StreamIndex$1.STREAM_INDEX_MAIN) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_MAIN);
42198
+ if (isAutoCapture) {
42199
+ var _this__videoConfig1;
42200
+ this.engine.setVideoSourceType(StreamIndex$1.STREAM_INDEX_SCREEN, VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
42201
+ await this.engine.startScreenCapture(null === (_this__videoConfig1 = this._videoConfig) || void 0 === _this__videoConfig1 ? void 0 : _this__videoConfig1.screenConfig);
42202
+ await this.engine.publishScreen(MediaType$1.VIDEO);
42203
+ }
42204
+ this._streamIndex = StreamIndex$1.STREAM_INDEX_SCREEN;
42205
+ } else {
42206
+ if (this._streamIndex === StreamIndex$1.STREAM_INDEX_SCREEN) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_SCREEN);
42207
+ if (isAutoCapture) await this.engine.startVideoCapture(deviceId);
42208
+ this._streamIndex = StreamIndex$1.STREAM_INDEX_MAIN;
42209
+ }
42210
+ this.engine.setLocalVideoPlayer(this._streamIndex, {
42211
+ renderDom: (null === (_this__videoConfig = this._videoConfig) || void 0 === _this__videoConfig ? void 0 : _this__videoConfig.renderDom) || 'local-player',
42212
+ userId: this._roomUserId
42213
+ });
42214
+ }
41981
42215
  async createLocalStream(userId, videoConfig) {
42216
+ this._roomUserId = userId;
41982
42217
  const devices = await getAudioDevices({
41983
42218
  video: this._isSupportVideo
41984
42219
  });
41985
42220
  if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get audio devices');
41986
42221
  if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get video devices');
41987
42222
  await this.engine.startAudioCapture(devices.audioInputs[0].deviceId);
41988
- if (this._isSupportVideo && (null == videoConfig ? void 0 : videoConfig.videoOnDefault)) await this.engine.startVideoCapture(devices.videoInputs[0].deviceId);
41989
- if (this._isSupportVideo) this.engine.setLocalVideoPlayer(StreamIndex$1.STREAM_INDEX_MAIN, {
41990
- renderDom: (null == videoConfig ? void 0 : videoConfig.renderDom) || 'local-player',
41991
- userId
41992
- });
42223
+ if (this._isSupportVideo) this.setVideoInputDevice((null == videoConfig ? void 0 : videoConfig.videoInputDeviceId) || devices.videoInputs[0].deviceId, null == videoConfig ? void 0 : videoConfig.videoOnDefault);
41993
42224
  }
41994
42225
  async disconnect() {
41995
42226
  try {
41996
- if (this._isSupportVideo) await this.engine.stopVideoCapture();
41997
- await this.engine.stopAudioCapture();
42227
+ if (this._isSupportVideo) await this.changeVideoState(false);
42228
+ await this.changeAudioState(false);
41998
42229
  await this.engine.unpublishStream(MediaType$1.AUDIO);
41999
42230
  await this.engine.leaveRoom();
42000
42231
  this.removeEventListener();
@@ -42014,8 +42245,19 @@
42014
42245
  }
42015
42246
  async changeVideoState(isVideoOn) {
42016
42247
  try {
42017
- if (isVideoOn) await this.engine.startVideoCapture();
42018
- else await this.engine.stopVideoCapture();
42248
+ if (isVideoOn) {
42249
+ if (this._streamIndex === StreamIndex$1.STREAM_INDEX_MAIN) await this.engine.startVideoCapture();
42250
+ else {
42251
+ var _this__videoConfig;
42252
+ this.engine.setVideoSourceType(StreamIndex$1.STREAM_INDEX_SCREEN, VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
42253
+ await this.engine.startScreenCapture(null === (_this__videoConfig = this._videoConfig) || void 0 === _this__videoConfig ? void 0 : _this__videoConfig.screenConfig);
42254
+ await this.engine.publishScreen(MediaType$1.VIDEO);
42255
+ }
42256
+ } else if (this._streamIndex === StreamIndex$1.STREAM_INDEX_MAIN) await this.engine.stopVideoCapture();
42257
+ else {
42258
+ await this.engine.stopScreenCapture();
42259
+ await this.engine.unpublishScreen(MediaType$1.VIDEO);
42260
+ }
42019
42261
  } catch (e) {
42020
42262
  this.dispatch(event_handler_EventNames.ERROR, e);
42021
42263
  throw e;
@@ -42093,7 +42335,7 @@
42093
42335
  }
42094
42336
  }
42095
42337
  // eslint-disable-next-line max-params
42096
- constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false){
42338
+ constructor(appId, debug = false, isTestEnv = false, isSupportVideo = false, videoConfig){
42097
42339
  super(debug), this.joinUserId = '', this._AIAnsExtension = null, this._isSupportVideo = false;
42098
42340
  if (isTestEnv) index_esm_min_index.setParameter('ICE_CONFIG_REQUEST_URLS', [
42099
42341
  'rtc-test.bytedance.com'
@@ -42108,6 +42350,7 @@
42108
42350
  this.handleLocalAudioPropertiesReport = this.handleLocalAudioPropertiesReport.bind(this);
42109
42351
  this.handleRemoteAudioPropertiesReport = this.handleRemoteAudioPropertiesReport.bind(this);
42110
42352
  this._isSupportVideo = isSupportVideo;
42353
+ this._videoConfig = videoConfig;
42111
42354
  }
42112
42355
  }
42113
42356
  class RealtimeClient extends RealtimeEventHandler {
@@ -42132,7 +42375,7 @@
42132
42375
  throw new RealtimeAPIError(error_RealtimeError.CREATE_ROOM_ERROR, error instanceof Error ? error.message : 'Unknown error', error);
42133
42376
  }
42134
42377
  // Step2 create engine
42135
- this._client = new EngineClient(roomInfo.app_id, this._config.debug, this._isTestEnv, this._isSupportVideo);
42378
+ this._client = new EngineClient(roomInfo.app_id, this._config.debug, this._isTestEnv, this._isSupportVideo, this._config.videoConfig);
42136
42379
  // Step3 bind engine events
42137
42380
  this._client.bindEngineEvents();
42138
42381
  this._client.on(event_handler_EventNames.ALL, (eventName, data)=>{
@@ -42268,6 +42511,13 @@
42268
42511
  deviceId
42269
42512
  });
42270
42513
  }
42514
+ async setVideoInputDevice(deviceId) {
42515
+ var _this__client;
42516
+ await (null === (_this__client = this._client) || void 0 === _this__client ? void 0 : _this__client.setVideoInputDevice(deviceId));
42517
+ this.dispatch(event_handler_EventNames.VIDEO_INPUT_DEVICE_CHANGED, {
42518
+ deviceId
42519
+ });
42520
+ }
42271
42521
  /**
42272
42522
  * Constructor for initializing a RealtimeClient instance.
42273
42523
  *
@@ -42298,6 +42548,16 @@
42298
42548
  * @param config.suppressNonStationaryNoise - Optional, suppress non-stationary noise, defaults to false. |
42299
42549
  * 可选,默认是否抑制非静态噪声,默认值为 false。
42300
42550
  * @param config.isAutoSubscribeAudio - Optional, whether to automatically subscribe to bot reply audio streams, defaults to true. |
42551
+ * @param config.videoConfig - Optional, Video configuration. |
42552
+ * 可选,视频配置。
42553
+ * @param config.videoConfig.videoOnDefault - Optional, Whether to turn on video by default, defaults to true. |
42554
+ * 可选,默认是否开启视频,默认值为 true。
42555
+ * @param config.videoConfig.renderDom - Optional, The DOM element to render the video stream to. |
42556
+ * 可选,渲染视频流的 DOM 元素。
42557
+ * @param config.videoConfig.videoInputDeviceId - Optional, The device ID of the video input device to use. |
42558
+ * 可选,视频输入设备的设备 ID。
42559
+ * @param config.videoConfig.screenConfig - Optional, Screen share configuration if videoInputDeviceId is 'screenShare' see https://www.volcengine.com/docs/6348/104481#screenconfig for more details. |
42560
+ * 可选,屏幕共享配置,如果 videoInputDeviceId 是 'screenShare',请参考 https://www.volcengine.com/docs/6348/104481#screenconfig 了解更多详情。
42301
42561
  */ constructor(config){
42302
42562
  super(config.debug), this._client = null, this.isConnected = false, this._isTestEnv = false, this._isSupportVideo = false;
42303
42563
  this._config = config;