@coze/realtime-api 1.0.3-beta.7 → 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
- "?e272": function() {
10
+ "?666e": function() {
11
11
  /* (ignored) */ },
12
- "?5742": function() {
12
+ "?79fd": function() {
13
13
  /* (ignored) */ },
14
- "?9caf": 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, {
@@ -98,480 +113,1041 @@
98
113
  getAudioDevices: ()=>getAudioDevices,
99
114
  isScreenShareDevice: ()=>isScreenShareDevice,
100
115
  isScreenShareSupported: ()=>isScreenShareSupported,
101
- sleep: ()=>utils_sleep
116
+ sleep: ()=>src_utils_sleep
102
117
  });
103
- function bind(fn, thisArg) {
104
- return function() {
105
- return fn.apply(thisArg, arguments);
106
- };
118
+ class APIResource {
119
+ constructor(client){
120
+ this._client = client;
121
+ }
107
122
  }
108
- // utils is a library of generic helper functions non-specific to axios
109
- const { toString: utils_toString } = Object.prototype;
110
- const { getPrototypeOf } = Object;
111
- const kindOf = ((cache)=>(thing)=>{
112
- const str = utils_toString.call(thing);
113
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
114
- })(Object.create(null));
115
- const kindOfTest = (type)=>{
116
- type = type.toLowerCase();
117
- return (thing)=>kindOf(thing) === type;
118
- };
119
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
120
- /**
121
- * Determine if a value is an Array
122
- *
123
- * @param {Object} val The value to test
124
- *
125
- * @returns {boolean} True if value is an Array, otherwise false
126
- */ const { isArray } = Array;
127
- /**
128
- * Determine if a value is undefined
129
- *
130
- * @param {*} val The value to test
131
- *
132
- * @returns {boolean} True if the value is undefined, otherwise false
133
- */ const isUndefined = typeOfTest('undefined');
134
- /**
135
- * Determine if a value is a Buffer
136
- *
137
- * @param {*} val The value to test
138
- *
139
- * @returns {boolean} True if value is a Buffer, otherwise false
140
- */ function isBuffer(val) {
141
- 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
+ }
142
198
  }
143
- /**
144
- * Determine if a value is an ArrayBuffer
145
- *
146
- * @param {*} val The value to test
147
- *
148
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
149
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
150
- /**
151
- * Determine if a value is a view on an ArrayBuffer
152
- *
153
- * @param {*} val The value to test
154
- *
155
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
156
- */ function isArrayBufferView(val) {
157
- let result;
158
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
159
- 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
+ }
160
206
  }
161
- /**
162
- * Determine if a value is a String
163
- *
164
- * @param {*} val The value to test
165
- *
166
- * @returns {boolean} True if value is a String, otherwise false
167
- */ const isString = typeOfTest('string');
168
- /**
169
- * Determine if a value is a Function
170
- *
171
- * @param {*} val The value to test
172
- * @returns {boolean} True if value is a Function, otherwise false
173
- */ const isFunction = typeOfTest('function');
174
- /**
175
- * Determine if a value is a Number
176
- *
177
- * @param {*} val The value to test
178
- *
179
- * @returns {boolean} True if value is a Number, otherwise false
180
- */ const isNumber = typeOfTest('number');
181
- /**
182
- * Determine if a value is an Object
183
- *
184
- * @param {*} thing The value to test
185
- *
186
- * @returns {boolean} True if value is an Object, otherwise false
187
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
188
- /**
189
- * Determine if a value is a Boolean
190
- *
191
- * @param {*} thing The value to test
192
- * @returns {boolean} True if value is a Boolean, otherwise false
193
- */ const isBoolean = (thing)=>true === thing || false === thing;
194
- /**
195
- * Determine if a value is a plain Object
196
- *
197
- * @param {*} val The value to test
198
- *
199
- * @returns {boolean} True if value is a plain Object, otherwise false
200
- */ const isPlainObject = (val)=>{
201
- if ('object' !== kindOf(val)) return false;
202
- const prototype = getPrototypeOf(val);
203
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
204
- };
205
- /**
206
- * Determine if a value is a Date
207
- *
208
- * @param {*} val The value to test
209
- *
210
- * @returns {boolean} True if value is a Date, otherwise false
211
- */ const isDate = kindOfTest('Date');
212
- /**
213
- * Determine if a value is a File
214
- *
215
- * @param {*} val The value to test
216
- *
217
- * @returns {boolean} True if value is a File, otherwise false
218
- */ const isFile = kindOfTest('File');
219
- /**
220
- * Determine if a value is a Blob
221
- *
222
- * @param {*} val The value to test
223
- *
224
- * @returns {boolean} True if value is a Blob, otherwise false
225
- */ const isBlob = kindOfTest('Blob');
226
- /**
227
- * Determine if a value is a FileList
228
- *
229
- * @param {*} val The value to test
230
- *
231
- * @returns {boolean} True if value is a File, otherwise false
232
- */ const utils_isFileList = kindOfTest('FileList');
233
- /**
234
- * Determine if a value is a Stream
235
- *
236
- * @param {*} val The value to test
237
- *
238
- * @returns {boolean} True if value is a Stream, otherwise false
239
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
240
- /**
241
- * Determine if a value is a FormData
242
- *
243
- * @param {*} thing The value to test
244
- *
245
- * @returns {boolean} True if value is an FormData, otherwise false
246
- */ const utils_isFormData = (thing)=>{
247
- let kind;
248
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
249
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
250
- };
251
- /**
252
- * Determine if a value is a URLSearchParams object
253
- *
254
- * @param {*} val The value to test
255
- *
256
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
257
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
258
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
259
- 'ReadableStream',
260
- 'Request',
261
- 'Response',
262
- 'Headers'
263
- ].map(kindOfTest);
264
- /**
265
- * Trim excess whitespace off the beginning and end of a string
266
- *
267
- * @param {String} str The String to trim
268
- *
269
- * @returns {String} The String freed of excess whitespace
270
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
271
- /**
272
- * Iterate over an Array or an Object invoking a function for each item.
273
- *
274
- * If `obj` is an Array callback will be called passing
275
- * the value, index, and complete array for each item.
276
- *
277
- * If 'obj' is an Object callback will be called passing
278
- * the value, key, and complete object for each property.
279
- *
280
- * @param {Object|Array} obj The object to iterate
281
- * @param {Function} fn The callback to invoke for each item
282
- *
283
- * @param {Boolean} [allOwnKeys = false]
284
- * @returns {any}
285
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
286
- // Don't bother if no value provided
287
- if (null == obj) return;
288
- let i;
289
- let l;
290
- // Force an array if not already something iterable
291
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
292
- obj
293
- ];
294
- if (isArray(obj)) // Iterate over array values
295
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
296
- else {
297
- // Iterate over object keys
298
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
299
- const len = keys.length;
300
- let key;
301
- for(i = 0; i < len; i++){
302
- key = keys[i];
303
- 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(', ');
304
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;
305
285
  }
306
286
  }
307
- function findKey(obj, key) {
308
- key = key.toLowerCase();
309
- const keys = Object.keys(obj);
310
- let i = keys.length;
311
- let _key;
312
- while(i-- > 0){
313
- _key = keys[i];
314
- 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
+ // }
315
293
  }
316
- return null;
317
294
  }
318
- const _global = (()=>{
319
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
320
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
321
- })();
322
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
323
- /**
324
- * Accepts varargs expecting each argument to be an object, then
325
- * immutably merges the properties of each object and returns result.
326
- *
327
- * When multiple objects contain the same key the later object in
328
- * the arguments list will take precedence.
329
- *
330
- * Example:
331
- *
332
- * ```js
333
- * var result = merge({foo: 123}, {foo: 456});
334
- * console.log(result.foo); // outputs 456
335
- * ```
336
- *
337
- * @param {Object} obj1 Object to merge
338
- *
339
- * @returns {Object} Result of all merge properties
340
- */ function utils_merge() {
341
- const { caseless } = isContextDefined(this) && this || {};
342
- const result = {};
343
- const assignValue = (val, key)=>{
344
- const targetKey = caseless && findKey(result, key) || key;
345
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
346
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
347
- else if (isArray(val)) result[targetKey] = val.slice();
348
- else result[targetKey] = val;
349
- };
350
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
351
- 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
+ }
352
299
  }
353
- /**
354
- * Extends object a by mutably adding to it the properties of object b.
355
- *
356
- * @param {Object} a The object to be extended
357
- * @param {Object} b The object to copy properties from
358
- * @param {Object} thisArg The object to bind function to
359
- *
360
- * @param {Boolean} [allOwnKeys]
361
- * @returns {Object} The resulting value of object a
362
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
363
- forEach(b, (val, key)=>{
364
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
365
- else a[key] = val;
366
- }, {
367
- allOwnKeys
368
- });
369
- return a;
370
- };
371
- /**
372
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
373
- *
374
- * @param {string} content with BOM
375
- *
376
- * @returns {string} content value without BOM
377
- */ const stripBOM = (content)=>{
378
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
379
- return content;
380
- };
381
- /**
382
- * Inherit the prototype methods from one constructor into another
383
- * @param {function} constructor
384
- * @param {function} superConstructor
385
- * @param {object} [props]
386
- * @param {object} [descriptors]
387
- *
388
- * @returns {void}
389
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
390
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
391
- constructor.prototype.constructor = constructor;
392
- Object.defineProperty(constructor, 'super', {
393
- value: superConstructor.prototype
394
- });
395
- 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);
396
343
  };
397
- /**
398
- * Resolve object with deep prototype chain to a flat object
399
- * @param {Object} sourceObj source object
400
- * @param {Object} [destObj]
401
- * @param {Function|Boolean} [filter]
402
- * @param {Function} [propFilter]
403
- *
404
- * @returns {Object}
405
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
406
- let props;
407
- let i;
408
- let prop;
409
- const merged = {};
410
- destObj = destObj || {};
411
- // eslint-disable-next-line no-eq-null,eqeqeq
412
- if (null == sourceObj) return destObj;
413
- do {
414
- props = Object.getOwnPropertyNames(sourceObj);
415
- i = props.length;
416
- while(i-- > 0){
417
- prop = props[i];
418
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
419
- destObj[prop] = sourceObj[prop];
420
- merged[prop] = true;
421
- }
422
- }
423
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
424
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
425
- 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;
426
694
  };
695
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
427
696
  /**
428
- * Determines whether a string ends with the characters of a specified string
697
+ * Determine if a value is an Array
429
698
  *
430
- * @param {String} str
431
- * @param {String} searchString
432
- * @param {Number} [position= 0]
699
+ * @param {Object} val The value to test
433
700
  *
434
- * @returns {boolean}
435
- */ const endsWith = (str, searchString, position)=>{
436
- str = String(str);
437
- if (void 0 === position || position > str.length) position = str.length;
438
- position -= searchString.length;
439
- const lastIndex = str.indexOf(searchString, position);
440
- return -1 !== lastIndex && lastIndex === position;
441
- };
701
+ * @returns {boolean} True if value is an Array, otherwise false
702
+ */ const { isArray } = Array;
442
703
  /**
443
- * Returns new array from array like object or null if failed
704
+ * Determine if a value is undefined
444
705
  *
445
- * @param {*} [thing]
706
+ * @param {*} val The value to test
446
707
  *
447
- * @returns {?Array}
448
- */ const toArray = (thing)=>{
449
- if (!thing) return null;
450
- if (isArray(thing)) return thing;
451
- let i = thing.length;
452
- if (!isNumber(i)) return null;
453
- const arr = new Array(i);
454
- while(i-- > 0)arr[i] = thing[i];
455
- return arr;
456
- };
708
+ * @returns {boolean} True if the value is undefined, otherwise false
709
+ */ const isUndefined = typeOfTest('undefined');
457
710
  /**
458
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
459
- * thing passed in is an instance of Uint8Array
711
+ * Determine if a value is a Buffer
460
712
  *
461
- * @param {TypedArray}
713
+ * @param {*} val The value to test
462
714
  *
463
- * @returns {Array}
464
- */ // eslint-disable-next-line func-names
465
- 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
+ }
466
719
  /**
467
- * For each entry in the object, call the function with the key and value.
720
+ * Determine if a value is an ArrayBuffer
468
721
  *
469
- * @param {Object<any, any>} obj - The object to iterate over.
470
- * @param {Function} fn - The function to call for each entry.
722
+ * @param {*} val The value to test
471
723
  *
472
- * @returns {void}
473
- */ const forEachEntry = (obj, fn)=>{
474
- const generator = obj && obj[Symbol.iterator];
475
- const iterator = generator.call(obj);
476
- let result;
477
- while((result = iterator.next()) && !result.done){
478
- const pair = result.value;
479
- fn.call(obj, pair[0], pair[1]);
480
- }
481
- };
724
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
725
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
482
726
  /**
483
- * 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
484
728
  *
485
- * @param {string} regExp - The regular expression to match against.
486
- * @param {string} str - The string to search.
729
+ * @param {*} val The value to test
487
730
  *
488
- * @returns {Array<boolean>}
489
- */ const matchAll = (regExp, str)=>{
490
- let matches;
491
- const arr = [];
492
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
493
- return arr;
494
- };
495
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
496
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
497
- return p1.toUpperCase() + p2;
498
- });
499
- /* 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
+ }
500
737
  /**
501
- * Determine if a value is a RegExp object
738
+ * Determine if a value is a String
502
739
  *
503
740
  * @param {*} val The value to test
504
741
  *
505
- * @returns {boolean} True if value is a RegExp object, otherwise false
506
- */ const isRegExp = kindOfTest('RegExp');
507
- const reduceDescriptors = (obj, reducer)=>{
508
- const descriptors = Object.getOwnPropertyDescriptors(obj);
509
- const reducedDescriptors = {};
510
- forEach(descriptors, (descriptor, name)=>{
511
- let ret;
512
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
513
- });
514
- Object.defineProperties(obj, reducedDescriptors);
515
- };
742
+ * @returns {boolean} True if value is a String, otherwise false
743
+ */ const isString = typeOfTest('string');
516
744
  /**
517
- * Makes all methods read-only
518
- * @param {Object} obj
519
- */ const freezeMethods = (obj)=>{
520
- reduceDescriptors(obj, (descriptor, name)=>{
521
- // skip restricted props in strict mode
522
- if (isFunction(obj) && -1 !== [
523
- 'arguments',
524
- 'caller',
525
- 'callee'
526
- ].indexOf(name)) return false;
527
- const value = obj[name];
528
- if (!isFunction(value)) return;
529
- descriptor.enumerable = false;
530
- if ('writable' in descriptor) {
531
- descriptor.writable = false;
532
- return;
533
- }
534
- if (!descriptor.set) descriptor.set = ()=>{
535
- throw Error('Can not rewrite read-only method \'' + name + '\'');
536
- };
537
- });
538
- };
539
- const toObjectSet = (arrayOrString, delimiter)=>{
540
- const obj = {};
541
- const define1 = (arr)=>{
542
- arr.forEach((value)=>{
543
- obj[value] = true;
544
- });
545
- };
546
- isArray(arrayOrString) ? define1(arrayOrString) : define1(String(arrayOrString).split(delimiter));
547
- return obj;
548
- };
549
- const noop = ()=>{};
550
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
551
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
552
- const DIGIT = '0123456789';
553
- const ALPHABET = {
554
- DIGIT,
555
- ALPHA,
556
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
557
- };
558
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
559
- let str = '';
560
- const { length } = alphabet;
561
- while(size--)str += alphabet[Math.random() * length | 0];
562
- return str;
563
- };
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');
564
750
  /**
565
- * If the thing is a FormData object, return true, otherwise return false.
751
+ * Determine if a value is a Number
566
752
  *
567
- * @param {unknown} thing - The thing to check.
753
+ * @param {*} val The value to test
568
754
  *
569
- * @returns {boolean}
570
- */ function isSpecCompliantForm(thing) {
571
- return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
572
- }
573
- const toJSONObject = (obj)=>{
574
- 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);
575
1151
  const visit = (source, i)=>{
576
1152
  if (isObject(source)) {
577
1153
  if (stack.indexOf(source) >= 0) return;
@@ -618,7 +1194,7 @@
618
1194
  isNumber,
619
1195
  isBoolean,
620
1196
  isObject,
621
- isPlainObject,
1197
+ isPlainObject: utils_isPlainObject,
622
1198
  isReadableStream,
623
1199
  isRequest,
624
1200
  isResponse,
@@ -1816,7 +2392,7 @@
1816
2392
  * @param {Object} config2
1817
2393
  *
1818
2394
  * @returns {Object} New object resulting from merging config2 to config1
1819
- */ function mergeConfig(config1, config2) {
2395
+ */ function mergeConfig_mergeConfig(config1, config2) {
1820
2396
  // eslint-disable-next-line no-param-reassign
1821
2397
  config2 = config2 || {};
1822
2398
  const config = {};
@@ -1886,7 +2462,7 @@
1886
2462
  return config;
1887
2463
  }
1888
2464
  /* ESM default export */ const resolveConfig = (config)=>{
1889
- const newConfig = mergeConfig({}, config);
2465
+ const newConfig = mergeConfig_mergeConfig({}, config);
1890
2466
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1891
2467
  newConfig.headers = headers = AxiosHeaders.from(headers);
1892
2468
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2492,946 +3068,379 @@
2492
3068
  config = config || {};
2493
3069
  config.url = configOrUrl;
2494
3070
  } else config = configOrUrl || {};
2495
- config = mergeConfig(this.defaults, config);
2496
- const { transitional, paramsSerializer, headers } = config;
2497
- if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2498
- silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
2499
- forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
2500
- clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean)
2501
- }, false);
2502
- if (null != paramsSerializer) {
2503
- if (utils.isFunction(paramsSerializer)) config.paramsSerializer = {
2504
- serialize: paramsSerializer
2505
- };
2506
- else helpers_validator.assertOptions(paramsSerializer, {
2507
- encode: Axios_validators.function,
2508
- serialize: Axios_validators.function
2509
- }, true);
2510
- }
2511
- // Set config.method
2512
- config.method = (config.method || this.defaults.method || 'get').toLowerCase();
2513
- // Flatten headers
2514
- let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
2515
- headers && utils.forEach([
2516
- 'delete',
2517
- 'get',
2518
- 'head',
2519
- 'post',
2520
- 'put',
2521
- 'patch',
2522
- 'common'
2523
- ], (method)=>{
2524
- delete headers[method];
2525
- });
2526
- config.headers = AxiosHeaders.concat(contextHeaders, headers);
2527
- // filter out skipped interceptors
2528
- const requestInterceptorChain = [];
2529
- let synchronousRequestInterceptors = true;
2530
- this.interceptors.request.forEach(function(interceptor) {
2531
- if ('function' == typeof interceptor.runWhen && false === interceptor.runWhen(config)) return;
2532
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2533
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2534
- });
2535
- const responseInterceptorChain = [];
2536
- this.interceptors.response.forEach(function(interceptor) {
2537
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2538
- });
2539
- let promise;
2540
- let i = 0;
2541
- let len;
2542
- if (!synchronousRequestInterceptors) {
2543
- const chain = [
2544
- dispatchRequest.bind(this),
2545
- void 0
2546
- ];
2547
- chain.unshift.apply(chain, requestInterceptorChain);
2548
- chain.push.apply(chain, responseInterceptorChain);
2549
- len = chain.length;
2550
- promise = Promise.resolve(config);
2551
- while(i < len)promise = promise.then(chain[i++], chain[i++]);
2552
- return promise;
2553
- }
2554
- len = requestInterceptorChain.length;
2555
- let newConfig = config;
2556
- i = 0;
2557
- while(i < len){
2558
- const onFulfilled = requestInterceptorChain[i++];
2559
- const onRejected = requestInterceptorChain[i++];
2560
- try {
2561
- newConfig = onFulfilled(newConfig);
2562
- } catch (error) {
2563
- onRejected.call(this, error);
2564
- break;
2565
- }
2566
- }
2567
- try {
2568
- promise = dispatchRequest.call(this, newConfig);
2569
- } catch (error) {
2570
- return Promise.reject(error);
2571
- }
2572
- i = 0;
2573
- len = responseInterceptorChain.length;
2574
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2575
- return promise;
2576
- }
2577
- getUri(config) {
2578
- config = mergeConfig(this.defaults, config);
2579
- const fullPath = buildFullPath(config.baseURL, config.url);
2580
- return buildURL(fullPath, config.params, config.paramsSerializer);
2581
- }
2582
- }
2583
- // Provide aliases for supported request methods
2584
- utils.forEach([
2585
- 'delete',
2586
- 'get',
2587
- 'head',
2588
- 'options'
2589
- ], function(method) {
2590
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2591
- return this.request(mergeConfig(config || {}, {
2592
- method,
2593
- url,
2594
- data: (config || {}).data
2595
- }));
2596
- };
2597
- });
2598
- utils.forEach([
2599
- 'post',
2600
- 'put',
2601
- 'patch'
2602
- ], function(method) {
2603
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2604
- return function(url, data, config) {
2605
- return this.request(mergeConfig(config || {}, {
2606
- method,
2607
- headers: isForm ? {
2608
- 'Content-Type': 'multipart/form-data'
2609
- } : {},
2610
- url,
2611
- data
2612
- }));
2613
- };
2614
- }
2615
- Axios_Axios.prototype[method] = generateHTTPMethod();
2616
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2617
- });
2618
- /* ESM default export */ const Axios = Axios_Axios;
2619
- /**
2620
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2621
- *
2622
- * @param {Function} executor The executor function.
2623
- *
2624
- * @returns {CancelToken}
2625
- */ class CancelToken_CancelToken {
2626
- constructor(executor){
2627
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2628
- let resolvePromise;
2629
- this.promise = new Promise(function(resolve) {
2630
- resolvePromise = resolve;
2631
- });
2632
- const token = this;
2633
- // eslint-disable-next-line func-names
2634
- this.promise.then((cancel)=>{
2635
- if (!token._listeners) return;
2636
- let i = token._listeners.length;
2637
- while(i-- > 0)token._listeners[i](cancel);
2638
- token._listeners = null;
2639
- });
2640
- // eslint-disable-next-line func-names
2641
- this.promise.then = (onfulfilled)=>{
2642
- let _resolve;
2643
- // eslint-disable-next-line func-names
2644
- const promise = new Promise((resolve)=>{
2645
- token.subscribe(resolve);
2646
- _resolve = resolve;
2647
- }).then(onfulfilled);
2648
- promise.cancel = function() {
2649
- token.unsubscribe(_resolve);
2650
- };
2651
- return promise;
2652
- };
2653
- executor(function(message, config, request) {
2654
- if (token.reason) // Cancellation has already been requested
2655
- return;
2656
- token.reason = new CanceledError(message, config, request);
2657
- resolvePromise(token.reason);
2658
- });
2659
- }
2660
- /**
2661
- * Throws a `CanceledError` if cancellation has been requested.
2662
- */ throwIfRequested() {
2663
- if (this.reason) throw this.reason;
2664
- }
2665
- /**
2666
- * Subscribe to the cancel signal
2667
- */ subscribe(listener) {
2668
- if (this.reason) {
2669
- listener(this.reason);
2670
- return;
2671
- }
2672
- if (this._listeners) this._listeners.push(listener);
2673
- else this._listeners = [
2674
- listener
2675
- ];
2676
- }
2677
- /**
2678
- * Unsubscribe from the cancel signal
2679
- */ unsubscribe(listener) {
2680
- if (!this._listeners) return;
2681
- const index = this._listeners.indexOf(listener);
2682
- if (-1 !== index) this._listeners.splice(index, 1);
2683
- }
2684
- toAbortSignal() {
2685
- const controller = new AbortController();
2686
- const abort = (err)=>{
2687
- controller.abort(err);
2688
- };
2689
- this.subscribe(abort);
2690
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2691
- return controller.signal;
2692
- }
2693
- /**
2694
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2695
- * cancels the `CancelToken`.
2696
- */ static source() {
2697
- let cancel;
2698
- const token = new CancelToken_CancelToken(function(c) {
2699
- cancel = c;
2700
- });
2701
- return {
2702
- token,
2703
- cancel
2704
- };
2705
- }
2706
- }
2707
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2708
- /**
2709
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2710
- *
2711
- * Common use case would be to use `Function.prototype.apply`.
2712
- *
2713
- * ```js
2714
- * function f(x, y, z) {}
2715
- * var args = [1, 2, 3];
2716
- * f.apply(null, args);
2717
- * ```
2718
- *
2719
- * With `spread` this example can be re-written.
2720
- *
2721
- * ```js
2722
- * spread(function(x, y, z) {})([1, 2, 3]);
2723
- * ```
2724
- *
2725
- * @param {Function} callback
2726
- *
2727
- * @returns {Function}
2728
- */ function spread(callback) {
2729
- return function(arr) {
2730
- return callback.apply(null, arr);
2731
- };
2732
- }
2733
- /**
2734
- * Determines whether the payload is an error thrown by Axios
2735
- *
2736
- * @param {*} payload The value to test
2737
- *
2738
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2739
- */ function isAxiosError(payload) {
2740
- return utils.isObject(payload) && true === payload.isAxiosError;
2741
- }
2742
- const HttpStatusCode = {
2743
- Continue: 100,
2744
- SwitchingProtocols: 101,
2745
- Processing: 102,
2746
- EarlyHints: 103,
2747
- Ok: 200,
2748
- Created: 201,
2749
- Accepted: 202,
2750
- NonAuthoritativeInformation: 203,
2751
- NoContent: 204,
2752
- ResetContent: 205,
2753
- PartialContent: 206,
2754
- MultiStatus: 207,
2755
- AlreadyReported: 208,
2756
- ImUsed: 226,
2757
- MultipleChoices: 300,
2758
- MovedPermanently: 301,
2759
- Found: 302,
2760
- SeeOther: 303,
2761
- NotModified: 304,
2762
- UseProxy: 305,
2763
- Unused: 306,
2764
- TemporaryRedirect: 307,
2765
- PermanentRedirect: 308,
2766
- BadRequest: 400,
2767
- Unauthorized: 401,
2768
- PaymentRequired: 402,
2769
- Forbidden: 403,
2770
- NotFound: 404,
2771
- MethodNotAllowed: 405,
2772
- NotAcceptable: 406,
2773
- ProxyAuthenticationRequired: 407,
2774
- RequestTimeout: 408,
2775
- Conflict: 409,
2776
- Gone: 410,
2777
- LengthRequired: 411,
2778
- PreconditionFailed: 412,
2779
- PayloadTooLarge: 413,
2780
- UriTooLong: 414,
2781
- UnsupportedMediaType: 415,
2782
- RangeNotSatisfiable: 416,
2783
- ExpectationFailed: 417,
2784
- ImATeapot: 418,
2785
- MisdirectedRequest: 421,
2786
- UnprocessableEntity: 422,
2787
- Locked: 423,
2788
- FailedDependency: 424,
2789
- TooEarly: 425,
2790
- UpgradeRequired: 426,
2791
- PreconditionRequired: 428,
2792
- TooManyRequests: 429,
2793
- RequestHeaderFieldsTooLarge: 431,
2794
- UnavailableForLegalReasons: 451,
2795
- InternalServerError: 500,
2796
- NotImplemented: 501,
2797
- BadGateway: 502,
2798
- ServiceUnavailable: 503,
2799
- GatewayTimeout: 504,
2800
- HttpVersionNotSupported: 505,
2801
- VariantAlsoNegotiates: 506,
2802
- InsufficientStorage: 507,
2803
- LoopDetected: 508,
2804
- NotExtended: 510,
2805
- NetworkAuthenticationRequired: 511
2806
- };
2807
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2808
- HttpStatusCode[value] = key;
2809
- });
2810
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2811
- /**
2812
- * Create an instance of Axios
2813
- *
2814
- * @param {Object} defaultConfig The default config for the instance
2815
- *
2816
- * @returns {Axios} A new instance of Axios
2817
- */ function createInstance(defaultConfig) {
2818
- const context = new Axios(defaultConfig);
2819
- const instance = bind(Axios.prototype.request, context);
2820
- // Copy axios.prototype to instance
2821
- utils.extend(instance, Axios.prototype, context, {
2822
- allOwnKeys: true
2823
- });
2824
- // Copy context to instance
2825
- utils.extend(instance, context, null, {
2826
- allOwnKeys: true
2827
- });
2828
- // Factory for creating new instances
2829
- instance.create = function(instanceConfig) {
2830
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2831
- };
2832
- return instance;
2833
- }
2834
- // Create the default instance to be exported
2835
- const axios = createInstance(defaults);
2836
- // Expose Axios class to allow class inheritance
2837
- axios.Axios = Axios;
2838
- // Expose Cancel & CancelToken
2839
- axios.CanceledError = CanceledError;
2840
- axios.CancelToken = CancelToken;
2841
- axios.isCancel = isCancel;
2842
- axios.VERSION = VERSION;
2843
- axios.toFormData = toFormData;
2844
- // Expose AxiosError class
2845
- axios.AxiosError = core_AxiosError;
2846
- // alias for CanceledError for backward compatibility
2847
- axios.Cancel = axios.CanceledError;
2848
- // Expose all/spread
2849
- axios.all = function(promises) {
2850
- return Promise.all(promises);
2851
- };
2852
- axios.spread = spread;
2853
- // Expose isAxiosError
2854
- axios.isAxiosError = isAxiosError;
2855
- // Expose mergeConfig
2856
- axios.mergeConfig = mergeConfig;
2857
- axios.AxiosHeaders = AxiosHeaders;
2858
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2859
- axios.getAdapter = adapters_adapters.getAdapter;
2860
- axios.HttpStatusCode = helpers_HttpStatusCode;
2861
- axios.default = axios;
2862
- // this module should only have a default export
2863
- /* ESM default export */ const lib_axios = axios;
2864
- // This module is intended to unwrap Axios default export as named.
2865
- // Keep top-level export same with static properties
2866
- // so that it can keep same with es module or cjs
2867
- 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;
2868
- // EXTERNAL MODULE: os (ignored)
2869
- var os_ignored_ = __webpack_require__("?9caf");
2870
- // EXTERNAL MODULE: crypto (ignored)
2871
- __webpack_require__("?e272");
2872
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2873
- __webpack_require__("?5742");
2874
- class APIResource {
2875
- constructor(client){
2876
- this._client = client;
2877
- }
2878
- }
2879
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2880
- /**
2881
- * Create a new agent. | 调用接口创建一个新的智能体。
2882
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2883
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2884
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2885
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2886
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2887
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2888
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2889
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2890
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2891
- * @returns Information about the created bot. | 创建的 Bot 信息。
2892
- */ async create(params, options) {
2893
- const apiUrl = '/v1/bot/create';
2894
- const result = await this._client.post(apiUrl, params, false, options);
2895
- return result.data;
2896
- }
2897
- /**
2898
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2899
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2900
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2901
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2902
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2903
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2904
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2905
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2906
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2907
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2908
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2909
- * @returns Undefined | 无返回值
2910
- */ async update(params, options) {
2911
- const apiUrl = '/v1/bot/update';
2912
- const result = await this._client.post(apiUrl, params, false, options);
2913
- return result.data;
2914
- }
2915
- /**
2916
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2917
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2918
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2919
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2920
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2921
- * @param params.page_size - Optional Pagination size. | 分页大小。
2922
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2923
- * @returns List of published bots. | 已发布的 Bot 列表。
2924
- */ async list(params, options) {
2925
- const apiUrl = '/v1/space/published_bots_list';
2926
- const result = await this._client.get(apiUrl, params, false, options);
2927
- return result.data;
2928
- }
2929
- /**
2930
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2931
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2932
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2933
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2934
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2935
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2936
- * @returns Undefined | 无返回值
2937
- */ async publish(params, options) {
2938
- const apiUrl = '/v1/bot/publish';
2939
- const result = await this._client.post(apiUrl, params, false, options);
2940
- return result.data;
2941
- }
2942
- /**
2943
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2944
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2945
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2946
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2947
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2948
- * @returns Information about the bot. | Bot 的配置信息。
2949
- */ async retrieve(params, options) {
2950
- const apiUrl = '/v1/bot/get_online_info';
2951
- const result = await this._client.get(apiUrl, params, false, options);
2952
- return result.data;
2953
- }
2954
- }
2955
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2956
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2957
- try {
2958
- return JSON.parse(jsonString);
2959
- } catch (error) {
2960
- return defaultValue;
2961
- }
2962
- }
2963
- function sleep(ms) {
2964
- return new Promise((resolve)=>{
2965
- setTimeout(resolve, ms);
2966
- });
2967
- }
2968
- function isBrowser() {
2969
- return 'undefined' != typeof window;
2970
- }
2971
- function esm_isPlainObject(obj) {
2972
- if ('object' != typeof obj || null === obj) return false;
2973
- const proto = Object.getPrototypeOf(obj);
2974
- if (null === proto) return true;
2975
- let baseProto = proto;
2976
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2977
- return proto === baseProto;
2978
- }
2979
- function esm_mergeConfig() {
2980
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2981
- return objects.reduce((result, obj)=>{
2982
- if (void 0 === obj) return result || {};
2983
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2984
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2985
- else result[key] = obj[key];
2986
- }
2987
- return result;
2988
- }, {});
2989
- }
2990
- function isPersonalAccessToken(token) {
2991
- return null == token ? void 0 : token.startsWith('pat_');
2992
- }
2993
- /* eslint-disable max-params */ class CozeError extends Error {
2994
- }
2995
- class APIError extends CozeError {
2996
- static makeMessage(status, errorBody, message, headers) {
2997
- if (!errorBody && message) return message;
2998
- if (errorBody) {
2999
- const list = [];
3000
- const { code, msg, error } = errorBody;
3001
- if (code) list.push(`code: ${code}`);
3002
- if (msg) list.push(`msg: ${msg}`);
3003
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
3004
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
3005
- if (logId) list.push(`logid: ${logId}`);
3006
- const help_doc = null == error ? void 0 : error.help_doc;
3007
- if (help_doc) list.push(`help doc: ${help_doc}`);
3008
- return list.join(', ');
3009
- }
3010
- if (status) return `http status code: ${status} (no body)`;
3011
- return '(no status code or body)';
3012
- }
3013
- static generate(status, errorResponse, message, headers) {
3014
- if (!status) return new APIConnectionError({
3015
- cause: castToError(errorResponse)
3016
- });
3017
- const error = errorResponse;
3018
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
3019
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3020
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3021
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3022
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3023
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3024
- if (408 === status) return new TimeoutError(status, error, message, headers);
3025
- if (502 === status) return new GatewayError(status, error, message, headers);
3026
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3027
- return new APIError(status, error, message, headers);
3028
- }
3029
- constructor(status, error, message, headers){
3030
- var _error_error, _error_error1;
3031
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3032
- this.status = status;
3033
- this.headers = headers;
3034
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3035
- // this.error = error;
3036
- this.code = null == error ? void 0 : error.code;
3037
- this.msg = null == error ? void 0 : error.msg;
3038
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3039
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3040
- this.rawError = error;
3041
- }
3042
- }
3043
- class APIConnectionError extends APIError {
3044
- constructor({ message, cause }){
3045
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3046
- // if (cause) {
3047
- // this.cause = cause;
3048
- // }
3049
- }
3050
- }
3051
- class APIUserAbortError extends APIError {
3052
- constructor(message){
3053
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3054
- }
3055
- }
3056
- class BadRequestError extends APIError {
3057
- constructor(...args){
3058
- super(...args), this.name = 'BadRequestError', this.status = 400;
3059
- }
3060
- }
3061
- class AuthenticationError extends APIError {
3062
- constructor(...args){
3063
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3064
- }
3065
- }
3066
- class PermissionDeniedError extends APIError {
3067
- constructor(...args){
3068
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3069
- }
3070
- }
3071
- class NotFoundError extends APIError {
3072
- constructor(...args){
3073
- super(...args), this.name = 'NotFoundError', this.status = 404;
3074
- }
3075
- }
3076
- class TimeoutError extends APIError {
3077
- constructor(...args){
3078
- super(...args), this.name = 'TimeoutError', this.status = 408;
3079
- }
3080
- }
3081
- class RateLimitError extends APIError {
3082
- constructor(...args){
3083
- super(...args), this.name = 'RateLimitError', this.status = 429;
3084
- }
3085
- }
3086
- class InternalServerError extends APIError {
3087
- constructor(...args){
3088
- super(...args), this.name = 'InternalServerError', this.status = 500;
3089
- }
3090
- }
3091
- class GatewayError extends APIError {
3092
- constructor(...args){
3093
- super(...args), this.name = 'GatewayError', this.status = 502;
3094
- }
3095
- }
3096
- const castToError = (err)=>{
3097
- if (err instanceof Error) return err;
3098
- return new Error(err);
3099
- };
3100
- class Messages extends APIResource {
3101
- /**
3102
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3103
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3104
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3105
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3106
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3107
- * @returns An array of chat messages. | 对话消息数组。
3108
- */ async list(conversation_id, chat_id, options) {
3109
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3110
- const result = await this._client.get(apiUrl, void 0, false, options);
3111
- return result.data;
3112
- }
3113
- }
3114
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3115
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3116
- ...i,
3117
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3118
- }));
3119
- class Chat extends APIResource {
3120
- /**
3121
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3122
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3123
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3124
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3125
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3126
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3127
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3128
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3129
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3130
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3131
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3132
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3133
- * @returns The data of the created chat. | 创建的对话数据。
3134
- */ async create(params, options) {
3135
- if (!params.user_id) params.user_id = uuid();
3136
- const { conversation_id, ...rest } = params;
3137
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3138
- const payload = {
3139
- ...rest,
3140
- additional_messages: handleAdditionalMessages(params.additional_messages),
3141
- stream: false
3142
- };
3143
- const result = await this._client.post(apiUrl, payload, false, options);
3144
- return result.data;
3145
- }
3146
- /**
3147
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3148
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3149
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3150
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3151
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3152
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3153
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3154
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3155
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3156
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3157
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3158
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3159
- * @returns
3160
- */ async createAndPoll(params, options) {
3161
- if (!params.user_id) params.user_id = uuid();
3162
- const { conversation_id, ...rest } = params;
3163
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3164
- const payload = {
3165
- ...rest,
3166
- additional_messages: handleAdditionalMessages(params.additional_messages),
3167
- stream: false
3168
- };
3169
- const result = await this._client.post(apiUrl, payload, false, options);
3170
- const chatId = result.data.id;
3171
- const conversationId = result.data.conversation_id;
3172
- let chat;
3173
- while(true){
3174
- await sleep(100);
3175
- chat = await this.retrieve(conversationId, chatId);
3176
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3177
- }
3178
- const messageList = await this.messages.list(conversationId, chatId);
3179
- return {
3180
- chat,
3181
- messages: messageList
3182
- };
3183
- }
3184
- /**
3185
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3186
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3187
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3188
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3189
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3190
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3191
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3192
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3193
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3194
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3195
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3196
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3197
- * @returns A stream of chat data. | 对话数据流。
3198
- */ async *stream(params, options) {
3199
- if (!params.user_id) params.user_id = uuid();
3200
- const { conversation_id, ...rest } = params;
3201
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3202
- const payload = {
3203
- ...rest,
3204
- additional_messages: handleAdditionalMessages(params.additional_messages),
3205
- stream: true
3206
- };
3207
- const result = await this._client.post(apiUrl, payload, true, options);
3208
- for await (const message of result)if ("done" === message.event) {
3209
- const ret = {
3210
- event: message.event,
3211
- data: '[DONE]'
3212
- };
3213
- yield ret;
3214
- } else try {
3215
- const ret = {
3216
- event: message.event,
3217
- data: JSON.parse(message.data)
3218
- };
3219
- yield ret;
3220
- } catch (error) {
3221
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3222
- }
3223
- }
3224
- /**
3225
- * Get the detailed information of the chat. | 查看对话的详细信息。
3226
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3227
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3228
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3229
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3230
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3231
- */ async retrieve(conversation_id, chat_id, options) {
3232
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3233
- const result = await this._client.post(apiUrl, void 0, false, options);
3234
- return result.data;
3235
- }
3236
- /**
3237
- * Cancel a chat session. | 取消对话会话。
3238
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3239
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3240
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3241
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3242
- * @returns The data of the canceled chat. | 取消的对话数据。
3243
- */ async cancel(conversation_id, chat_id, options) {
3244
- const apiUrl = '/v3/chat/cancel';
3245
- const payload = {
3246
- conversation_id,
3247
- chat_id
3248
- };
3249
- const result = await this._client.post(apiUrl, payload, false, options);
3250
- return result.data;
3251
- }
3252
- /**
3253
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3254
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3255
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3256
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3257
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3258
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3259
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3260
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3261
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3262
- */ async *submitToolOutputs(params, options) {
3263
- const { conversation_id, chat_id, ...rest } = params;
3264
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3265
- const payload = {
3266
- ...rest
3267
- };
3268
- if (false === params.stream) {
3269
- const response = await this._client.post(apiUrl, payload, false, options);
3270
- return response.data;
3071
+ config = mergeConfig_mergeConfig(this.defaults, config);
3072
+ const { transitional, paramsSerializer, headers } = config;
3073
+ if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
3074
+ silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
3075
+ forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
3076
+ clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean)
3077
+ }, false);
3078
+ if (null != paramsSerializer) {
3079
+ if (utils.isFunction(paramsSerializer)) config.paramsSerializer = {
3080
+ serialize: paramsSerializer
3081
+ };
3082
+ else helpers_validator.assertOptions(paramsSerializer, {
3083
+ encode: Axios_validators.function,
3084
+ serialize: Axios_validators.function
3085
+ }, true);
3271
3086
  }
3272
- {
3273
- const result = await this._client.post(apiUrl, payload, true, options);
3274
- for await (const message of result)if ("done" === message.event) {
3275
- const ret = {
3276
- event: message.event,
3277
- data: '[DONE]'
3278
- };
3279
- yield ret;
3280
- } else try {
3281
- const ret = {
3282
- event: message.event,
3283
- data: JSON.parse(message.data)
3284
- };
3285
- yield ret;
3087
+ // Set config.method
3088
+ config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3089
+ // Flatten headers
3090
+ let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
3091
+ headers && utils.forEach([
3092
+ 'delete',
3093
+ 'get',
3094
+ 'head',
3095
+ 'post',
3096
+ 'put',
3097
+ 'patch',
3098
+ 'common'
3099
+ ], (method)=>{
3100
+ delete headers[method];
3101
+ });
3102
+ config.headers = AxiosHeaders.concat(contextHeaders, headers);
3103
+ // filter out skipped interceptors
3104
+ const requestInterceptorChain = [];
3105
+ let synchronousRequestInterceptors = true;
3106
+ this.interceptors.request.forEach(function(interceptor) {
3107
+ if ('function' == typeof interceptor.runWhen && false === interceptor.runWhen(config)) return;
3108
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3109
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3110
+ });
3111
+ const responseInterceptorChain = [];
3112
+ this.interceptors.response.forEach(function(interceptor) {
3113
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3114
+ });
3115
+ let promise;
3116
+ let i = 0;
3117
+ let len;
3118
+ if (!synchronousRequestInterceptors) {
3119
+ const chain = [
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;
3129
+ }
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);
3286
3138
  } catch (error) {
3287
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3139
+ onRejected.call(this, error);
3140
+ break;
3288
3141
  }
3289
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;
3290
3152
  }
3291
- constructor(...args){
3292
- 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);
3293
3157
  }
3294
3158
  }
3295
- var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
3296
- ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3297
- ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3298
- ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3299
- ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3300
- ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3301
- ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3302
- ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3303
- ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3304
- ChatEventType["DONE"] = "done";
3305
- ChatEventType["ERROR"] = "error";
3306
- return ChatEventType;
3307
- }({});
3308
- class messages_Messages extends APIResource {
3309
- /**
3310
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3311
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3312
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3313
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3314
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3315
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3316
- * @param params.content - Required The content of the message. | 消息的内容。
3317
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3318
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3319
- * @returns Information about the new message. | 消息详情。
3320
- */ async create(conversation_id, params, options) {
3321
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3322
- const response = await this._client.post(apiUrl, params, false, options);
3323
- return response.data;
3324
- }
3325
- /**
3326
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3327
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3328
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3329
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3330
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3331
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3332
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3333
- * @param params.content - Optional The content of the message. | 消息的内容。
3334
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3335
- * @returns Information about the modified message. | 消息详情。
3336
- */ // eslint-disable-next-line max-params
3337
- async update(conversation_id, message_id, params, options) {
3338
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3339
- const response = await this._client.post(apiUrl, params, false, options);
3340
- return response.message;
3341
- }
3342
- /**
3343
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3344
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3345
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3346
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3347
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3348
- * @returns Information about the message. | 消息详情。
3349
- */ async retrieve(conversation_id, message_id, options) {
3350
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3351
- const response = await this._client.get(apiUrl, null, false, options);
3352
- 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
+ };
3353
3190
  }
3354
- /**
3355
- * List messages in a conversation. | 列出会话中的消息。
3356
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3357
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3358
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3359
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3360
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3361
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3362
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3363
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3364
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3365
- * @returns A list of messages. | 消息列表。
3366
- */ async list(conversation_id, params, options) {
3367
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3368
- const response = await this._client.post(apiUrl, params, false, options);
3369
- 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
+ });
3370
3235
  }
3371
3236
  /**
3372
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3373
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3374
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3375
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3376
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3377
- * @returns Details of the deleted message. | 已删除的消息详情。
3378
- */ async delete(conversation_id, message_id, options) {
3379
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3380
- const response = await this._client.post(apiUrl, void 0, false, options);
3381
- return response.data;
3237
+ * Throws a `CanceledError` if cancellation has been requested.
3238
+ */ throwIfRequested() {
3239
+ if (this.reason) throw this.reason;
3382
3240
  }
3383
- }
3384
- class Conversations extends APIResource {
3385
3241
  /**
3386
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3387
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3388
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3389
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3390
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3391
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3392
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3393
- * @returns Information about the created conversation. | 会话的基础信息。
3394
- */ async create(params, options) {
3395
- const apiUrl = '/v1/conversation/create';
3396
- const response = await this._client.post(apiUrl, params, false, options);
3397
- 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
+ ];
3398
3252
  }
3399
3253
  /**
3400
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3401
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3402
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3403
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3404
- * @returns Information about the conversation. | 会话的基础信息。
3405
- */ async retrieve(conversation_id, options) {
3406
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3407
- const response = await this._client.get(apiUrl, null, false, options);
3408
- 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);
3409
3259
  }
3410
- /**
3411
- * List all conversations. | 列出 Bot 下所有会话。
3412
- * @param params
3413
- * @param params.bot_id - Required Bot ID. | Bot ID。
3414
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3415
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3416
- * @returns Information about the conversations. | 会话的信息。
3417
- */ async list(params, options) {
3418
- const apiUrl = '/v1/conversations';
3419
- const response = await this._client.get(apiUrl, params, false, options);
3420
- 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;
3421
3268
  }
3422
3269
  /**
3423
- * Clear a conversation. | 清空会话。
3424
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3425
- * @returns Information about the conversation session. | 会话的会话 ID。
3426
- */ async clear(conversation_id, options) {
3427
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3428
- const response = await this._client.post(apiUrl, null, false, options);
3429
- return response.data;
3430
- }
3431
- constructor(...args){
3432
- 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
+ };
3433
3281
  }
3434
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;
3435
3444
  class Files extends APIResource {
3436
3445
  /**
3437
3446
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3594,7 +3603,7 @@
3594
3603
  * @returns ListDocumentData | 知识库文件列表
3595
3604
  */ list(params, options) {
3596
3605
  const apiUrl = '/open_api/knowledge/document/list';
3597
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3606
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3598
3607
  headers: documents_headers
3599
3608
  }));
3600
3609
  return response;
@@ -3612,7 +3621,7 @@
3612
3621
  * @returns DocumentInfo[] | 已上传文件的基本信息
3613
3622
  */ async create(params, options) {
3614
3623
  const apiUrl = '/open_api/knowledge/document/create';
3615
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3624
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3616
3625
  headers: documents_headers
3617
3626
  }));
3618
3627
  return response.document_infos;
@@ -3628,7 +3637,7 @@
3628
3637
  * @returns void | 无返回
3629
3638
  */ async delete(params, options) {
3630
3639
  const apiUrl = '/open_api/knowledge/document/delete';
3631
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3640
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3632
3641
  headers: documents_headers
3633
3642
  }));
3634
3643
  }
@@ -3644,7 +3653,7 @@
3644
3653
  * @returns void | 无返回
3645
3654
  */ async update(params, options) {
3646
3655
  const apiUrl = '/open_api/knowledge/document/update';
3647
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3656
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3648
3657
  headers: documents_headers
3649
3658
  }));
3650
3659
  }
@@ -3672,7 +3681,7 @@
3672
3681
  * @returns ListDocumentData | 知识库文件列表
3673
3682
  */ async list(params, options) {
3674
3683
  const apiUrl = '/open_api/knowledge/document/list';
3675
- const response = await this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3684
+ const response = await this._client.get(apiUrl, params, false, mergeConfig(options, {
3676
3685
  headers: documents_documents_headers
3677
3686
  }));
3678
3687
  return response;
@@ -3688,7 +3697,7 @@
3688
3697
  * @returns DocumentInfo[] | 已上传文件的基本信息
3689
3698
  */ async create(params, options) {
3690
3699
  const apiUrl = '/open_api/knowledge/document/create';
3691
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3700
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3692
3701
  headers: documents_documents_headers
3693
3702
  }));
3694
3703
  return response.document_infos;
@@ -3702,7 +3711,7 @@
3702
3711
  * @returns void | 无返回
3703
3712
  */ async delete(params, options) {
3704
3713
  const apiUrl = '/open_api/knowledge/document/delete';
3705
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3714
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3706
3715
  headers: documents_documents_headers
3707
3716
  }));
3708
3717
  }
@@ -3716,7 +3725,7 @@
3716
3725
  * @returns void | 无返回
3717
3726
  */ async update(params, options) {
3718
3727
  const apiUrl = '/open_api/knowledge/document/update';
3719
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3728
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3720
3729
  headers: documents_documents_headers
3721
3730
  }));
3722
3731
  }
@@ -3875,7 +3884,10 @@
3875
3884
  * @returns Speech synthesis data
3876
3885
  */ async create(params, options) {
3877
3886
  const apiUrl = '/v1/audio/speech';
3878
- 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, {
3879
3891
  responseType: 'arraybuffer'
3880
3892
  }));
3881
3893
  return response;
@@ -3888,23 +3900,40 @@
3888
3900
  return response.data;
3889
3901
  }
3890
3902
  }
3891
- class esm_Audio extends APIResource {
3903
+ class audio_Audio extends APIResource {
3892
3904
  constructor(...args){
3893
3905
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3894
3906
  }
3895
3907
  }
3896
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.15-beta.8","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","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"}}'); // CONCATENATED MODULE: ./src/version.ts
3897
- 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;
3898
3927
  const getEnv = ()=>{
3899
3928
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3900
3929
  const { platform } = process;
3901
3930
  let osName = platform.toLowerCase();
3902
- let osVersion = os_ignored_.release();
3931
+ let osVersion = os_ignored_default().release();
3903
3932
  if ('darwin' === platform) {
3904
3933
  osName = 'macos';
3905
3934
  // Try to parse the macOS version
3906
3935
  try {
3907
- const darwinVersion = os_ignored_.release().split('.');
3936
+ const darwinVersion = os_ignored_default().release().split('.');
3908
3937
  if (darwinVersion.length >= 2) {
3909
3938
  const majorVersion = parseInt(darwinVersion[0], 10);
3910
3939
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3917,10 +3946,10 @@
3917
3946
  }
3918
3947
  } else if ('win32' === platform) {
3919
3948
  osName = 'windows';
3920
- osVersion = os_ignored_.release();
3949
+ osVersion = os_ignored_default().release();
3921
3950
  } else if ('linux' === platform) {
3922
3951
  osName = 'linux';
3923
- osVersion = os_ignored_.release();
3952
+ osVersion = os_ignored_default().release();
3924
3953
  }
3925
3954
  return {
3926
3955
  osName,
@@ -3930,12 +3959,12 @@
3930
3959
  };
3931
3960
  const getUserAgent = ()=>{
3932
3961
  const { nodeVersion, osName, osVersion } = getEnv();
3933
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3962
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3934
3963
  };
3935
3964
  const getNodeClientUserAgent = ()=>{
3936
3965
  const { osVersion, nodeVersion, osName } = getEnv();
3937
3966
  const ua = {
3938
- version: esm_version,
3967
+ version: version_version,
3939
3968
  lang: 'node',
3940
3969
  lang_version: nodeVersion,
3941
3970
  os_name: osName,
@@ -3943,15 +3972,66 @@
3943
3972
  };
3944
3973
  return JSON.stringify(ua);
3945
3974
  };
3946
- /* 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)=>{
3947
4025
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3948
4026
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3949
4027
  var _error_response;
3950
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);
3951
4029
  }
3952
4030
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3953
- var _error_response1, _error_response2, _error_response3;
3954
- 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
+ }
3955
4035
  };
3956
4036
  async function fetchAPI(url) {
3957
4037
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -3967,7 +4047,7 @@
3967
4047
  adapter: options.isStreaming ? 'fetch' : void 0,
3968
4048
  ...options
3969
4049
  }).catch((error)=>{
3970
- throw esm_handleError(error);
4050
+ throw fetcher_handleError(error);
3971
4051
  });
3972
4052
  return {
3973
4053
  async *stream () {
@@ -4005,7 +4085,7 @@
4005
4085
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
4006
4086
  }
4007
4087
  } catch (error) {
4008
- esm_handleError(error);
4088
+ fetcher_handleError(error);
4009
4089
  }
4010
4090
  },
4011
4091
  json: ()=>response.data,
@@ -4029,8 +4109,8 @@
4029
4109
  }
4030
4110
  /**
4031
4111
  * default coze base URL is api.coze.com
4032
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
4033
- /* 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 {
4034
4114
  async getToken() {
4035
4115
  if ('function' == typeof this.token) return await this.token();
4036
4116
  return this.token;
@@ -4040,11 +4120,12 @@
4040
4120
  const headers = {
4041
4121
  authorization: `Bearer ${token}`
4042
4122
  };
4043
- if (!isBrowser()) {
4123
+ if (utils_isBrowser()) headers['X-Coze-Client-User-Agent'] = getBrowserClientUserAgent();
4124
+ else {
4044
4125
  headers['User-Agent'] = getUserAgent();
4045
4126
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
4046
4127
  }
4047
- const config = esm_mergeConfig(this.axiosOptions, options, {
4128
+ const config = mergeConfig(this.axiosOptions, options, {
4048
4129
  headers
4049
4130
  });
4050
4131
  config.method = method;
@@ -4068,7 +4149,7 @@
4068
4149
  if (contentType && contentType.includes('application/json')) {
4069
4150
  const result = await json();
4070
4151
  const { code, msg } = result;
4071
- 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);
4072
4153
  }
4073
4154
  return stream();
4074
4155
  }
@@ -4076,7 +4157,7 @@
4076
4157
  {
4077
4158
  const result = await json();
4078
4159
  const { code, msg } = result;
4079
- 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);
4080
4161
  return result;
4081
4162
  }
4082
4163
  }
@@ -4108,31 +4189,35 @@
4108
4189
  }
4109
4190
  constructor(config){
4110
4191
  this._config = config;
4111
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4192
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
4112
4193
  this.token = config.token;
4113
4194
  this.axiosOptions = config.axiosOptions || {};
4114
4195
  this.axiosInstance = config.axiosInstance;
4115
4196
  this.debug = config.debug || false;
4116
4197
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
4117
4198
  this.headers = config.headers;
4118
- 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');
4119
- }
4120
- }
4121
- APIClient.APIError = APIError;
4122
- APIClient.BadRequestError = BadRequestError;
4123
- APIClient.AuthenticationError = AuthenticationError;
4124
- APIClient.PermissionDeniedError = PermissionDeniedError;
4125
- APIClient.NotFoundError = NotFoundError;
4126
- APIClient.RateLimitError = RateLimitError;
4127
- APIClient.InternalServerError = InternalServerError;
4128
- APIClient.GatewayError = GatewayError;
4129
- APIClient.TimeoutError = TimeoutError;
4130
- APIClient.UserAbortError = APIUserAbortError;
4131
- 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 {
4132
4217
  constructor(...args){
4133
4218
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4134
4219
  * @deprecated
4135
- */ 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);
4136
4221
  }
4137
4222
  }
4138
4223
  /**
@@ -9364,7 +9449,7 @@
9364
9449
  }, stringPad = {
9365
9450
  start: createMethod(!1),
9366
9451
  end: createMethod(!0)
9367
- }, 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;
9368
9453
  $$F({
9369
9454
  target: "String",
9370
9455
  proto: !0,
@@ -38517,7 +38602,7 @@
38517
38602
  + * @param milliseconds The time to sleep in milliseconds
38518
38603
  + * @throws {Error} If milliseconds is negative
38519
38604
  + * @returns Promise that resolves after the specified duration
38520
- + */ const utils_sleep = (milliseconds)=>{
38605
+ + */ const src_utils_sleep = (milliseconds)=>{
38521
38606
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38522
38607
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38523
38608
  };
@@ -42114,7 +42199,7 @@
42114
42199
  var _this__videoConfig1;
42115
42200
  this.engine.setVideoSourceType(StreamIndex$1.STREAM_INDEX_SCREEN, VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
42116
42201
  await this.engine.startScreenCapture(null === (_this__videoConfig1 = this._videoConfig) || void 0 === _this__videoConfig1 ? void 0 : _this__videoConfig1.screenConfig);
42117
- await this.engine.publishScreen(MediaType$1.AUDIO_AND_VIDEO);
42202
+ await this.engine.publishScreen(MediaType$1.VIDEO);
42118
42203
  }
42119
42204
  this._streamIndex = StreamIndex$1.STREAM_INDEX_SCREEN;
42120
42205
  } else {
@@ -42133,7 +42218,7 @@
42133
42218
  video: this._isSupportVideo
42134
42219
  });
42135
42220
  if (!devices.audioInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get audio devices');
42136
- if (!devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get video devices');
42221
+ if (this._isSupportVideo && !devices.videoInputs.length) throw new RealtimeAPIError(error_RealtimeError.DEVICE_ACCESS_ERROR, 'Failed to get video devices');
42137
42222
  await this.engine.startAudioCapture(devices.audioInputs[0].deviceId);
42138
42223
  if (this._isSupportVideo) this.setVideoInputDevice((null == videoConfig ? void 0 : videoConfig.videoInputDeviceId) || devices.videoInputs[0].deviceId, null == videoConfig ? void 0 : videoConfig.videoOnDefault);
42139
42224
  }
@@ -42166,12 +42251,12 @@
42166
42251
  var _this__videoConfig;
42167
42252
  this.engine.setVideoSourceType(StreamIndex$1.STREAM_INDEX_SCREEN, VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL);
42168
42253
  await this.engine.startScreenCapture(null === (_this__videoConfig = this._videoConfig) || void 0 === _this__videoConfig ? void 0 : _this__videoConfig.screenConfig);
42169
- await this.engine.publishScreen(MediaType$1.AUDIO_AND_VIDEO);
42254
+ await this.engine.publishScreen(MediaType$1.VIDEO);
42170
42255
  }
42171
42256
  } else if (this._streamIndex === StreamIndex$1.STREAM_INDEX_MAIN) await this.engine.stopVideoCapture();
42172
42257
  else {
42173
42258
  await this.engine.stopScreenCapture();
42174
- await this.engine.unpublishScreen(MediaType$1.AUDIO_AND_VIDEO);
42259
+ await this.engine.unpublishScreen(MediaType$1.VIDEO);
42175
42260
  }
42176
42261
  } catch (e) {
42177
42262
  this.dispatch(event_handler_EventNames.ERROR, e);