@coze/realtime-api 1.0.2 → 1.0.3-beta.2

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.
@@ -1,11 +1,11 @@
1
- /*! For license information please see index.cjs.LICENSE.txt */
1
+ /*! For license information please see index.js.LICENSE.txt */
2
2
  "use strict";
3
3
  var __webpack_modules__ = {
4
- "?e272": function() {
4
+ "?666e": function() {
5
5
  /* (ignored) */ },
6
- "?5742": function() {
6
+ "?79fd": function() {
7
7
  /* (ignored) */ },
8
- "?9caf": function() {
8
+ "?9050": function() {
9
9
  /* (ignored) */ }
10
10
  };
11
11
  /************************************************************************/ // The module cache
@@ -24,7 +24,22 @@ function __webpack_require__(moduleId) {
24
24
  // Return the exports of the module
25
25
  return module.exports;
26
26
  }
27
- /************************************************************************/ // webpack/runtime/define_property_getters
27
+ /************************************************************************/ // webpack/runtime/compat_get_default_export
28
+ (()=>{
29
+ // getDefaultExport function for compatibility with non-ESM modules
30
+ __webpack_require__.n = function(module) {
31
+ var getter = module && module.__esModule ? function() {
32
+ return module['default'];
33
+ } : function() {
34
+ return module;
35
+ };
36
+ __webpack_require__.d(getter, {
37
+ a: getter
38
+ });
39
+ return getter;
40
+ };
41
+ })();
42
+ // webpack/runtime/define_property_getters
28
43
  (()=>{
29
44
  __webpack_require__.d = function(exports1, definition) {
30
45
  for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
@@ -87,478 +102,1040 @@ __webpack_require__.d(common_utils_namespaceObject, {
87
102
  var src_utils_namespaceObject = {};
88
103
  __webpack_require__.r(src_utils_namespaceObject);
89
104
  __webpack_require__.d(src_utils_namespaceObject, {
105
+ checkDevicePermission: ()=>checkDevicePermission,
90
106
  checkPermission: ()=>checkPermission,
91
107
  getAudioDevices: ()=>getAudioDevices,
92
- sleep: ()=>utils_sleep
108
+ sleep: ()=>src_utils_sleep
93
109
  });
94
- function bind(fn, thisArg) {
95
- return function() {
96
- return fn.apply(thisArg, arguments);
97
- };
110
+ class APIResource {
111
+ constructor(client){
112
+ this._client = client;
113
+ }
98
114
  }
99
- // utils is a library of generic helper functions non-specific to axios
100
- const { toString: utils_toString } = Object.prototype;
101
- const { getPrototypeOf } = Object;
102
- const kindOf = ((cache)=>(thing)=>{
103
- const str = utils_toString.call(thing);
104
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
105
- })(Object.create(null));
106
- const kindOfTest = (type)=>{
107
- type = type.toLowerCase();
108
- return (thing)=>kindOf(thing) === type;
109
- };
110
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
111
- /**
112
- * Determine if a value is an Array
113
- *
114
- * @param {Object} val The value to test
115
- *
116
- * @returns {boolean} True if value is an Array, otherwise false
117
- */ const { isArray } = Array;
118
- /**
119
- * Determine if a value is undefined
120
- *
121
- * @param {*} val The value to test
122
- *
123
- * @returns {boolean} True if the value is undefined, otherwise false
124
- */ const isUndefined = typeOfTest('undefined');
125
- /**
126
- * Determine if a value is a Buffer
127
- *
128
- * @param {*} val The value to test
129
- *
130
- * @returns {boolean} True if value is a Buffer, otherwise false
131
- */ function isBuffer(val) {
132
- return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
115
+ /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
116
+ /**
117
+ * Create a new agent. | 调用接口创建一个新的智能体。
118
+ * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
119
+ * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
120
+ * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
121
+ * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
122
+ * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
123
+ * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
124
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
125
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
126
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
127
+ * @returns Information about the created bot. | 创建的 Bot 信息。
128
+ */ async create(params, options) {
129
+ const apiUrl = '/v1/bot/create';
130
+ const result = await this._client.post(apiUrl, params, false, options);
131
+ return result.data;
132
+ }
133
+ /**
134
+ * Update the configuration of an agent. | 调用接口修改智能体的配置。
135
+ * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
136
+ * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
137
+ * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
138
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
139
+ * @param params.name - Optional The name of the agent. | Bot 的名称。
140
+ * @param params.description - Optional The description of the agent. | Bot 的描述信息。
141
+ * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
142
+ * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
143
+ * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
144
+ * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
145
+ * @returns Undefined | 无返回值
146
+ */ async update(params, options) {
147
+ const apiUrl = '/v1/bot/update';
148
+ const result = await this._client.post(apiUrl, params, false, options);
149
+ return result.data;
150
+ }
151
+ /**
152
+ * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
153
+ * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
154
+ * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
155
+ * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
156
+ * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
157
+ * @param params.page_size - Optional Pagination size. | 分页大小。
158
+ * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
159
+ * @returns List of published bots. | 已发布的 Bot 列表。
160
+ */ async list(params, options) {
161
+ const apiUrl = '/v1/space/published_bots_list';
162
+ const result = await this._client.get(apiUrl, params, false, options);
163
+ return result.data;
164
+ }
165
+ /**
166
+ * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
167
+ * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
168
+ * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
169
+ * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
170
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
171
+ * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
172
+ * @returns Undefined | 无返回值
173
+ */ async publish(params, options) {
174
+ const apiUrl = '/v1/bot/publish';
175
+ const result = await this._client.post(apiUrl, params, false, options);
176
+ return result.data;
177
+ }
178
+ /**
179
+ * Get the configuration information of the agent. | 获取指定智能体的配置信息。
180
+ * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
181
+ * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
182
+ * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
183
+ * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
184
+ * @returns Information about the bot. | Bot 的配置信息。
185
+ */ async retrieve(params, options) {
186
+ const apiUrl = '/v1/bot/get_online_info';
187
+ const result = await this._client.get(apiUrl, params, false, options);
188
+ return result.data;
189
+ }
133
190
  }
134
- /**
135
- * Determine if a value is an ArrayBuffer
136
- *
137
- * @param {*} val The value to test
138
- *
139
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
140
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
141
- /**
142
- * Determine if a value is a view on an ArrayBuffer
143
- *
144
- * @param {*} val The value to test
145
- *
146
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
147
- */ function isArrayBufferView(val) {
148
- let result;
149
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
150
- return result;
191
+ /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
192
+ let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
193
+ try {
194
+ return JSON.parse(jsonString);
195
+ } catch (error) {
196
+ return defaultValue;
197
+ }
151
198
  }
152
- /**
153
- * Determine if a value is a String
154
- *
155
- * @param {*} val The value to test
156
- *
157
- * @returns {boolean} True if value is a String, otherwise false
158
- */ const isString = typeOfTest('string');
159
- /**
160
- * Determine if a value is a Function
161
- *
162
- * @param {*} val The value to test
163
- * @returns {boolean} True if value is a Function, otherwise false
164
- */ const isFunction = typeOfTest('function');
165
- /**
166
- * Determine if a value is a Number
167
- *
168
- * @param {*} val The value to test
169
- *
170
- * @returns {boolean} True if value is a Number, otherwise false
171
- */ const isNumber = typeOfTest('number');
172
- /**
173
- * Determine if a value is an Object
174
- *
175
- * @param {*} thing The value to test
176
- *
177
- * @returns {boolean} True if value is an Object, otherwise false
178
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
179
- /**
180
- * Determine if a value is a Boolean
181
- *
182
- * @param {*} thing The value to test
183
- * @returns {boolean} True if value is a Boolean, otherwise false
184
- */ const isBoolean = (thing)=>true === thing || false === thing;
185
- /**
186
- * Determine if a value is a plain Object
187
- *
188
- * @param {*} val The value to test
189
- *
190
- * @returns {boolean} True if value is a plain Object, otherwise false
191
- */ const isPlainObject = (val)=>{
192
- if ('object' !== kindOf(val)) return false;
193
- const prototype = getPrototypeOf(val);
194
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
195
- };
196
- /**
197
- * Determine if a value is a Date
198
- *
199
- * @param {*} val The value to test
200
- *
201
- * @returns {boolean} True if value is a Date, otherwise false
202
- */ const isDate = kindOfTest('Date');
203
- /**
204
- * Determine if a value is a File
205
- *
206
- * @param {*} val The value to test
207
- *
208
- * @returns {boolean} True if value is a File, otherwise false
209
- */ const isFile = kindOfTest('File');
210
- /**
211
- * Determine if a value is a Blob
212
- *
213
- * @param {*} val The value to test
214
- *
215
- * @returns {boolean} True if value is a Blob, otherwise false
216
- */ const isBlob = kindOfTest('Blob');
217
- /**
218
- * Determine if a value is a FileList
219
- *
220
- * @param {*} val The value to test
221
- *
222
- * @returns {boolean} True if value is a File, otherwise false
223
- */ const utils_isFileList = kindOfTest('FileList');
224
- /**
225
- * Determine if a value is a Stream
226
- *
227
- * @param {*} val The value to test
228
- *
229
- * @returns {boolean} True if value is a Stream, otherwise false
230
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
231
- /**
232
- * Determine if a value is a FormData
233
- *
234
- * @param {*} thing The value to test
235
- *
236
- * @returns {boolean} True if value is an FormData, otherwise false
237
- */ const utils_isFormData = (thing)=>{
238
- let kind;
239
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
240
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
241
- };
242
- /**
243
- * Determine if a value is a URLSearchParams object
244
- *
245
- * @param {*} val The value to test
246
- *
247
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
248
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
249
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
250
- 'ReadableStream',
251
- 'Request',
252
- 'Response',
253
- 'Headers'
254
- ].map(kindOfTest);
255
- /**
256
- * Trim excess whitespace off the beginning and end of a string
257
- *
258
- * @param {String} str The String to trim
259
- *
260
- * @returns {String} The String freed of excess whitespace
261
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
262
- /**
263
- * Iterate over an Array or an Object invoking a function for each item.
264
- *
265
- * If `obj` is an Array callback will be called passing
266
- * the value, index, and complete array for each item.
267
- *
268
- * If 'obj' is an Object callback will be called passing
269
- * the value, key, and complete object for each property.
270
- *
271
- * @param {Object|Array} obj The object to iterate
272
- * @param {Function} fn The callback to invoke for each item
273
- *
274
- * @param {Boolean} [allOwnKeys = false]
275
- * @returns {any}
276
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
277
- // Don't bother if no value provided
278
- if (null == obj) return;
279
- let i;
280
- let l;
281
- // Force an array if not already something iterable
282
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
283
- obj
284
- ];
285
- if (isArray(obj)) // Iterate over array values
286
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
287
- else {
288
- // Iterate over object keys
289
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
290
- const len = keys.length;
291
- let key;
292
- for(i = 0; i < len; i++){
293
- key = keys[i];
294
- fn.call(null, obj[key], key, obj);
199
+ function utils_sleep(ms) {
200
+ return new Promise((resolve)=>{
201
+ setTimeout(resolve, ms);
202
+ });
203
+ }
204
+ function utils_isBrowser() {
205
+ return 'undefined' != typeof window;
206
+ }
207
+ function isPlainObject(obj) {
208
+ if ('object' != typeof obj || null === obj) return false;
209
+ const proto = Object.getPrototypeOf(obj);
210
+ if (null === proto) return true;
211
+ let baseProto = proto;
212
+ while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
213
+ return proto === baseProto;
214
+ }
215
+ function mergeConfig() {
216
+ for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
217
+ return objects.reduce((result, obj)=>{
218
+ if (void 0 === obj) return result || {};
219
+ for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
220
+ if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]);
221
+ else result[key] = obj[key];
222
+ }
223
+ return result;
224
+ }, {});
225
+ }
226
+ function isPersonalAccessToken(token) {
227
+ return null == token ? void 0 : token.startsWith('pat_');
228
+ }
229
+ /* eslint-disable max-params */ class CozeError extends Error {
230
+ }
231
+ class error_APIError extends CozeError {
232
+ static makeMessage(status, errorBody, message, headers) {
233
+ if (!errorBody && message) return message;
234
+ if (errorBody) {
235
+ const list = [];
236
+ const { code, msg, error } = errorBody;
237
+ if (code) list.push(`code: ${code}`);
238
+ if (msg) list.push(`msg: ${msg}`);
239
+ if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
240
+ const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
241
+ if (logId) list.push(`logid: ${logId}`);
242
+ const help_doc = null == error ? void 0 : error.help_doc;
243
+ if (help_doc) list.push(`help doc: ${help_doc}`);
244
+ return list.join(', ');
295
245
  }
246
+ if (status) return `http status code: ${status} (no body)`;
247
+ return '(no status code or body)';
248
+ }
249
+ static generate(status, errorResponse, message, headers) {
250
+ if (!status) return new APIConnectionError({
251
+ cause: castToError(errorResponse)
252
+ });
253
+ const error = errorResponse;
254
+ // https://www.coze.cn/docs/developer_guides/coze_error_codes
255
+ if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
256
+ if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
257
+ if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
258
+ if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
259
+ if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
260
+ if (408 === status) return new TimeoutError(status, error, message, headers);
261
+ if (502 === status) return new GatewayError(status, error, message, headers);
262
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
263
+ return new error_APIError(status, error, message, headers);
264
+ }
265
+ constructor(status, error, message, headers){
266
+ var _error_error, _error_error1;
267
+ super(`${error_APIError.makeMessage(status, error, message, headers)}`);
268
+ this.status = status;
269
+ this.headers = headers;
270
+ this.logid = null == headers ? void 0 : headers['x-tt-logid'];
271
+ // this.error = error;
272
+ this.code = null == error ? void 0 : error.code;
273
+ this.msg = null == error ? void 0 : error.msg;
274
+ this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
275
+ this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
276
+ this.rawError = error;
296
277
  }
297
278
  }
298
- function findKey(obj, key) {
299
- key = key.toLowerCase();
300
- const keys = Object.keys(obj);
301
- let i = keys.length;
302
- let _key;
303
- while(i-- > 0){
304
- _key = keys[i];
305
- if (key === _key.toLowerCase()) return _key;
279
+ class APIConnectionError extends error_APIError {
280
+ constructor({ message, cause }){
281
+ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
282
+ // if (cause) {
283
+ // this.cause = cause;
284
+ // }
306
285
  }
307
- return null;
308
286
  }
309
- const _global = (()=>{
310
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
311
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
312
- })();
313
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
314
- /**
315
- * Accepts varargs expecting each argument to be an object, then
316
- * immutably merges the properties of each object and returns result.
317
- *
318
- * When multiple objects contain the same key the later object in
319
- * the arguments list will take precedence.
320
- *
321
- * Example:
322
- *
323
- * ```js
324
- * var result = merge({foo: 123}, {foo: 456});
325
- * console.log(result.foo); // outputs 456
326
- * ```
327
- *
328
- * @param {Object} obj1 Object to merge
329
- *
330
- * @returns {Object} Result of all merge properties
331
- */ function utils_merge() {
332
- const { caseless } = isContextDefined(this) && this || {};
333
- const result = {};
334
- const assignValue = (val, key)=>{
335
- const targetKey = caseless && findKey(result, key) || key;
336
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
337
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
338
- else if (isArray(val)) result[targetKey] = val.slice();
339
- else result[targetKey] = val;
340
- };
341
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
342
- return result;
287
+ class APIUserAbortError extends error_APIError {
288
+ constructor(message){
289
+ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
290
+ }
343
291
  }
344
- /**
345
- * Extends object a by mutably adding to it the properties of object b.
346
- *
347
- * @param {Object} a The object to be extended
348
- * @param {Object} b The object to copy properties from
349
- * @param {Object} thisArg The object to bind function to
350
- *
351
- * @param {Boolean} [allOwnKeys]
352
- * @returns {Object} The resulting value of object a
353
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
354
- forEach(b, (val, key)=>{
355
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
356
- else a[key] = val;
357
- }, {
358
- allOwnKeys
359
- });
360
- return a;
361
- };
362
- /**
363
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
364
- *
365
- * @param {string} content with BOM
366
- *
367
- * @returns {string} content value without BOM
368
- */ const stripBOM = (content)=>{
369
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
370
- return content;
371
- };
372
- /**
373
- * Inherit the prototype methods from one constructor into another
374
- * @param {function} constructor
375
- * @param {function} superConstructor
376
- * @param {object} [props]
377
- * @param {object} [descriptors]
378
- *
379
- * @returns {void}
380
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
381
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
382
- constructor.prototype.constructor = constructor;
383
- Object.defineProperty(constructor, 'super', {
384
- value: superConstructor.prototype
385
- });
386
- props && Object.assign(constructor.prototype, props);
292
+ class BadRequestError extends error_APIError {
293
+ constructor(...args){
294
+ super(...args), this.name = 'BadRequestError', this.status = 400;
295
+ }
296
+ }
297
+ class AuthenticationError extends error_APIError {
298
+ constructor(...args){
299
+ super(...args), this.name = 'AuthenticationError', this.status = 401;
300
+ }
301
+ }
302
+ class PermissionDeniedError extends error_APIError {
303
+ constructor(...args){
304
+ super(...args), this.name = 'PermissionDeniedError', this.status = 403;
305
+ }
306
+ }
307
+ class NotFoundError extends error_APIError {
308
+ constructor(...args){
309
+ super(...args), this.name = 'NotFoundError', this.status = 404;
310
+ }
311
+ }
312
+ class TimeoutError extends error_APIError {
313
+ constructor(...args){
314
+ super(...args), this.name = 'TimeoutError', this.status = 408;
315
+ }
316
+ }
317
+ class RateLimitError extends error_APIError {
318
+ constructor(...args){
319
+ super(...args), this.name = 'RateLimitError', this.status = 429;
320
+ }
321
+ }
322
+ class InternalServerError extends error_APIError {
323
+ constructor(...args){
324
+ super(...args), this.name = 'InternalServerError', this.status = 500;
325
+ }
326
+ }
327
+ class GatewayError extends error_APIError {
328
+ constructor(...args){
329
+ super(...args), this.name = 'GatewayError', this.status = 502;
330
+ }
331
+ }
332
+ const castToError = (err)=>{
333
+ if (err instanceof Error) return err;
334
+ return new Error(err);
387
335
  };
388
- /**
389
- * Resolve object with deep prototype chain to a flat object
390
- * @param {Object} sourceObj source object
391
- * @param {Object} [destObj]
392
- * @param {Function|Boolean} [filter]
393
- * @param {Function} [propFilter]
394
- *
395
- * @returns {Object}
396
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
397
- let props;
398
- let i;
399
- let prop;
400
- const merged = {};
401
- destObj = destObj || {};
402
- // eslint-disable-next-line no-eq-null,eqeqeq
403
- if (null == sourceObj) return destObj;
404
- do {
405
- props = Object.getOwnPropertyNames(sourceObj);
406
- i = props.length;
407
- while(i-- > 0){
408
- prop = props[i];
409
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
410
- destObj[prop] = sourceObj[prop];
411
- merged[prop] = true;
412
- }
413
- }
414
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
415
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
416
- return destObj;
336
+ class Messages extends APIResource {
337
+ /**
338
+ * Get the list of messages in a chat. | 获取对话中的消息列表。
339
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
340
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
341
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
342
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
343
+ * @returns An array of chat messages. | 对话消息数组。
344
+ */ async list(conversation_id, chat_id, options) {
345
+ const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
346
+ const result = await this._client.get(apiUrl, void 0, false, options);
347
+ return result.data;
348
+ }
349
+ }
350
+ const uuid = ()=>(Math.random() * new Date().getTime()).toString();
351
+ const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
352
+ ...i,
353
+ content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
354
+ }));
355
+ class Chat extends APIResource {
356
+ /**
357
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
358
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
359
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
360
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
361
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
362
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
363
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
364
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
365
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
366
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
367
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
368
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
369
+ * @returns The data of the created chat. | 创建的对话数据。
370
+ */ async create(params, options) {
371
+ if (!params.user_id) params.user_id = uuid();
372
+ const { conversation_id, ...rest } = params;
373
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
374
+ const payload = {
375
+ ...rest,
376
+ additional_messages: handleAdditionalMessages(params.additional_messages),
377
+ stream: false
378
+ };
379
+ const result = await this._client.post(apiUrl, payload, false, options);
380
+ return result.data;
381
+ }
382
+ /**
383
+ * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
384
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
385
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
386
+ * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
387
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
388
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
389
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
390
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
391
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
392
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
393
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
394
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
395
+ * @returns
396
+ */ async createAndPoll(params, options) {
397
+ if (!params.user_id) params.user_id = uuid();
398
+ const { conversation_id, ...rest } = params;
399
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
400
+ const payload = {
401
+ ...rest,
402
+ additional_messages: handleAdditionalMessages(params.additional_messages),
403
+ stream: false
404
+ };
405
+ const result = await this._client.post(apiUrl, payload, false, options);
406
+ const chatId = result.data.id;
407
+ const conversationId = result.data.conversation_id;
408
+ let chat;
409
+ while(true){
410
+ await utils_sleep(100);
411
+ chat = await this.retrieve(conversationId, chatId);
412
+ if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
413
+ }
414
+ const messageList = await this.messages.list(conversationId, chatId);
415
+ return {
416
+ chat,
417
+ messages: messageList
418
+ };
419
+ }
420
+ /**
421
+ * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
422
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
423
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
424
+ * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
425
+ * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
426
+ * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
427
+ * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
428
+ * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
429
+ * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
430
+ * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
431
+ * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
432
+ * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
433
+ * @returns A stream of chat data. | 对话数据流。
434
+ */ async *stream(params, options) {
435
+ if (!params.user_id) params.user_id = uuid();
436
+ const { conversation_id, ...rest } = params;
437
+ const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
438
+ const payload = {
439
+ ...rest,
440
+ additional_messages: handleAdditionalMessages(params.additional_messages),
441
+ stream: true
442
+ };
443
+ const result = await this._client.post(apiUrl, payload, true, options);
444
+ for await (const message of result)if ("done" === message.event) {
445
+ const ret = {
446
+ event: message.event,
447
+ data: '[DONE]'
448
+ };
449
+ yield ret;
450
+ } else try {
451
+ const ret = {
452
+ event: message.event,
453
+ data: JSON.parse(message.data)
454
+ };
455
+ yield ret;
456
+ } catch (error) {
457
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
458
+ }
459
+ }
460
+ /**
461
+ * Get the detailed information of the chat. | 查看对话的详细信息。
462
+ * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
463
+ * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
464
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
465
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
466
+ * @returns The data of the retrieved chat. | 检索到的对话数据。
467
+ */ async retrieve(conversation_id, chat_id, options) {
468
+ const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
469
+ const result = await this._client.post(apiUrl, void 0, false, options);
470
+ return result.data;
471
+ }
472
+ /**
473
+ * Cancel a chat session. | 取消对话会话。
474
+ * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
475
+ * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
476
+ * @param conversation_id - Required The ID of the conversation. | 会话 ID。
477
+ * @param chat_id - Required The ID of the chat. | 对话 ID。
478
+ * @returns The data of the canceled chat. | 取消的对话数据。
479
+ */ async cancel(conversation_id, chat_id, options) {
480
+ const apiUrl = '/v3/chat/cancel';
481
+ const payload = {
482
+ conversation_id,
483
+ chat_id
484
+ };
485
+ const result = await this._client.post(apiUrl, payload, false, options);
486
+ return result.data;
487
+ }
488
+ /**
489
+ * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
490
+ * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
491
+ * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
492
+ * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
493
+ * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
494
+ * @param params.chat_id - Required The ID of the chat. | 对话 ID。
495
+ * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
496
+ * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
497
+ * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
498
+ */ async *submitToolOutputs(params, options) {
499
+ const { conversation_id, chat_id, ...rest } = params;
500
+ const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
501
+ const payload = {
502
+ ...rest
503
+ };
504
+ if (false === params.stream) {
505
+ const response = await this._client.post(apiUrl, payload, false, options);
506
+ return response.data;
507
+ }
508
+ {
509
+ const result = await this._client.post(apiUrl, payload, true, options);
510
+ for await (const message of result)if ("done" === message.event) {
511
+ const ret = {
512
+ event: message.event,
513
+ data: '[DONE]'
514
+ };
515
+ yield ret;
516
+ } else try {
517
+ const ret = {
518
+ event: message.event,
519
+ data: JSON.parse(message.data)
520
+ };
521
+ yield ret;
522
+ } catch (error) {
523
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
524
+ }
525
+ }
526
+ }
527
+ constructor(...args){
528
+ super(...args), this.messages = new Messages(this._client);
529
+ }
530
+ }
531
+ var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
532
+ ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
533
+ ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
534
+ ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
535
+ ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
536
+ ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
537
+ ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
538
+ ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
539
+ ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
540
+ ChatEventType["DONE"] = "done";
541
+ ChatEventType["ERROR"] = "error";
542
+ return ChatEventType;
543
+ }({});
544
+ class messages_Messages extends APIResource {
545
+ /**
546
+ * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
547
+ * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
548
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
549
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
550
+ * @param params - Required The parameters for creating a message | 创建消息所需的参数
551
+ * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
552
+ * @param params.content - Required The content of the message. | 消息的内容。
553
+ * @param params.content_type - Required The type of the message content. | 消息内容的类型。
554
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
555
+ * @returns Information about the new message. | 消息详情。
556
+ */ async create(conversation_id, params, options) {
557
+ const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
558
+ const response = await this._client.post(apiUrl, params, false, options);
559
+ return response.data;
560
+ }
561
+ /**
562
+ * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
563
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
564
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
565
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
566
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
567
+ * @param params - Required The parameters for modifying a message | 修改消息所需的参数
568
+ * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
569
+ * @param params.content - Optional The content of the message. | 消息的内容。
570
+ * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
571
+ * @returns Information about the modified message. | 消息详情。
572
+ */ // eslint-disable-next-line max-params
573
+ async update(conversation_id, message_id, params, options) {
574
+ const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
575
+ const response = await this._client.post(apiUrl, params, false, options);
576
+ return response.message;
577
+ }
578
+ /**
579
+ * Get the detailed information of specified message. | 查看指定消息的详细信息。
580
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
581
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
582
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
583
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
584
+ * @returns Information about the message. | 消息详情。
585
+ */ async retrieve(conversation_id, message_id, options) {
586
+ const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
587
+ const response = await this._client.get(apiUrl, null, false, options);
588
+ return response.data;
589
+ }
590
+ /**
591
+ * List messages in a conversation. | 列出会话中的消息。
592
+ * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
593
+ * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
594
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
595
+ * @param params - Optional The parameters for listing messages | 列出消息所需的参数
596
+ * @param params.order - Optional The order of the messages. | 消息的顺序。
597
+ * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
598
+ * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
599
+ * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
600
+ * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
601
+ * @returns A list of messages. | 消息列表。
602
+ */ async list(conversation_id, params, options) {
603
+ const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
604
+ const response = await this._client.post(apiUrl, params, false, options);
605
+ return response;
606
+ }
607
+ /**
608
+ * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
609
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
610
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
611
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
612
+ * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
613
+ * @returns Details of the deleted message. | 已删除的消息详情。
614
+ */ async delete(conversation_id, message_id, options) {
615
+ const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
616
+ const response = await this._client.post(apiUrl, void 0, false, options);
617
+ return response.data;
618
+ }
619
+ }
620
+ class Conversations extends APIResource {
621
+ /**
622
+ * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
623
+ * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
624
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
625
+ * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
626
+ * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
627
+ * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
628
+ * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
629
+ * @returns Information about the created conversation. | 会话的基础信息。
630
+ */ async create(params, options) {
631
+ const apiUrl = '/v1/conversation/create';
632
+ const response = await this._client.post(apiUrl, params, false, options);
633
+ return response.data;
634
+ }
635
+ /**
636
+ * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
637
+ * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
638
+ * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
639
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
640
+ * @returns Information about the conversation. | 会话的基础信息。
641
+ */ async retrieve(conversation_id, options) {
642
+ const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
643
+ const response = await this._client.get(apiUrl, null, false, options);
644
+ return response.data;
645
+ }
646
+ /**
647
+ * List all conversations. | 列出 Bot 下所有会话。
648
+ * @param params
649
+ * @param params.bot_id - Required Bot ID. | Bot ID。
650
+ * @param params.page_num - Optional The page number. | 页码,默认值为 1。
651
+ * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
652
+ * @returns Information about the conversations. | 会话的信息。
653
+ */ async list(params, options) {
654
+ const apiUrl = '/v1/conversations';
655
+ const response = await this._client.get(apiUrl, params, false, options);
656
+ return response.data;
657
+ }
658
+ /**
659
+ * Clear a conversation. | 清空会话。
660
+ * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
661
+ * @returns Information about the conversation session. | 会话的会话 ID。
662
+ */ async clear(conversation_id, options) {
663
+ const apiUrl = `/v1/conversations/${conversation_id}/clear`;
664
+ const response = await this._client.post(apiUrl, null, false, options);
665
+ return response.data;
666
+ }
667
+ constructor(...args){
668
+ super(...args), this.messages = new messages_Messages(this._client);
669
+ }
670
+ }
671
+ function bind(fn, thisArg) {
672
+ return function() {
673
+ return fn.apply(thisArg, arguments);
674
+ };
675
+ }
676
+ // utils is a library of generic helper functions non-specific to axios
677
+ const { toString: utils_toString } = Object.prototype;
678
+ const { getPrototypeOf } = Object;
679
+ const kindOf = ((cache)=>(thing)=>{
680
+ const str = utils_toString.call(thing);
681
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
682
+ })(Object.create(null));
683
+ const kindOfTest = (type)=>{
684
+ type = type.toLowerCase();
685
+ return (thing)=>kindOf(thing) === type;
417
686
  };
687
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
418
688
  /**
419
- * Determines whether a string ends with the characters of a specified string
689
+ * Determine if a value is an Array
420
690
  *
421
- * @param {String} str
422
- * @param {String} searchString
423
- * @param {Number} [position= 0]
691
+ * @param {Object} val The value to test
424
692
  *
425
- * @returns {boolean}
426
- */ const endsWith = (str, searchString, position)=>{
427
- str = String(str);
428
- if (void 0 === position || position > str.length) position = str.length;
429
- position -= searchString.length;
430
- const lastIndex = str.indexOf(searchString, position);
431
- return -1 !== lastIndex && lastIndex === position;
432
- };
693
+ * @returns {boolean} True if value is an Array, otherwise false
694
+ */ const { isArray } = Array;
433
695
  /**
434
- * Returns new array from array like object or null if failed
696
+ * Determine if a value is undefined
435
697
  *
436
- * @param {*} [thing]
698
+ * @param {*} val The value to test
437
699
  *
438
- * @returns {?Array}
439
- */ const toArray = (thing)=>{
440
- if (!thing) return null;
441
- if (isArray(thing)) return thing;
442
- let i = thing.length;
443
- if (!isNumber(i)) return null;
444
- const arr = new Array(i);
445
- while(i-- > 0)arr[i] = thing[i];
446
- return arr;
447
- };
700
+ * @returns {boolean} True if the value is undefined, otherwise false
701
+ */ const isUndefined = typeOfTest('undefined');
448
702
  /**
449
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
450
- * thing passed in is an instance of Uint8Array
703
+ * Determine if a value is a Buffer
451
704
  *
452
- * @param {TypedArray}
705
+ * @param {*} val The value to test
453
706
  *
454
- * @returns {Array}
455
- */ // eslint-disable-next-line func-names
456
- const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
707
+ * @returns {boolean} True if value is a Buffer, otherwise false
708
+ */ function isBuffer(val) {
709
+ return null !== val && !isUndefined(val) && null !== val.constructor && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
710
+ }
457
711
  /**
458
- * For each entry in the object, call the function with the key and value.
712
+ * Determine if a value is an ArrayBuffer
459
713
  *
460
- * @param {Object<any, any>} obj - The object to iterate over.
461
- * @param {Function} fn - The function to call for each entry.
714
+ * @param {*} val The value to test
462
715
  *
463
- * @returns {void}
464
- */ const forEachEntry = (obj, fn)=>{
465
- const generator = obj && obj[Symbol.iterator];
466
- const iterator = generator.call(obj);
716
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
717
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
718
+ /**
719
+ * Determine if a value is a view on an ArrayBuffer
720
+ *
721
+ * @param {*} val The value to test
722
+ *
723
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
724
+ */ function isArrayBufferView(val) {
467
725
  let result;
468
- while((result = iterator.next()) && !result.done){
469
- const pair = result.value;
470
- fn.call(obj, pair[0], pair[1]);
471
- }
472
- };
726
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
727
+ return result;
728
+ }
473
729
  /**
474
- * It takes a regular expression and a string, and returns an array of all the matches
730
+ * Determine if a value is a String
475
731
  *
476
- * @param {string} regExp - The regular expression to match against.
477
- * @param {string} str - The string to search.
732
+ * @param {*} val The value to test
478
733
  *
479
- * @returns {Array<boolean>}
480
- */ const matchAll = (regExp, str)=>{
481
- let matches;
482
- const arr = [];
483
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
484
- return arr;
485
- };
486
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
487
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
488
- return p1.toUpperCase() + p2;
489
- });
490
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
734
+ * @returns {boolean} True if value is a String, otherwise false
735
+ */ const isString = typeOfTest('string');
491
736
  /**
492
- * Determine if a value is a RegExp object
737
+ * Determine if a value is a Function
738
+ *
739
+ * @param {*} val The value to test
740
+ * @returns {boolean} True if value is a Function, otherwise false
741
+ */ const isFunction = typeOfTest('function');
742
+ /**
743
+ * Determine if a value is a Number
493
744
  *
494
745
  * @param {*} val The value to test
495
746
  *
496
- * @returns {boolean} True if value is a RegExp object, otherwise false
497
- */ const isRegExp = kindOfTest('RegExp');
498
- const reduceDescriptors = (obj, reducer)=>{
499
- const descriptors = Object.getOwnPropertyDescriptors(obj);
500
- const reducedDescriptors = {};
501
- forEach(descriptors, (descriptor, name)=>{
502
- let ret;
503
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
504
- });
505
- Object.defineProperties(obj, reducedDescriptors);
506
- };
747
+ * @returns {boolean} True if value is a Number, otherwise false
748
+ */ const isNumber = typeOfTest('number');
507
749
  /**
508
- * Makes all methods read-only
509
- * @param {Object} obj
510
- */ const freezeMethods = (obj)=>{
511
- reduceDescriptors(obj, (descriptor, name)=>{
512
- // skip restricted props in strict mode
513
- if (isFunction(obj) && -1 !== [
514
- 'arguments',
515
- 'caller',
516
- 'callee'
517
- ].indexOf(name)) return false;
518
- const value = obj[name];
519
- if (!isFunction(value)) return;
520
- descriptor.enumerable = false;
521
- if ('writable' in descriptor) {
522
- descriptor.writable = false;
523
- return;
524
- }
525
- if (!descriptor.set) descriptor.set = ()=>{
526
- throw Error('Can not rewrite read-only method \'' + name + '\'');
527
- };
528
- });
529
- };
530
- const toObjectSet = (arrayOrString, delimiter)=>{
531
- const obj = {};
532
- const define = (arr)=>{
533
- arr.forEach((value)=>{
534
- obj[value] = true;
535
- });
536
- };
537
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
538
- return obj;
539
- };
540
- const noop = ()=>{};
541
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
542
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
543
- const DIGIT = '0123456789';
544
- const ALPHABET = {
545
- DIGIT,
546
- ALPHA,
547
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
548
- };
549
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
550
- let str = '';
551
- const { length } = alphabet;
552
- while(size--)str += alphabet[Math.random() * length | 0];
553
- return str;
554
- };
750
+ * Determine if a value is an Object
751
+ *
752
+ * @param {*} thing The value to test
753
+ *
754
+ * @returns {boolean} True if value is an Object, otherwise false
755
+ */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
555
756
  /**
556
- * If the thing is a FormData object, return true, otherwise return false.
757
+ * Determine if a value is a Boolean
557
758
  *
558
- * @param {unknown} thing - The thing to check.
759
+ * @param {*} thing The value to test
760
+ * @returns {boolean} True if value is a Boolean, otherwise false
761
+ */ const isBoolean = (thing)=>true === thing || false === thing;
762
+ /**
763
+ * Determine if a value is a plain Object
559
764
  *
560
- * @returns {boolean}
561
- */ function isSpecCompliantForm(thing) {
765
+ * @param {*} val The value to test
766
+ *
767
+ * @returns {boolean} True if value is a plain Object, otherwise false
768
+ */ const utils_isPlainObject = (val)=>{
769
+ if ('object' !== kindOf(val)) return false;
770
+ const prototype = getPrototypeOf(val);
771
+ return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
772
+ };
773
+ /**
774
+ * Determine if a value is a Date
775
+ *
776
+ * @param {*} val The value to test
777
+ *
778
+ * @returns {boolean} True if value is a Date, otherwise false
779
+ */ const isDate = kindOfTest('Date');
780
+ /**
781
+ * Determine if a value is a File
782
+ *
783
+ * @param {*} val The value to test
784
+ *
785
+ * @returns {boolean} True if value is a File, otherwise false
786
+ */ const isFile = kindOfTest('File');
787
+ /**
788
+ * Determine if a value is a Blob
789
+ *
790
+ * @param {*} val The value to test
791
+ *
792
+ * @returns {boolean} True if value is a Blob, otherwise false
793
+ */ const isBlob = kindOfTest('Blob');
794
+ /**
795
+ * Determine if a value is a FileList
796
+ *
797
+ * @param {*} val The value to test
798
+ *
799
+ * @returns {boolean} True if value is a File, otherwise false
800
+ */ const utils_isFileList = kindOfTest('FileList');
801
+ /**
802
+ * Determine if a value is a Stream
803
+ *
804
+ * @param {*} val The value to test
805
+ *
806
+ * @returns {boolean} True if value is a Stream, otherwise false
807
+ */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
808
+ /**
809
+ * Determine if a value is a FormData
810
+ *
811
+ * @param {*} thing The value to test
812
+ *
813
+ * @returns {boolean} True if value is an FormData, otherwise false
814
+ */ const utils_isFormData = (thing)=>{
815
+ let kind;
816
+ return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
817
+ 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
818
+ };
819
+ /**
820
+ * Determine if a value is a URLSearchParams object
821
+ *
822
+ * @param {*} val The value to test
823
+ *
824
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
825
+ */ const isURLSearchParams = kindOfTest('URLSearchParams');
826
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
827
+ 'ReadableStream',
828
+ 'Request',
829
+ 'Response',
830
+ 'Headers'
831
+ ].map(kindOfTest);
832
+ /**
833
+ * Trim excess whitespace off the beginning and end of a string
834
+ *
835
+ * @param {String} str The String to trim
836
+ *
837
+ * @returns {String} The String freed of excess whitespace
838
+ */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
839
+ /**
840
+ * Iterate over an Array or an Object invoking a function for each item.
841
+ *
842
+ * If `obj` is an Array callback will be called passing
843
+ * the value, index, and complete array for each item.
844
+ *
845
+ * If 'obj' is an Object callback will be called passing
846
+ * the value, key, and complete object for each property.
847
+ *
848
+ * @param {Object|Array} obj The object to iterate
849
+ * @param {Function} fn The callback to invoke for each item
850
+ *
851
+ * @param {Boolean} [allOwnKeys = false]
852
+ * @returns {any}
853
+ */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
854
+ // Don't bother if no value provided
855
+ if (null == obj) return;
856
+ let i;
857
+ let l;
858
+ // Force an array if not already something iterable
859
+ if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
860
+ obj
861
+ ];
862
+ if (isArray(obj)) // Iterate over array values
863
+ for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
864
+ else {
865
+ // Iterate over object keys
866
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
867
+ const len = keys.length;
868
+ let key;
869
+ for(i = 0; i < len; i++){
870
+ key = keys[i];
871
+ fn.call(null, obj[key], key, obj);
872
+ }
873
+ }
874
+ }
875
+ function findKey(obj, key) {
876
+ key = key.toLowerCase();
877
+ const keys = Object.keys(obj);
878
+ let i = keys.length;
879
+ let _key;
880
+ while(i-- > 0){
881
+ _key = keys[i];
882
+ if (key === _key.toLowerCase()) return _key;
883
+ }
884
+ return null;
885
+ }
886
+ const _global = (()=>{
887
+ /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
888
+ return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
889
+ })();
890
+ const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
891
+ /**
892
+ * Accepts varargs expecting each argument to be an object, then
893
+ * immutably merges the properties of each object and returns result.
894
+ *
895
+ * When multiple objects contain the same key the later object in
896
+ * the arguments list will take precedence.
897
+ *
898
+ * Example:
899
+ *
900
+ * ```js
901
+ * var result = merge({foo: 123}, {foo: 456});
902
+ * console.log(result.foo); // outputs 456
903
+ * ```
904
+ *
905
+ * @param {Object} obj1 Object to merge
906
+ *
907
+ * @returns {Object} Result of all merge properties
908
+ */ function utils_merge() {
909
+ const { caseless } = isContextDefined(this) && this || {};
910
+ const result = {};
911
+ const assignValue = (val, key)=>{
912
+ const targetKey = caseless && findKey(result, key) || key;
913
+ if (utils_isPlainObject(result[targetKey]) && utils_isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
914
+ else if (utils_isPlainObject(val)) result[targetKey] = utils_merge({}, val);
915
+ else if (isArray(val)) result[targetKey] = val.slice();
916
+ else result[targetKey] = val;
917
+ };
918
+ for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
919
+ return result;
920
+ }
921
+ /**
922
+ * Extends object a by mutably adding to it the properties of object b.
923
+ *
924
+ * @param {Object} a The object to be extended
925
+ * @param {Object} b The object to copy properties from
926
+ * @param {Object} thisArg The object to bind function to
927
+ *
928
+ * @param {Boolean} [allOwnKeys]
929
+ * @returns {Object} The resulting value of object a
930
+ */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
931
+ forEach(b, (val, key)=>{
932
+ if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
933
+ else a[key] = val;
934
+ }, {
935
+ allOwnKeys
936
+ });
937
+ return a;
938
+ };
939
+ /**
940
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
941
+ *
942
+ * @param {string} content with BOM
943
+ *
944
+ * @returns {string} content value without BOM
945
+ */ const stripBOM = (content)=>{
946
+ if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
947
+ return content;
948
+ };
949
+ /**
950
+ * Inherit the prototype methods from one constructor into another
951
+ * @param {function} constructor
952
+ * @param {function} superConstructor
953
+ * @param {object} [props]
954
+ * @param {object} [descriptors]
955
+ *
956
+ * @returns {void}
957
+ */ const inherits = (constructor, superConstructor, props, descriptors)=>{
958
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
959
+ constructor.prototype.constructor = constructor;
960
+ Object.defineProperty(constructor, 'super', {
961
+ value: superConstructor.prototype
962
+ });
963
+ props && Object.assign(constructor.prototype, props);
964
+ };
965
+ /**
966
+ * Resolve object with deep prototype chain to a flat object
967
+ * @param {Object} sourceObj source object
968
+ * @param {Object} [destObj]
969
+ * @param {Function|Boolean} [filter]
970
+ * @param {Function} [propFilter]
971
+ *
972
+ * @returns {Object}
973
+ */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
974
+ let props;
975
+ let i;
976
+ let prop;
977
+ const merged = {};
978
+ destObj = destObj || {};
979
+ // eslint-disable-next-line no-eq-null,eqeqeq
980
+ if (null == sourceObj) return destObj;
981
+ do {
982
+ props = Object.getOwnPropertyNames(sourceObj);
983
+ i = props.length;
984
+ while(i-- > 0){
985
+ prop = props[i];
986
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
987
+ destObj[prop] = sourceObj[prop];
988
+ merged[prop] = true;
989
+ }
990
+ }
991
+ sourceObj = false !== filter && getPrototypeOf(sourceObj);
992
+ }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
993
+ return destObj;
994
+ };
995
+ /**
996
+ * Determines whether a string ends with the characters of a specified string
997
+ *
998
+ * @param {String} str
999
+ * @param {String} searchString
1000
+ * @param {Number} [position= 0]
1001
+ *
1002
+ * @returns {boolean}
1003
+ */ const endsWith = (str, searchString, position)=>{
1004
+ str = String(str);
1005
+ if (void 0 === position || position > str.length) position = str.length;
1006
+ position -= searchString.length;
1007
+ const lastIndex = str.indexOf(searchString, position);
1008
+ return -1 !== lastIndex && lastIndex === position;
1009
+ };
1010
+ /**
1011
+ * Returns new array from array like object or null if failed
1012
+ *
1013
+ * @param {*} [thing]
1014
+ *
1015
+ * @returns {?Array}
1016
+ */ const toArray = (thing)=>{
1017
+ if (!thing) return null;
1018
+ if (isArray(thing)) return thing;
1019
+ let i = thing.length;
1020
+ if (!isNumber(i)) return null;
1021
+ const arr = new Array(i);
1022
+ while(i-- > 0)arr[i] = thing[i];
1023
+ return arr;
1024
+ };
1025
+ /**
1026
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1027
+ * thing passed in is an instance of Uint8Array
1028
+ *
1029
+ * @param {TypedArray}
1030
+ *
1031
+ * @returns {Array}
1032
+ */ // eslint-disable-next-line func-names
1033
+ const isTypedArray = ((TypedArray)=>(thing)=>TypedArray && thing instanceof TypedArray)('undefined' != typeof Uint8Array && getPrototypeOf(Uint8Array));
1034
+ /**
1035
+ * For each entry in the object, call the function with the key and value.
1036
+ *
1037
+ * @param {Object<any, any>} obj - The object to iterate over.
1038
+ * @param {Function} fn - The function to call for each entry.
1039
+ *
1040
+ * @returns {void}
1041
+ */ const forEachEntry = (obj, fn)=>{
1042
+ const generator = obj && obj[Symbol.iterator];
1043
+ const iterator = generator.call(obj);
1044
+ let result;
1045
+ while((result = iterator.next()) && !result.done){
1046
+ const pair = result.value;
1047
+ fn.call(obj, pair[0], pair[1]);
1048
+ }
1049
+ };
1050
+ /**
1051
+ * It takes a regular expression and a string, and returns an array of all the matches
1052
+ *
1053
+ * @param {string} regExp - The regular expression to match against.
1054
+ * @param {string} str - The string to search.
1055
+ *
1056
+ * @returns {Array<boolean>}
1057
+ */ const matchAll = (regExp, str)=>{
1058
+ let matches;
1059
+ const arr = [];
1060
+ while(null !== (matches = regExp.exec(str)))arr.push(matches);
1061
+ return arr;
1062
+ };
1063
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
1064
+ const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
1065
+ return p1.toUpperCase() + p2;
1066
+ });
1067
+ /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
1068
+ /**
1069
+ * Determine if a value is a RegExp object
1070
+ *
1071
+ * @param {*} val The value to test
1072
+ *
1073
+ * @returns {boolean} True if value is a RegExp object, otherwise false
1074
+ */ const isRegExp = kindOfTest('RegExp');
1075
+ const reduceDescriptors = (obj, reducer)=>{
1076
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
1077
+ const reducedDescriptors = {};
1078
+ forEach(descriptors, (descriptor, name)=>{
1079
+ let ret;
1080
+ if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
1081
+ });
1082
+ Object.defineProperties(obj, reducedDescriptors);
1083
+ };
1084
+ /**
1085
+ * Makes all methods read-only
1086
+ * @param {Object} obj
1087
+ */ const freezeMethods = (obj)=>{
1088
+ reduceDescriptors(obj, (descriptor, name)=>{
1089
+ // skip restricted props in strict mode
1090
+ if (isFunction(obj) && -1 !== [
1091
+ 'arguments',
1092
+ 'caller',
1093
+ 'callee'
1094
+ ].indexOf(name)) return false;
1095
+ const value = obj[name];
1096
+ if (!isFunction(value)) return;
1097
+ descriptor.enumerable = false;
1098
+ if ('writable' in descriptor) {
1099
+ descriptor.writable = false;
1100
+ return;
1101
+ }
1102
+ if (!descriptor.set) descriptor.set = ()=>{
1103
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
1104
+ };
1105
+ });
1106
+ };
1107
+ const toObjectSet = (arrayOrString, delimiter)=>{
1108
+ const obj = {};
1109
+ const define = (arr)=>{
1110
+ arr.forEach((value)=>{
1111
+ obj[value] = true;
1112
+ });
1113
+ };
1114
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1115
+ return obj;
1116
+ };
1117
+ const noop = ()=>{};
1118
+ const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
1119
+ const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
1120
+ const DIGIT = '0123456789';
1121
+ const ALPHABET = {
1122
+ DIGIT,
1123
+ ALPHA,
1124
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
1125
+ };
1126
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
1127
+ let str = '';
1128
+ const { length } = alphabet;
1129
+ while(size--)str += alphabet[Math.random() * length | 0];
1130
+ return str;
1131
+ };
1132
+ /**
1133
+ * If the thing is a FormData object, return true, otherwise return false.
1134
+ *
1135
+ * @param {unknown} thing - The thing to check.
1136
+ *
1137
+ * @returns {boolean}
1138
+ */ function isSpecCompliantForm(thing) {
562
1139
  return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
563
1140
  }
564
1141
  const toJSONObject = (obj)=>{
@@ -609,7 +1186,7 @@ const asap = 'undefined' != typeof queueMicrotask ? queueMicrotask.bind(_global)
609
1186
  isNumber,
610
1187
  isBoolean,
611
1188
  isObject,
612
- isPlainObject,
1189
+ isPlainObject: utils_isPlainObject,
613
1190
  isReadableStream,
614
1191
  isRequest,
615
1192
  isResponse,
@@ -1807,7 +2384,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1807
2384
  * @param {Object} config2
1808
2385
  *
1809
2386
  * @returns {Object} New object resulting from merging config2 to config1
1810
- */ function mergeConfig(config1, config2) {
2387
+ */ function mergeConfig_mergeConfig(config1, config2) {
1811
2388
  // eslint-disable-next-line no-param-reassign
1812
2389
  config2 = config2 || {};
1813
2390
  const config = {};
@@ -1877,7 +2454,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1877
2454
  return config;
1878
2455
  }
1879
2456
  /* ESM default export */ const resolveConfig = (config)=>{
1880
- const newConfig = mergeConfig({}, config);
2457
+ const newConfig = mergeConfig_mergeConfig({}, config);
1881
2458
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1882
2459
  newConfig.headers = headers = AxiosHeaders.from(headers);
1883
2460
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2483,7 +3060,7 @@ const Axios_validators = helpers_validator.validators;
2483
3060
  config = config || {};
2484
3061
  config.url = configOrUrl;
2485
3062
  } else config = configOrUrl || {};
2486
- config = mergeConfig(this.defaults, config);
3063
+ config = mergeConfig_mergeConfig(this.defaults, config);
2487
3064
  const { transitional, paramsSerializer, headers } = config;
2488
3065
  if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2489
3066
  silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
@@ -2529,887 +3106,333 @@ const Axios_validators = helpers_validator.validators;
2529
3106
  });
2530
3107
  let promise;
2531
3108
  let i = 0;
2532
- let len;
2533
- if (!synchronousRequestInterceptors) {
2534
- const chain = [
2535
- dispatchRequest.bind(this),
2536
- void 0
2537
- ];
2538
- chain.unshift.apply(chain, requestInterceptorChain);
2539
- chain.push.apply(chain, responseInterceptorChain);
2540
- len = chain.length;
2541
- promise = Promise.resolve(config);
2542
- while(i < len)promise = promise.then(chain[i++], chain[i++]);
2543
- return promise;
2544
- }
2545
- len = requestInterceptorChain.length;
2546
- let newConfig = config;
2547
- i = 0;
2548
- while(i < len){
2549
- const onFulfilled = requestInterceptorChain[i++];
2550
- const onRejected = requestInterceptorChain[i++];
2551
- try {
2552
- newConfig = onFulfilled(newConfig);
2553
- } catch (error) {
2554
- onRejected.call(this, error);
2555
- break;
2556
- }
2557
- }
2558
- try {
2559
- promise = dispatchRequest.call(this, newConfig);
2560
- } catch (error) {
2561
- return Promise.reject(error);
2562
- }
2563
- i = 0;
2564
- len = responseInterceptorChain.length;
2565
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2566
- return promise;
2567
- }
2568
- getUri(config) {
2569
- config = mergeConfig(this.defaults, config);
2570
- const fullPath = buildFullPath(config.baseURL, config.url);
2571
- return buildURL(fullPath, config.params, config.paramsSerializer);
2572
- }
2573
- }
2574
- // Provide aliases for supported request methods
2575
- utils.forEach([
2576
- 'delete',
2577
- 'get',
2578
- 'head',
2579
- 'options'
2580
- ], function(method) {
2581
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2582
- return this.request(mergeConfig(config || {}, {
2583
- method,
2584
- url,
2585
- data: (config || {}).data
2586
- }));
2587
- };
2588
- });
2589
- utils.forEach([
2590
- 'post',
2591
- 'put',
2592
- 'patch'
2593
- ], function(method) {
2594
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2595
- return function(url, data, config) {
2596
- return this.request(mergeConfig(config || {}, {
2597
- method,
2598
- headers: isForm ? {
2599
- 'Content-Type': 'multipart/form-data'
2600
- } : {},
2601
- url,
2602
- data
2603
- }));
2604
- };
2605
- }
2606
- Axios_Axios.prototype[method] = generateHTTPMethod();
2607
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2608
- });
2609
- /* ESM default export */ const Axios = Axios_Axios;
2610
- /**
2611
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2612
- *
2613
- * @param {Function} executor The executor function.
2614
- *
2615
- * @returns {CancelToken}
2616
- */ class CancelToken_CancelToken {
2617
- constructor(executor){
2618
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2619
- let resolvePromise;
2620
- this.promise = new Promise(function(resolve) {
2621
- resolvePromise = resolve;
2622
- });
2623
- const token = this;
2624
- // eslint-disable-next-line func-names
2625
- this.promise.then((cancel)=>{
2626
- if (!token._listeners) return;
2627
- let i = token._listeners.length;
2628
- while(i-- > 0)token._listeners[i](cancel);
2629
- token._listeners = null;
2630
- });
2631
- // eslint-disable-next-line func-names
2632
- this.promise.then = (onfulfilled)=>{
2633
- let _resolve;
2634
- // eslint-disable-next-line func-names
2635
- const promise = new Promise((resolve)=>{
2636
- token.subscribe(resolve);
2637
- _resolve = resolve;
2638
- }).then(onfulfilled);
2639
- promise.cancel = function() {
2640
- token.unsubscribe(_resolve);
2641
- };
2642
- return promise;
2643
- };
2644
- executor(function(message, config, request) {
2645
- if (token.reason) // Cancellation has already been requested
2646
- return;
2647
- token.reason = new CanceledError(message, config, request);
2648
- resolvePromise(token.reason);
2649
- });
2650
- }
2651
- /**
2652
- * Throws a `CanceledError` if cancellation has been requested.
2653
- */ throwIfRequested() {
2654
- if (this.reason) throw this.reason;
2655
- }
2656
- /**
2657
- * Subscribe to the cancel signal
2658
- */ subscribe(listener) {
2659
- if (this.reason) {
2660
- listener(this.reason);
2661
- return;
2662
- }
2663
- if (this._listeners) this._listeners.push(listener);
2664
- else this._listeners = [
2665
- listener
2666
- ];
2667
- }
2668
- /**
2669
- * Unsubscribe from the cancel signal
2670
- */ unsubscribe(listener) {
2671
- if (!this._listeners) return;
2672
- const index = this._listeners.indexOf(listener);
2673
- if (-1 !== index) this._listeners.splice(index, 1);
2674
- }
2675
- toAbortSignal() {
2676
- const controller = new AbortController();
2677
- const abort = (err)=>{
2678
- controller.abort(err);
2679
- };
2680
- this.subscribe(abort);
2681
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2682
- return controller.signal;
2683
- }
2684
- /**
2685
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2686
- * cancels the `CancelToken`.
2687
- */ static source() {
2688
- let cancel;
2689
- const token = new CancelToken_CancelToken(function(c) {
2690
- cancel = c;
2691
- });
2692
- return {
2693
- token,
2694
- cancel
2695
- };
2696
- }
2697
- }
2698
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2699
- /**
2700
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2701
- *
2702
- * Common use case would be to use `Function.prototype.apply`.
2703
- *
2704
- * ```js
2705
- * function f(x, y, z) {}
2706
- * var args = [1, 2, 3];
2707
- * f.apply(null, args);
2708
- * ```
2709
- *
2710
- * With `spread` this example can be re-written.
2711
- *
2712
- * ```js
2713
- * spread(function(x, y, z) {})([1, 2, 3]);
2714
- * ```
2715
- *
2716
- * @param {Function} callback
2717
- *
2718
- * @returns {Function}
2719
- */ function spread(callback) {
2720
- return function(arr) {
2721
- return callback.apply(null, arr);
2722
- };
2723
- }
2724
- /**
2725
- * Determines whether the payload is an error thrown by Axios
2726
- *
2727
- * @param {*} payload The value to test
2728
- *
2729
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2730
- */ function isAxiosError(payload) {
2731
- return utils.isObject(payload) && true === payload.isAxiosError;
2732
- }
2733
- const HttpStatusCode = {
2734
- Continue: 100,
2735
- SwitchingProtocols: 101,
2736
- Processing: 102,
2737
- EarlyHints: 103,
2738
- Ok: 200,
2739
- Created: 201,
2740
- Accepted: 202,
2741
- NonAuthoritativeInformation: 203,
2742
- NoContent: 204,
2743
- ResetContent: 205,
2744
- PartialContent: 206,
2745
- MultiStatus: 207,
2746
- AlreadyReported: 208,
2747
- ImUsed: 226,
2748
- MultipleChoices: 300,
2749
- MovedPermanently: 301,
2750
- Found: 302,
2751
- SeeOther: 303,
2752
- NotModified: 304,
2753
- UseProxy: 305,
2754
- Unused: 306,
2755
- TemporaryRedirect: 307,
2756
- PermanentRedirect: 308,
2757
- BadRequest: 400,
2758
- Unauthorized: 401,
2759
- PaymentRequired: 402,
2760
- Forbidden: 403,
2761
- NotFound: 404,
2762
- MethodNotAllowed: 405,
2763
- NotAcceptable: 406,
2764
- ProxyAuthenticationRequired: 407,
2765
- RequestTimeout: 408,
2766
- Conflict: 409,
2767
- Gone: 410,
2768
- LengthRequired: 411,
2769
- PreconditionFailed: 412,
2770
- PayloadTooLarge: 413,
2771
- UriTooLong: 414,
2772
- UnsupportedMediaType: 415,
2773
- RangeNotSatisfiable: 416,
2774
- ExpectationFailed: 417,
2775
- ImATeapot: 418,
2776
- MisdirectedRequest: 421,
2777
- UnprocessableEntity: 422,
2778
- Locked: 423,
2779
- FailedDependency: 424,
2780
- TooEarly: 425,
2781
- UpgradeRequired: 426,
2782
- PreconditionRequired: 428,
2783
- TooManyRequests: 429,
2784
- RequestHeaderFieldsTooLarge: 431,
2785
- UnavailableForLegalReasons: 451,
2786
- InternalServerError: 500,
2787
- NotImplemented: 501,
2788
- BadGateway: 502,
2789
- ServiceUnavailable: 503,
2790
- GatewayTimeout: 504,
2791
- HttpVersionNotSupported: 505,
2792
- VariantAlsoNegotiates: 506,
2793
- InsufficientStorage: 507,
2794
- LoopDetected: 508,
2795
- NotExtended: 510,
2796
- NetworkAuthenticationRequired: 511
2797
- };
2798
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2799
- HttpStatusCode[value] = key;
2800
- });
2801
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2802
- /**
2803
- * Create an instance of Axios
2804
- *
2805
- * @param {Object} defaultConfig The default config for the instance
2806
- *
2807
- * @returns {Axios} A new instance of Axios
2808
- */ function createInstance(defaultConfig) {
2809
- const context = new Axios(defaultConfig);
2810
- const instance = bind(Axios.prototype.request, context);
2811
- // Copy axios.prototype to instance
2812
- utils.extend(instance, Axios.prototype, context, {
2813
- allOwnKeys: true
2814
- });
2815
- // Copy context to instance
2816
- utils.extend(instance, context, null, {
2817
- allOwnKeys: true
2818
- });
2819
- // Factory for creating new instances
2820
- instance.create = function(instanceConfig) {
2821
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2822
- };
2823
- return instance;
2824
- }
2825
- // Create the default instance to be exported
2826
- const axios = createInstance(defaults);
2827
- // Expose Axios class to allow class inheritance
2828
- axios.Axios = Axios;
2829
- // Expose Cancel & CancelToken
2830
- axios.CanceledError = CanceledError;
2831
- axios.CancelToken = CancelToken;
2832
- axios.isCancel = isCancel;
2833
- axios.VERSION = VERSION;
2834
- axios.toFormData = toFormData;
2835
- // Expose AxiosError class
2836
- axios.AxiosError = core_AxiosError;
2837
- // alias for CanceledError for backward compatibility
2838
- axios.Cancel = axios.CanceledError;
2839
- // Expose all/spread
2840
- axios.all = function(promises) {
2841
- return Promise.all(promises);
2842
- };
2843
- axios.spread = spread;
2844
- // Expose isAxiosError
2845
- axios.isAxiosError = isAxiosError;
2846
- // Expose mergeConfig
2847
- axios.mergeConfig = mergeConfig;
2848
- axios.AxiosHeaders = AxiosHeaders;
2849
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2850
- axios.getAdapter = adapters_adapters.getAdapter;
2851
- axios.HttpStatusCode = helpers_HttpStatusCode;
2852
- axios.default = axios;
2853
- // this module should only have a default export
2854
- /* ESM default export */ const lib_axios = axios;
2855
- // This module is intended to unwrap Axios default export as named.
2856
- // Keep top-level export same with static properties
2857
- // so that it can keep same with es module or cjs
2858
- 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;
2859
- // EXTERNAL MODULE: os (ignored)
2860
- var os_ignored_ = __webpack_require__("?9caf");
2861
- // EXTERNAL MODULE: crypto (ignored)
2862
- __webpack_require__("?e272");
2863
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2864
- __webpack_require__("?5742");
2865
- class APIResource {
2866
- constructor(client){
2867
- this._client = client;
2868
- }
2869
- }
2870
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2871
- /**
2872
- * Create a new agent. | 调用接口创建一个新的智能体。
2873
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2874
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2875
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2876
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2877
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2878
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2879
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2880
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2881
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2882
- * @returns Information about the created bot. | 创建的 Bot 信息。
2883
- */ async create(params, options) {
2884
- const apiUrl = '/v1/bot/create';
2885
- const result = await this._client.post(apiUrl, params, false, options);
2886
- return result.data;
2887
- }
2888
- /**
2889
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2890
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2891
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2892
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2893
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2894
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2895
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2896
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2897
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2898
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2899
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2900
- * @returns Undefined | 无返回值
2901
- */ async update(params, options) {
2902
- const apiUrl = '/v1/bot/update';
2903
- const result = await this._client.post(apiUrl, params, false, options);
2904
- return result.data;
2905
- }
2906
- /**
2907
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2908
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2909
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2910
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2911
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2912
- * @param params.page_size - Optional Pagination size. | 分页大小。
2913
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2914
- * @returns List of published bots. | 已发布的 Bot 列表。
2915
- */ async list(params, options) {
2916
- const apiUrl = '/v1/space/published_bots_list';
2917
- const result = await this._client.get(apiUrl, params, false, options);
2918
- return result.data;
2919
- }
2920
- /**
2921
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2922
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2923
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2924
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2925
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2926
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2927
- * @returns Undefined | 无返回值
2928
- */ async publish(params, options) {
2929
- const apiUrl = '/v1/bot/publish';
2930
- const result = await this._client.post(apiUrl, params, false, options);
2931
- return result.data;
2932
- }
2933
- /**
2934
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2935
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2936
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2937
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2938
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2939
- * @returns Information about the bot. | Bot 的配置信息。
2940
- */ async retrieve(params, options) {
2941
- const apiUrl = '/v1/bot/get_online_info';
2942
- const result = await this._client.get(apiUrl, params, false, options);
2943
- return result.data;
2944
- }
2945
- }
2946
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2947
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2948
- try {
2949
- return JSON.parse(jsonString);
2950
- } catch (error) {
2951
- return defaultValue;
2952
- }
2953
- }
2954
- function sleep(ms) {
2955
- return new Promise((resolve)=>{
2956
- setTimeout(resolve, ms);
2957
- });
2958
- }
2959
- function isBrowser() {
2960
- return 'undefined' != typeof window;
2961
- }
2962
- function esm_isPlainObject(obj) {
2963
- if ('object' != typeof obj || null === obj) return false;
2964
- const proto = Object.getPrototypeOf(obj);
2965
- if (null === proto) return true;
2966
- let baseProto = proto;
2967
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2968
- return proto === baseProto;
2969
- }
2970
- function esm_mergeConfig() {
2971
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2972
- return objects.reduce((result, obj)=>{
2973
- if (void 0 === obj) return result || {};
2974
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2975
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2976
- else result[key] = obj[key];
2977
- }
2978
- return result;
2979
- }, {});
2980
- }
2981
- function isPersonalAccessToken(token) {
2982
- return null == token ? void 0 : token.startsWith('pat_');
2983
- }
2984
- /* eslint-disable max-params */ class CozeError extends Error {
2985
- }
2986
- class APIError extends CozeError {
2987
- static makeMessage(status, errorBody, message, headers) {
2988
- if (!errorBody && message) return message;
2989
- if (errorBody) {
2990
- const list = [];
2991
- const { code, msg, error } = errorBody;
2992
- if (code) list.push(`code: ${code}`);
2993
- if (msg) list.push(`msg: ${msg}`);
2994
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
2995
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
2996
- if (logId) list.push(`logid: ${logId}`);
2997
- const help_doc = null == error ? void 0 : error.help_doc;
2998
- if (help_doc) list.push(`help doc: ${help_doc}`);
2999
- return list.join(', ');
3000
- }
3001
- if (status) return `http status code: ${status} (no body)`;
3002
- return '(no status code or body)';
3003
- }
3004
- static generate(status, errorResponse, message, headers) {
3005
- if (!status) return new APIConnectionError({
3006
- cause: castToError(errorResponse)
3007
- });
3008
- const error = errorResponse;
3009
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
3010
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3011
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3012
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3013
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3014
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3015
- if (408 === status) return new TimeoutError(status, error, message, headers);
3016
- if (502 === status) return new GatewayError(status, error, message, headers);
3017
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3018
- return new APIError(status, error, message, headers);
3019
- }
3020
- constructor(status, error, message, headers){
3021
- var _error_error, _error_error1;
3022
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3023
- this.status = status;
3024
- this.headers = headers;
3025
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3026
- // this.error = error;
3027
- this.code = null == error ? void 0 : error.code;
3028
- this.msg = null == error ? void 0 : error.msg;
3029
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3030
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3031
- this.rawError = error;
3032
- }
3033
- }
3034
- class APIConnectionError extends APIError {
3035
- constructor({ message, cause }){
3036
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3037
- // if (cause) {
3038
- // this.cause = cause;
3039
- // }
3040
- }
3041
- }
3042
- class APIUserAbortError extends APIError {
3043
- constructor(message){
3044
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3045
- }
3046
- }
3047
- class BadRequestError extends APIError {
3048
- constructor(...args){
3049
- super(...args), this.name = 'BadRequestError', this.status = 400;
3050
- }
3051
- }
3052
- class AuthenticationError extends APIError {
3053
- constructor(...args){
3054
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3055
- }
3056
- }
3057
- class PermissionDeniedError extends APIError {
3058
- constructor(...args){
3059
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3060
- }
3061
- }
3062
- class NotFoundError extends APIError {
3063
- constructor(...args){
3064
- super(...args), this.name = 'NotFoundError', this.status = 404;
3065
- }
3066
- }
3067
- class TimeoutError extends APIError {
3068
- constructor(...args){
3069
- super(...args), this.name = 'TimeoutError', this.status = 408;
3070
- }
3071
- }
3072
- class RateLimitError extends APIError {
3073
- constructor(...args){
3074
- super(...args), this.name = 'RateLimitError', this.status = 429;
3075
- }
3076
- }
3077
- class InternalServerError extends APIError {
3078
- constructor(...args){
3079
- super(...args), this.name = 'InternalServerError', this.status = 500;
3080
- }
3081
- }
3082
- class GatewayError extends APIError {
3083
- constructor(...args){
3084
- super(...args), this.name = 'GatewayError', this.status = 502;
3085
- }
3086
- }
3087
- const castToError = (err)=>{
3088
- if (err instanceof Error) return err;
3089
- return new Error(err);
3090
- };
3091
- class Messages extends APIResource {
3092
- /**
3093
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3094
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3095
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3096
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3097
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3098
- * @returns An array of chat messages. | 对话消息数组。
3099
- */ async list(conversation_id, chat_id, options) {
3100
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3101
- const result = await this._client.get(apiUrl, void 0, false, options);
3102
- return result.data;
3103
- }
3104
- }
3105
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3106
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3107
- ...i,
3108
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3109
- }));
3110
- class Chat extends APIResource {
3111
- /**
3112
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3113
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3114
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3115
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3116
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3117
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3118
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3119
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3120
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3121
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3122
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3123
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3124
- * @returns The data of the created chat. | 创建的对话数据。
3125
- */ async create(params, options) {
3126
- if (!params.user_id) params.user_id = uuid();
3127
- const { conversation_id, ...rest } = params;
3128
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3129
- const payload = {
3130
- ...rest,
3131
- additional_messages: handleAdditionalMessages(params.additional_messages),
3132
- stream: false
3133
- };
3134
- const result = await this._client.post(apiUrl, payload, false, options);
3135
- return result.data;
3136
- }
3137
- /**
3138
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3139
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3140
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3141
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3142
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3143
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3144
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3145
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3146
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3147
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3148
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3149
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3150
- * @returns
3151
- */ async createAndPoll(params, options) {
3152
- if (!params.user_id) params.user_id = uuid();
3153
- const { conversation_id, ...rest } = params;
3154
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3155
- const payload = {
3156
- ...rest,
3157
- additional_messages: handleAdditionalMessages(params.additional_messages),
3158
- stream: false
3159
- };
3160
- const result = await this._client.post(apiUrl, payload, false, options);
3161
- const chatId = result.data.id;
3162
- const conversationId = result.data.conversation_id;
3163
- let chat;
3164
- while(true){
3165
- await sleep(100);
3166
- chat = await this.retrieve(conversationId, chatId);
3167
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3168
- }
3169
- const messageList = await this.messages.list(conversationId, chatId);
3170
- return {
3171
- chat,
3172
- messages: messageList
3173
- };
3174
- }
3175
- /**
3176
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3177
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3178
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3179
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3180
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3181
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3182
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3183
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3184
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3185
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3186
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3187
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3188
- * @returns A stream of chat data. | 对话数据流。
3189
- */ async *stream(params, options) {
3190
- if (!params.user_id) params.user_id = uuid();
3191
- const { conversation_id, ...rest } = params;
3192
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3193
- const payload = {
3194
- ...rest,
3195
- additional_messages: handleAdditionalMessages(params.additional_messages),
3196
- stream: true
3197
- };
3198
- const result = await this._client.post(apiUrl, payload, true, options);
3199
- for await (const message of result)if ("done" === message.event) {
3200
- const ret = {
3201
- event: message.event,
3202
- data: '[DONE]'
3203
- };
3204
- yield ret;
3205
- } else try {
3206
- const ret = {
3207
- event: message.event,
3208
- data: JSON.parse(message.data)
3209
- };
3210
- yield ret;
3211
- } catch (error) {
3212
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3213
- }
3214
- }
3215
- /**
3216
- * Get the detailed information of the chat. | 查看对话的详细信息。
3217
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3218
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3219
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3220
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3221
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3222
- */ async retrieve(conversation_id, chat_id, options) {
3223
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3224
- const result = await this._client.post(apiUrl, void 0, false, options);
3225
- return result.data;
3226
- }
3227
- /**
3228
- * Cancel a chat session. | 取消对话会话。
3229
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3230
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3231
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3232
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3233
- * @returns The data of the canceled chat. | 取消的对话数据。
3234
- */ async cancel(conversation_id, chat_id, options) {
3235
- const apiUrl = '/v3/chat/cancel';
3236
- const payload = {
3237
- conversation_id,
3238
- chat_id
3239
- };
3240
- const result = await this._client.post(apiUrl, payload, false, options);
3241
- return result.data;
3242
- }
3243
- /**
3244
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3245
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3246
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3247
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3248
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3249
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3250
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3251
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3252
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3253
- */ async *submitToolOutputs(params, options) {
3254
- const { conversation_id, chat_id, ...rest } = params;
3255
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3256
- const payload = {
3257
- ...rest
3258
- };
3259
- if (false === params.stream) {
3260
- const response = await this._client.post(apiUrl, payload, false, options);
3261
- return response.data;
3262
- }
3263
- {
3264
- const result = await this._client.post(apiUrl, payload, true, options);
3265
- for await (const message of result)if ("done" === message.event) {
3266
- const ret = {
3267
- event: message.event,
3268
- data: '[DONE]'
3269
- };
3270
- yield ret;
3271
- } else try {
3272
- const ret = {
3273
- event: message.event,
3274
- data: JSON.parse(message.data)
3275
- };
3276
- yield ret;
3109
+ let len;
3110
+ if (!synchronousRequestInterceptors) {
3111
+ const chain = [
3112
+ dispatchRequest.bind(this),
3113
+ void 0
3114
+ ];
3115
+ chain.unshift.apply(chain, requestInterceptorChain);
3116
+ chain.push.apply(chain, responseInterceptorChain);
3117
+ len = chain.length;
3118
+ promise = Promise.resolve(config);
3119
+ while(i < len)promise = promise.then(chain[i++], chain[i++]);
3120
+ return promise;
3121
+ }
3122
+ len = requestInterceptorChain.length;
3123
+ let newConfig = config;
3124
+ i = 0;
3125
+ while(i < len){
3126
+ const onFulfilled = requestInterceptorChain[i++];
3127
+ const onRejected = requestInterceptorChain[i++];
3128
+ try {
3129
+ newConfig = onFulfilled(newConfig);
3277
3130
  } catch (error) {
3278
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3131
+ onRejected.call(this, error);
3132
+ break;
3279
3133
  }
3280
3134
  }
3135
+ try {
3136
+ promise = dispatchRequest.call(this, newConfig);
3137
+ } catch (error) {
3138
+ return Promise.reject(error);
3139
+ }
3140
+ i = 0;
3141
+ len = responseInterceptorChain.length;
3142
+ while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3143
+ return promise;
3281
3144
  }
3282
- constructor(...args){
3283
- super(...args), this.messages = new Messages(this._client);
3145
+ getUri(config) {
3146
+ config = mergeConfig_mergeConfig(this.defaults, config);
3147
+ const fullPath = buildFullPath(config.baseURL, config.url);
3148
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3284
3149
  }
3285
3150
  }
3286
- class messages_Messages extends APIResource {
3287
- /**
3288
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3289
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3290
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3291
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3292
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3293
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3294
- * @param params.content - Required The content of the message. | 消息的内容。
3295
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3296
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3297
- * @returns Information about the new message. | 消息详情。
3298
- */ async create(conversation_id, params, options) {
3299
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3300
- const response = await this._client.post(apiUrl, params, false, options);
3301
- return response.data;
3302
- }
3303
- /**
3304
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3305
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3306
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3307
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3308
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3309
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3310
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3311
- * @param params.content - Optional The content of the message. | 消息的内容。
3312
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3313
- * @returns Information about the modified message. | 消息详情。
3314
- */ // eslint-disable-next-line max-params
3315
- async update(conversation_id, message_id, params, options) {
3316
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3317
- const response = await this._client.post(apiUrl, params, false, options);
3318
- return response.message;
3319
- }
3320
- /**
3321
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3322
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3323
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3324
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3325
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3326
- * @returns Information about the message. | 消息详情。
3327
- */ async retrieve(conversation_id, message_id, options) {
3328
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3329
- const response = await this._client.get(apiUrl, null, false, options);
3330
- return response.data;
3151
+ // Provide aliases for supported request methods
3152
+ utils.forEach([
3153
+ 'delete',
3154
+ 'get',
3155
+ 'head',
3156
+ 'options'
3157
+ ], function(method) {
3158
+ /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
3159
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3160
+ method,
3161
+ url,
3162
+ data: (config || {}).data
3163
+ }));
3164
+ };
3165
+ });
3166
+ utils.forEach([
3167
+ 'post',
3168
+ 'put',
3169
+ 'patch'
3170
+ ], function(method) {
3171
+ /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
3172
+ return function(url, data, config) {
3173
+ return this.request(mergeConfig_mergeConfig(config || {}, {
3174
+ method,
3175
+ headers: isForm ? {
3176
+ 'Content-Type': 'multipart/form-data'
3177
+ } : {},
3178
+ url,
3179
+ data
3180
+ }));
3181
+ };
3331
3182
  }
3332
- /**
3333
- * List messages in a conversation. | 列出会话中的消息。
3334
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3335
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3336
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3337
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3338
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3339
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3340
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3341
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3342
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3343
- * @returns A list of messages. | 消息列表。
3344
- */ async list(conversation_id, params, options) {
3345
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3346
- const response = await this._client.post(apiUrl, params, false, options);
3347
- return response;
3183
+ Axios_Axios.prototype[method] = generateHTTPMethod();
3184
+ Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3185
+ });
3186
+ /* ESM default export */ const Axios = Axios_Axios;
3187
+ /**
3188
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3189
+ *
3190
+ * @param {Function} executor The executor function.
3191
+ *
3192
+ * @returns {CancelToken}
3193
+ */ class CancelToken_CancelToken {
3194
+ constructor(executor){
3195
+ if ('function' != typeof executor) throw new TypeError('executor must be a function.');
3196
+ let resolvePromise;
3197
+ this.promise = new Promise(function(resolve) {
3198
+ resolvePromise = resolve;
3199
+ });
3200
+ const token = this;
3201
+ // eslint-disable-next-line func-names
3202
+ this.promise.then((cancel)=>{
3203
+ if (!token._listeners) return;
3204
+ let i = token._listeners.length;
3205
+ while(i-- > 0)token._listeners[i](cancel);
3206
+ token._listeners = null;
3207
+ });
3208
+ // eslint-disable-next-line func-names
3209
+ this.promise.then = (onfulfilled)=>{
3210
+ let _resolve;
3211
+ // eslint-disable-next-line func-names
3212
+ const promise = new Promise((resolve)=>{
3213
+ token.subscribe(resolve);
3214
+ _resolve = resolve;
3215
+ }).then(onfulfilled);
3216
+ promise.cancel = function() {
3217
+ token.unsubscribe(_resolve);
3218
+ };
3219
+ return promise;
3220
+ };
3221
+ executor(function(message, config, request) {
3222
+ if (token.reason) // Cancellation has already been requested
3223
+ return;
3224
+ token.reason = new CanceledError(message, config, request);
3225
+ resolvePromise(token.reason);
3226
+ });
3348
3227
  }
3349
3228
  /**
3350
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3351
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3352
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3353
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3354
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3355
- * @returns Details of the deleted message. | 已删除的消息详情。
3356
- */ async delete(conversation_id, message_id, options) {
3357
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3358
- const response = await this._client.post(apiUrl, void 0, false, options);
3359
- return response.data;
3229
+ * Throws a `CanceledError` if cancellation has been requested.
3230
+ */ throwIfRequested() {
3231
+ if (this.reason) throw this.reason;
3360
3232
  }
3361
- }
3362
- class Conversations extends APIResource {
3363
3233
  /**
3364
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3365
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3366
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3367
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3368
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3369
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3370
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3371
- * @returns Information about the created conversation. | 会话的基础信息。
3372
- */ async create(params, options) {
3373
- const apiUrl = '/v1/conversation/create';
3374
- const response = await this._client.post(apiUrl, params, false, options);
3375
- return response.data;
3234
+ * Subscribe to the cancel signal
3235
+ */ subscribe(listener) {
3236
+ if (this.reason) {
3237
+ listener(this.reason);
3238
+ return;
3239
+ }
3240
+ if (this._listeners) this._listeners.push(listener);
3241
+ else this._listeners = [
3242
+ listener
3243
+ ];
3376
3244
  }
3377
3245
  /**
3378
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3379
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3380
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3381
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3382
- * @returns Information about the conversation. | 会话的基础信息。
3383
- */ async retrieve(conversation_id, options) {
3384
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3385
- const response = await this._client.get(apiUrl, null, false, options);
3386
- return response.data;
3246
+ * Unsubscribe from the cancel signal
3247
+ */ unsubscribe(listener) {
3248
+ if (!this._listeners) return;
3249
+ const index = this._listeners.indexOf(listener);
3250
+ if (-1 !== index) this._listeners.splice(index, 1);
3387
3251
  }
3388
- /**
3389
- * List all conversations. | 列出 Bot 下所有会话。
3390
- * @param params
3391
- * @param params.bot_id - Required Bot ID. | Bot ID。
3392
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3393
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3394
- * @returns Information about the conversations. | 会话的信息。
3395
- */ async list(params, options) {
3396
- const apiUrl = '/v1/conversations';
3397
- const response = await this._client.get(apiUrl, params, false, options);
3398
- return response.data;
3252
+ toAbortSignal() {
3253
+ const controller = new AbortController();
3254
+ const abort = (err)=>{
3255
+ controller.abort(err);
3256
+ };
3257
+ this.subscribe(abort);
3258
+ controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
3259
+ return controller.signal;
3399
3260
  }
3400
3261
  /**
3401
- * Clear a conversation. | 清空会话。
3402
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3403
- * @returns Information about the conversation session. | 会话的会话 ID。
3404
- */ async clear(conversation_id, options) {
3405
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3406
- const response = await this._client.post(apiUrl, null, false, options);
3407
- return response.data;
3408
- }
3409
- constructor(...args){
3410
- super(...args), this.messages = new messages_Messages(this._client);
3262
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3263
+ * cancels the `CancelToken`.
3264
+ */ static source() {
3265
+ let cancel;
3266
+ const token = new CancelToken_CancelToken(function(c) {
3267
+ cancel = c;
3268
+ });
3269
+ return {
3270
+ token,
3271
+ cancel
3272
+ };
3411
3273
  }
3412
3274
  }
3275
+ /* ESM default export */ const CancelToken = CancelToken_CancelToken;
3276
+ /**
3277
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3278
+ *
3279
+ * Common use case would be to use `Function.prototype.apply`.
3280
+ *
3281
+ * ```js
3282
+ * function f(x, y, z) {}
3283
+ * var args = [1, 2, 3];
3284
+ * f.apply(null, args);
3285
+ * ```
3286
+ *
3287
+ * With `spread` this example can be re-written.
3288
+ *
3289
+ * ```js
3290
+ * spread(function(x, y, z) {})([1, 2, 3]);
3291
+ * ```
3292
+ *
3293
+ * @param {Function} callback
3294
+ *
3295
+ * @returns {Function}
3296
+ */ function spread(callback) {
3297
+ return function(arr) {
3298
+ return callback.apply(null, arr);
3299
+ };
3300
+ }
3301
+ /**
3302
+ * Determines whether the payload is an error thrown by Axios
3303
+ *
3304
+ * @param {*} payload The value to test
3305
+ *
3306
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3307
+ */ function isAxiosError(payload) {
3308
+ return utils.isObject(payload) && true === payload.isAxiosError;
3309
+ }
3310
+ const HttpStatusCode = {
3311
+ Continue: 100,
3312
+ SwitchingProtocols: 101,
3313
+ Processing: 102,
3314
+ EarlyHints: 103,
3315
+ Ok: 200,
3316
+ Created: 201,
3317
+ Accepted: 202,
3318
+ NonAuthoritativeInformation: 203,
3319
+ NoContent: 204,
3320
+ ResetContent: 205,
3321
+ PartialContent: 206,
3322
+ MultiStatus: 207,
3323
+ AlreadyReported: 208,
3324
+ ImUsed: 226,
3325
+ MultipleChoices: 300,
3326
+ MovedPermanently: 301,
3327
+ Found: 302,
3328
+ SeeOther: 303,
3329
+ NotModified: 304,
3330
+ UseProxy: 305,
3331
+ Unused: 306,
3332
+ TemporaryRedirect: 307,
3333
+ PermanentRedirect: 308,
3334
+ BadRequest: 400,
3335
+ Unauthorized: 401,
3336
+ PaymentRequired: 402,
3337
+ Forbidden: 403,
3338
+ NotFound: 404,
3339
+ MethodNotAllowed: 405,
3340
+ NotAcceptable: 406,
3341
+ ProxyAuthenticationRequired: 407,
3342
+ RequestTimeout: 408,
3343
+ Conflict: 409,
3344
+ Gone: 410,
3345
+ LengthRequired: 411,
3346
+ PreconditionFailed: 412,
3347
+ PayloadTooLarge: 413,
3348
+ UriTooLong: 414,
3349
+ UnsupportedMediaType: 415,
3350
+ RangeNotSatisfiable: 416,
3351
+ ExpectationFailed: 417,
3352
+ ImATeapot: 418,
3353
+ MisdirectedRequest: 421,
3354
+ UnprocessableEntity: 422,
3355
+ Locked: 423,
3356
+ FailedDependency: 424,
3357
+ TooEarly: 425,
3358
+ UpgradeRequired: 426,
3359
+ PreconditionRequired: 428,
3360
+ TooManyRequests: 429,
3361
+ RequestHeaderFieldsTooLarge: 431,
3362
+ UnavailableForLegalReasons: 451,
3363
+ InternalServerError: 500,
3364
+ NotImplemented: 501,
3365
+ BadGateway: 502,
3366
+ ServiceUnavailable: 503,
3367
+ GatewayTimeout: 504,
3368
+ HttpVersionNotSupported: 505,
3369
+ VariantAlsoNegotiates: 506,
3370
+ InsufficientStorage: 507,
3371
+ LoopDetected: 508,
3372
+ NotExtended: 510,
3373
+ NetworkAuthenticationRequired: 511
3374
+ };
3375
+ Object.entries(HttpStatusCode).forEach(([key, value])=>{
3376
+ HttpStatusCode[value] = key;
3377
+ });
3378
+ /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
3379
+ /**
3380
+ * Create an instance of Axios
3381
+ *
3382
+ * @param {Object} defaultConfig The default config for the instance
3383
+ *
3384
+ * @returns {Axios} A new instance of Axios
3385
+ */ function createInstance(defaultConfig) {
3386
+ const context = new Axios(defaultConfig);
3387
+ const instance = bind(Axios.prototype.request, context);
3388
+ // Copy axios.prototype to instance
3389
+ utils.extend(instance, Axios.prototype, context, {
3390
+ allOwnKeys: true
3391
+ });
3392
+ // Copy context to instance
3393
+ utils.extend(instance, context, null, {
3394
+ allOwnKeys: true
3395
+ });
3396
+ // Factory for creating new instances
3397
+ instance.create = function(instanceConfig) {
3398
+ return createInstance(mergeConfig_mergeConfig(defaultConfig, instanceConfig));
3399
+ };
3400
+ return instance;
3401
+ }
3402
+ // Create the default instance to be exported
3403
+ const axios = createInstance(defaults);
3404
+ // Expose Axios class to allow class inheritance
3405
+ axios.Axios = Axios;
3406
+ // Expose Cancel & CancelToken
3407
+ axios.CanceledError = CanceledError;
3408
+ axios.CancelToken = CancelToken;
3409
+ axios.isCancel = isCancel;
3410
+ axios.VERSION = VERSION;
3411
+ axios.toFormData = toFormData;
3412
+ // Expose AxiosError class
3413
+ axios.AxiosError = core_AxiosError;
3414
+ // alias for CanceledError for backward compatibility
3415
+ axios.Cancel = axios.CanceledError;
3416
+ // Expose all/spread
3417
+ axios.all = function(promises) {
3418
+ return Promise.all(promises);
3419
+ };
3420
+ axios.spread = spread;
3421
+ // Expose isAxiosError
3422
+ axios.isAxiosError = isAxiosError;
3423
+ // Expose mergeConfig
3424
+ axios.mergeConfig = mergeConfig_mergeConfig;
3425
+ axios.AxiosHeaders = AxiosHeaders;
3426
+ axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3427
+ axios.getAdapter = adapters_adapters.getAdapter;
3428
+ axios.HttpStatusCode = helpers_HttpStatusCode;
3429
+ axios.default = axios;
3430
+ // this module should only have a default export
3431
+ /* ESM default export */ const lib_axios = axios;
3432
+ // This module is intended to unwrap Axios default export as named.
3433
+ // Keep top-level export same with static properties
3434
+ // so that it can keep same with es module or cjs
3435
+ 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;
3413
3436
  class Files extends APIResource {
3414
3437
  /**
3415
3438
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3497,9 +3520,46 @@ class WorkflowEvent {
3497
3520
  this.data = data;
3498
3521
  }
3499
3522
  }
3523
+ class WorkflowChat extends APIResource {
3524
+ /**
3525
+ * Execute a chat workflow. | 执行对话流
3526
+ * @docs en: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=en
3527
+ * @docs zh: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=zh
3528
+ * @param params.workflow_id - Required The ID of the workflow to chat with. | 必选 要对话的工作流 ID。
3529
+ * @param params.additional_messages - Required Array of messages for the chat. | 必选 对话的消息数组。
3530
+ * @param params.parameters - Required Parameters for the workflow execution. | 必选 工作流执行的参数。
3531
+ * @param params.app_id - Optional The ID of the app. | 可选 应用 ID。
3532
+ * @param params.bot_id - Optional The ID of the bot. | 可选 Bot ID。
3533
+ * @param params.conversation_id - Optional The ID of the conversation. | 可选 会话 ID。
3534
+ * @param params.ext - Optional Additional information for the chat. | 可选 对话的附加信息。
3535
+ * @returns AsyncGenerator<StreamChatData> | 对话数据流
3536
+ */ async *stream(params, options) {
3537
+ const apiUrl = '/v1/workflows/chat';
3538
+ const payload = {
3539
+ ...params,
3540
+ additional_messages: handleAdditionalMessages(params.additional_messages)
3541
+ };
3542
+ const result = await this._client.post(apiUrl, payload, true, options);
3543
+ for await (const message of result)if (message.event === chat_ChatEventType.DONE) {
3544
+ const ret = {
3545
+ event: message.event,
3546
+ data: '[DONE]'
3547
+ };
3548
+ yield ret;
3549
+ } else try {
3550
+ const ret = {
3551
+ event: message.event,
3552
+ data: JSON.parse(message.data)
3553
+ };
3554
+ yield ret;
3555
+ } catch (error) {
3556
+ throw new CozeError(`Could not parse message into JSON:${message.data}`);
3557
+ }
3558
+ }
3559
+ }
3500
3560
  class Workflows extends APIResource {
3501
3561
  constructor(...args){
3502
- super(...args), this.runs = new Runs(this._client);
3562
+ super(...args), this.runs = new Runs(this._client), this.chat = new WorkflowChat(this._client);
3503
3563
  }
3504
3564
  }
3505
3565
  class WorkSpaces extends APIResource {
@@ -3523,6 +3583,8 @@ const documents_headers = {
3523
3583
  };
3524
3584
  class Documents extends APIResource {
3525
3585
  /**
3586
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.list' instead.
3587
+ *
3526
3588
  * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images.
3527
3589
  * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。
3528
3590
  * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en
@@ -3533,12 +3595,14 @@ class Documents extends APIResource {
3533
3595
  * @returns ListDocumentData | 知识库文件列表
3534
3596
  */ list(params, options) {
3535
3597
  const apiUrl = '/open_api/knowledge/document/list';
3536
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3598
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3537
3599
  headers: documents_headers
3538
3600
  }));
3539
3601
  return response;
3540
3602
  }
3541
3603
  /**
3604
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.create' instead.
3605
+ *
3542
3606
  * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。
3543
3607
  * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en
3544
3608
  * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh
@@ -3549,12 +3613,14 @@ class Documents extends APIResource {
3549
3613
  * @returns DocumentInfo[] | 已上传文件的基本信息
3550
3614
  */ async create(params, options) {
3551
3615
  const apiUrl = '/open_api/knowledge/document/create';
3552
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3616
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3553
3617
  headers: documents_headers
3554
3618
  }));
3555
3619
  return response.document_infos;
3556
3620
  }
3557
3621
  /**
3622
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.delete' instead.
3623
+ *
3558
3624
  * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion.
3559
3625
  * | 删除知识库中的文本、图像、表格等文件,支持批量删除。
3560
3626
  * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en
@@ -3563,11 +3629,13 @@ class Documents extends APIResource {
3563
3629
  * @returns void | 无返回
3564
3630
  */ async delete(params, options) {
3565
3631
  const apiUrl = '/open_api/knowledge/document/delete';
3566
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3632
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3567
3633
  headers: documents_headers
3568
3634
  }));
3569
3635
  }
3570
3636
  /**
3637
+ * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.update' instead.
3638
+ *
3571
3639
  * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。
3572
3640
  * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en
3573
3641
  * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh
@@ -3577,14 +3645,86 @@ class Documents extends APIResource {
3577
3645
  * @returns void | 无返回
3578
3646
  */ async update(params, options) {
3579
3647
  const apiUrl = '/open_api/knowledge/document/update';
3580
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3648
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3581
3649
  headers: documents_headers
3582
3650
  }));
3583
3651
  }
3584
3652
  }
3585
3653
  class Knowledge extends APIResource {
3586
3654
  constructor(...args){
3587
- super(...args), this.documents = new Documents(this._client);
3655
+ super(...args), /**
3656
+ * @deprecated
3657
+ */ this.documents = new Documents(this._client);
3658
+ }
3659
+ }
3660
+ // Required header for knowledge APIs
3661
+ const documents_documents_headers = {
3662
+ 'agw-js-conv': 'str'
3663
+ };
3664
+ class documents_Documents extends APIResource {
3665
+ /**
3666
+ * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images.
3667
+ * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。
3668
+ * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en
3669
+ * @docs zh: https://www.coze.cn/docs/developer_guides/list_knowledge_files?_lang=zh
3670
+ * @param params.dataset_id - Required The ID of the knowledge base. | 必选 待查看文件的知识库 ID。
3671
+ * @param params.page - Optional The page number for paginated queries. Default is 1. | 可选 分页查询时的页码。默认为 1。
3672
+ * @param params.page_size - Optional The size of pagination. Default is 10. | 可选 分页大小。默认为 10。
3673
+ * @returns ListDocumentData | 知识库文件列表
3674
+ */ list(params, options) {
3675
+ const apiUrl = '/open_api/knowledge/document/list';
3676
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3677
+ headers: documents_documents_headers
3678
+ }));
3679
+ return response;
3680
+ }
3681
+ /**
3682
+ * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。
3683
+ * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en
3684
+ * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh
3685
+ * @param params.dataset_id - Required The ID of the knowledge. | 必选 知识库 ID。
3686
+ * @param params.document_bases - Required The metadata information of the files awaiting upload. | 必选 待上传文件的元数据信息。
3687
+ * @param params.chunk_strategy - Required when uploading files to a new knowledge for the first time. Chunk strategy.
3688
+ * | 向新知识库首次上传文件时必选 分段规则。
3689
+ * @returns DocumentInfo[] | 已上传文件的基本信息
3690
+ */ async create(params, options) {
3691
+ const apiUrl = '/open_api/knowledge/document/create';
3692
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3693
+ headers: documents_documents_headers
3694
+ }));
3695
+ return response.document_infos;
3696
+ }
3697
+ /**
3698
+ * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion.
3699
+ * | 删除知识库中的文本、图像、表格等文件,支持批量删除。
3700
+ * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en
3701
+ * @docs zh: https://www.coze.cn/docs/developer_guides/delete_knowledge_files?_lang=zh
3702
+ * @param params.document_ids - Required The list of knowledge base files to be deleted. | 必选 待删除的文件 ID。
3703
+ * @returns void | 无返回
3704
+ */ async delete(params, options) {
3705
+ const apiUrl = '/open_api/knowledge/document/delete';
3706
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3707
+ headers: documents_documents_headers
3708
+ }));
3709
+ }
3710
+ /**
3711
+ * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。
3712
+ * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en
3713
+ * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh
3714
+ * @param params.document_id - Required The ID of the knowledge base file. | 必选 待修改的知识库文件 ID。
3715
+ * @param params.document_name - Optional The new name of the knowledge base file. | 可选 知识库文件的新名称。
3716
+ * @param params.update_rule - Optional The update strategy for online web pages. | 可选 在线网页更新策略。
3717
+ * @returns void | 无返回
3718
+ */ async update(params, options) {
3719
+ const apiUrl = '/open_api/knowledge/document/update';
3720
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3721
+ headers: documents_documents_headers
3722
+ }));
3723
+ }
3724
+ }
3725
+ class Datasets extends APIResource {
3726
+ constructor(...args){
3727
+ super(...args), this.documents = new documents_Documents(this._client);
3588
3728
  }
3589
3729
  }
3590
3730
  class Voices extends APIResource {
@@ -3641,7 +3781,7 @@ class Speech extends APIResource {
3641
3781
  * @returns Speech synthesis data
3642
3782
  */ async create(params, options) {
3643
3783
  const apiUrl = '/v1/audio/speech';
3644
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3784
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3645
3785
  responseType: 'arraybuffer'
3646
3786
  }));
3647
3787
  return response;
@@ -3654,23 +3794,26 @@ class Rooms extends APIResource {
3654
3794
  return response.data;
3655
3795
  }
3656
3796
  }
3657
- class esm_Audio extends APIResource {
3797
+ class audio_Audio extends APIResource {
3658
3798
  constructor(...args){
3659
3799
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3660
3800
  }
3661
3801
  }
3662
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.14","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"dist/types/index.d.ts","files":["dist","LICENSE","README.md","!**/*.tsbuildinfo"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","prepublishOnly":"npm run build","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"}}'); // CONCATENATED MODULE: ./src/version.ts
3663
- const { version: esm_version } = package_namespaceObject;
3802
+ // EXTERNAL MODULE: os (ignored)
3803
+ var os_ignored_ = __webpack_require__("?9050");
3804
+ var os_ignored_default = /*#__PURE__*/ __webpack_require__.n(os_ignored_);
3805
+ var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.15-beta.2","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","main":"src/index.ts","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"src/index.ts","files":["dist","LICENSE","README.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"},"cozePublishConfig":{"exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","types":"dist/types/index.d.ts"}}'); // CONCATENATED MODULE: ../coze-js/src/version.ts
3806
+ const { version: version_version } = package_namespaceObject;
3664
3807
  const getEnv = ()=>{
3665
3808
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3666
3809
  const { platform } = process;
3667
3810
  let osName = platform.toLowerCase();
3668
- let osVersion = os_ignored_.release();
3811
+ let osVersion = os_ignored_default().release();
3669
3812
  if ('darwin' === platform) {
3670
3813
  osName = 'macos';
3671
3814
  // Try to parse the macOS version
3672
3815
  try {
3673
- const darwinVersion = os_ignored_.release().split('.');
3816
+ const darwinVersion = os_ignored_default().release().split('.');
3674
3817
  if (darwinVersion.length >= 2) {
3675
3818
  const majorVersion = parseInt(darwinVersion[0], 10);
3676
3819
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3683,10 +3826,10 @@ const getEnv = ()=>{
3683
3826
  }
3684
3827
  } else if ('win32' === platform) {
3685
3828
  osName = 'windows';
3686
- osVersion = os_ignored_.release();
3829
+ osVersion = os_ignored_default().release();
3687
3830
  } else if ('linux' === platform) {
3688
3831
  osName = 'linux';
3689
- osVersion = os_ignored_.release();
3832
+ osVersion = os_ignored_default().release();
3690
3833
  }
3691
3834
  return {
3692
3835
  osName,
@@ -3696,12 +3839,12 @@ const getEnv = ()=>{
3696
3839
  };
3697
3840
  const getUserAgent = ()=>{
3698
3841
  const { nodeVersion, osName, osVersion } = getEnv();
3699
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3842
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3700
3843
  };
3701
3844
  const getNodeClientUserAgent = ()=>{
3702
3845
  const { osVersion, nodeVersion, osName } = getEnv();
3703
3846
  const ua = {
3704
- version: esm_version,
3847
+ version: version_version,
3705
3848
  lang: 'node',
3706
3849
  lang_version: nodeVersion,
3707
3850
  os_name: osName,
@@ -3709,15 +3852,17 @@ const getNodeClientUserAgent = ()=>{
3709
3852
  };
3710
3853
  return JSON.stringify(ua);
3711
3854
  };
3712
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3855
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3713
3856
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3714
3857
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3715
3858
  var _error_response;
3716
3859
  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);
3717
3860
  }
3718
3861
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3719
- var _error_response1, _error_response2, _error_response3;
3720
- 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);
3862
+ else {
3863
+ var _error_response1, _error_response2, _error_response3;
3864
+ 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);
3865
+ }
3721
3866
  };
3722
3867
  async function fetchAPI(url) {
3723
3868
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -3733,7 +3878,7 @@ async function fetchAPI(url) {
3733
3878
  adapter: options.isStreaming ? 'fetch' : void 0,
3734
3879
  ...options
3735
3880
  }).catch((error)=>{
3736
- throw esm_handleError(error);
3881
+ throw fetcher_handleError(error);
3737
3882
  });
3738
3883
  return {
3739
3884
  async *stream () {
@@ -3771,7 +3916,7 @@ async function fetchAPI(url) {
3771
3916
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3772
3917
  }
3773
3918
  } catch (error) {
3774
- esm_handleError(error);
3919
+ fetcher_handleError(error);
3775
3920
  }
3776
3921
  },
3777
3922
  json: ()=>response.data,
@@ -3795,17 +3940,22 @@ function isAxiosStatic(instance) {
3795
3940
  }
3796
3941
  /**
3797
3942
  * default coze base URL is api.coze.com
3798
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
3799
- /* eslint-disable max-params */ class APIClient {
3800
- buildOptions(method, body, options) {
3943
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
3944
+ /* eslint-disable max-params */ class core_APIClient {
3945
+ async getToken() {
3946
+ if ('function' == typeof this.token) return await this.token();
3947
+ return this.token;
3948
+ }
3949
+ async buildOptions(method, body, options) {
3950
+ const token = await this.getToken();
3801
3951
  const headers = {
3802
- authorization: `Bearer ${this.token}`
3952
+ authorization: `Bearer ${token}`
3803
3953
  };
3804
- if (!isBrowser()) {
3954
+ if (!utils_isBrowser()) {
3805
3955
  headers['User-Agent'] = getUserAgent();
3806
3956
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3807
3957
  }
3808
- const config = esm_mergeConfig(this.axiosOptions, options, {
3958
+ const config = mergeConfig(this.axiosOptions, options, {
3809
3959
  headers
3810
3960
  });
3811
3961
  config.method = method;
@@ -3814,7 +3964,7 @@ function isAxiosStatic(instance) {
3814
3964
  }
3815
3965
  async makeRequest(apiUrl, method, body, isStream, options) {
3816
3966
  const fullUrl = `${this.baseURL}${apiUrl}`;
3817
- const fetchOptions = this.buildOptions(method, body, options);
3967
+ const fetchOptions = await this.buildOptions(method, body, options);
3818
3968
  fetchOptions.isStreaming = isStream;
3819
3969
  fetchOptions.axiosInstance = this.axiosInstance;
3820
3970
  this.debugLog(`--- request url: ${fullUrl}`);
@@ -3829,7 +3979,7 @@ function isAxiosStatic(instance) {
3829
3979
  if (contentType && contentType.includes('application/json')) {
3830
3980
  const result = await json();
3831
3981
  const { code, msg } = result;
3832
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3982
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3833
3983
  }
3834
3984
  return stream();
3835
3985
  }
@@ -3837,7 +3987,7 @@ function isAxiosStatic(instance) {
3837
3987
  {
3838
3988
  const result = await json();
3839
3989
  const { code, msg } = result;
3840
- if (0 !== code && void 0 !== code) throw APIError.generate(response.status, result, msg, response.headers);
3990
+ if (0 !== code && void 0 !== code) throw error_APIError.generate(response.status, result, msg, response.headers);
3841
3991
  return result;
3842
3992
  }
3843
3993
  }
@@ -3869,29 +4019,35 @@ function isAxiosStatic(instance) {
3869
4019
  }
3870
4020
  constructor(config){
3871
4021
  this._config = config;
3872
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4022
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
3873
4023
  this.token = config.token;
3874
4024
  this.axiosOptions = config.axiosOptions || {};
3875
4025
  this.axiosInstance = config.axiosInstance;
3876
4026
  this.debug = config.debug || false;
3877
4027
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
3878
4028
  this.headers = config.headers;
3879
- if (isBrowser() && 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');
3880
- }
3881
- }
3882
- APIClient.APIError = APIError;
3883
- APIClient.BadRequestError = BadRequestError;
3884
- APIClient.AuthenticationError = AuthenticationError;
3885
- APIClient.PermissionDeniedError = PermissionDeniedError;
3886
- APIClient.NotFoundError = NotFoundError;
3887
- APIClient.RateLimitError = RateLimitError;
3888
- APIClient.InternalServerError = InternalServerError;
3889
- APIClient.GatewayError = GatewayError;
3890
- APIClient.TimeoutError = TimeoutError;
3891
- APIClient.UserAbortError = APIUserAbortError;
3892
- class CozeAPI extends APIClient {
4029
+ 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');
4030
+ }
4031
+ }
4032
+ core_APIClient.APIError = error_APIError;
4033
+ core_APIClient.BadRequestError = BadRequestError;
4034
+ core_APIClient.AuthenticationError = AuthenticationError;
4035
+ core_APIClient.PermissionDeniedError = PermissionDeniedError;
4036
+ core_APIClient.NotFoundError = NotFoundError;
4037
+ core_APIClient.RateLimitError = RateLimitError;
4038
+ core_APIClient.InternalServerError = InternalServerError;
4039
+ core_APIClient.GatewayError = GatewayError;
4040
+ core_APIClient.TimeoutError = TimeoutError;
4041
+ core_APIClient.UserAbortError = APIUserAbortError;
4042
+ // EXTERNAL MODULE: crypto (ignored)
4043
+ __webpack_require__("?666e");
4044
+ // EXTERNAL MODULE: jsonwebtoken (ignored)
4045
+ __webpack_require__("?79fd");
4046
+ class CozeAPI extends core_APIClient {
3893
4047
  constructor(...args){
3894
- super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), this.knowledge = new Knowledge(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new esm_Audio(this);
4048
+ super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4049
+ * @deprecated
4050
+ */ 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);
3895
4051
  }
3896
4052
  }
3897
4053
  /**
@@ -9123,7 +9279,7 @@ var setPrototypeOf = setPrototypeOf$2, _Object$setPrototypeOf = getDefaultExport
9123
9279
  }, stringPad = {
9124
9280
  start: createMethod(!1),
9125
9281
  end: createMethod(!0)
9126
- }, userAgent = engineUserAgent, stringPadWebkitBug = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent), $$F = _export, $padEnd = stringPad.end, WEBKIT_BUG$1 = stringPadWebkitBug;
9282
+ }, 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;
9127
9283
  $$F({
9128
9284
  target: "String",
9129
9285
  proto: !0,
@@ -38276,11 +38432,12 @@ var VERTC = _createClass(function e() {
38276
38432
  + * @param milliseconds The time to sleep in milliseconds
38277
38433
  + * @throws {Error} If milliseconds is negative
38278
38434
  + * @returns Promise that resolves after the specified duration
38279
- + */ const utils_sleep = (milliseconds)=>{
38435
+ + */ const src_utils_sleep = (milliseconds)=>{
38280
38436
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38281
38437
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38282
38438
  };
38283
38439
  /**
38440
+ * @deprecated use checkDevicePermission instead
38284
38441
  * Check microphone permission,return boolean
38285
38442
  */ const checkPermission = async function() {
38286
38443
  let { audio = true, video = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
@@ -38295,6 +38452,13 @@ var VERTC = _createClass(function e() {
38295
38452
  return false;
38296
38453
  }
38297
38454
  };
38455
+ const checkDevicePermission = async function() {
38456
+ let checkVideo = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
38457
+ return await index_esm_min_index.enableDevices({
38458
+ audio: true,
38459
+ video: checkVideo
38460
+ });
38461
+ };
38298
38462
  /**
38299
38463
  * Get audio devices
38300
38464
  * @returns Promise<AudioDevices> Object containing arrays of audio input and output devices