@coze/realtime-api 1.0.3 → 1.0.4-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
- "?c628": function() {
4
+ "?666e": function() {
5
5
  /* (ignored) */ },
6
- "?9452": function() {
6
+ "?79fd": function() {
7
7
  /* (ignored) */ },
8
- "?e2b1": 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, {
@@ -90,480 +105,1041 @@ __webpack_require__.d(src_utils_namespaceObject, {
90
105
  checkDevicePermission: ()=>checkDevicePermission,
91
106
  checkPermission: ()=>checkPermission,
92
107
  getAudioDevices: ()=>getAudioDevices,
93
- sleep: ()=>utils_sleep
108
+ sleep: ()=>src_utils_sleep
94
109
  });
95
- function bind(fn, thisArg) {
96
- return function() {
97
- return fn.apply(thisArg, arguments);
98
- };
110
+ class APIResource {
111
+ constructor(client){
112
+ this._client = client;
113
+ }
99
114
  }
100
- // utils is a library of generic helper functions non-specific to axios
101
- const { toString: utils_toString } = Object.prototype;
102
- const { getPrototypeOf } = Object;
103
- const kindOf = ((cache)=>(thing)=>{
104
- const str = utils_toString.call(thing);
105
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
106
- })(Object.create(null));
107
- const kindOfTest = (type)=>{
108
- type = type.toLowerCase();
109
- return (thing)=>kindOf(thing) === type;
110
- };
111
- const typeOfTest = (type)=>(thing)=>typeof thing === type;
112
- /**
113
- * Determine if a value is an Array
114
- *
115
- * @param {Object} val The value to test
116
- *
117
- * @returns {boolean} True if value is an Array, otherwise false
118
- */ const { isArray } = Array;
119
- /**
120
- * Determine if a value is undefined
121
- *
122
- * @param {*} val The value to test
123
- *
124
- * @returns {boolean} True if the value is undefined, otherwise false
125
- */ const isUndefined = typeOfTest('undefined');
126
- /**
127
- * Determine if a value is a Buffer
128
- *
129
- * @param {*} val The value to test
130
- *
131
- * @returns {boolean} True if value is a Buffer, otherwise false
132
- */ function isBuffer(val) {
133
- 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
+ }
134
190
  }
135
- /**
136
- * Determine if a value is an ArrayBuffer
137
- *
138
- * @param {*} val The value to test
139
- *
140
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
141
- */ const isArrayBuffer = kindOfTest('ArrayBuffer');
142
- /**
143
- * Determine if a value is a view on an ArrayBuffer
144
- *
145
- * @param {*} val The value to test
146
- *
147
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
148
- */ function isArrayBufferView(val) {
149
- let result;
150
- result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
151
- 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
+ }
152
198
  }
153
- /**
154
- * Determine if a value is a String
155
- *
156
- * @param {*} val The value to test
157
- *
158
- * @returns {boolean} True if value is a String, otherwise false
159
- */ const isString = typeOfTest('string');
160
- /**
161
- * Determine if a value is a Function
162
- *
163
- * @param {*} val The value to test
164
- * @returns {boolean} True if value is a Function, otherwise false
165
- */ const isFunction = typeOfTest('function');
166
- /**
167
- * Determine if a value is a Number
168
- *
169
- * @param {*} val The value to test
170
- *
171
- * @returns {boolean} True if value is a Number, otherwise false
172
- */ const isNumber = typeOfTest('number');
173
- /**
174
- * Determine if a value is an Object
175
- *
176
- * @param {*} thing The value to test
177
- *
178
- * @returns {boolean} True if value is an Object, otherwise false
179
- */ const isObject = (thing)=>null !== thing && 'object' == typeof thing;
180
- /**
181
- * Determine if a value is a Boolean
182
- *
183
- * @param {*} thing The value to test
184
- * @returns {boolean} True if value is a Boolean, otherwise false
185
- */ const isBoolean = (thing)=>true === thing || false === thing;
186
- /**
187
- * Determine if a value is a plain Object
188
- *
189
- * @param {*} val The value to test
190
- *
191
- * @returns {boolean} True if value is a plain Object, otherwise false
192
- */ const isPlainObject = (val)=>{
193
- if ('object' !== kindOf(val)) return false;
194
- const prototype = getPrototypeOf(val);
195
- return (null === prototype || prototype === Object.prototype || null === Object.getPrototypeOf(prototype)) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
196
- };
197
- /**
198
- * Determine if a value is a Date
199
- *
200
- * @param {*} val The value to test
201
- *
202
- * @returns {boolean} True if value is a Date, otherwise false
203
- */ const isDate = kindOfTest('Date');
204
- /**
205
- * Determine if a value is a File
206
- *
207
- * @param {*} val The value to test
208
- *
209
- * @returns {boolean} True if value is a File, otherwise false
210
- */ const isFile = kindOfTest('File');
211
- /**
212
- * Determine if a value is a Blob
213
- *
214
- * @param {*} val The value to test
215
- *
216
- * @returns {boolean} True if value is a Blob, otherwise false
217
- */ const isBlob = kindOfTest('Blob');
218
- /**
219
- * Determine if a value is a FileList
220
- *
221
- * @param {*} val The value to test
222
- *
223
- * @returns {boolean} True if value is a File, otherwise false
224
- */ const utils_isFileList = kindOfTest('FileList');
225
- /**
226
- * Determine if a value is a Stream
227
- *
228
- * @param {*} val The value to test
229
- *
230
- * @returns {boolean} True if value is a Stream, otherwise false
231
- */ const utils_isStream = (val)=>isObject(val) && isFunction(val.pipe);
232
- /**
233
- * Determine if a value is a FormData
234
- *
235
- * @param {*} thing The value to test
236
- *
237
- * @returns {boolean} True if value is an FormData, otherwise false
238
- */ const utils_isFormData = (thing)=>{
239
- let kind;
240
- return thing && ('function' == typeof FormData && thing instanceof FormData || isFunction(thing.append) && ('formdata' === (kind = kindOf(thing)) || // detect form-data instance
241
- 'object' === kind && isFunction(thing.toString) && '[object FormData]' === thing.toString()));
242
- };
243
- /**
244
- * Determine if a value is a URLSearchParams object
245
- *
246
- * @param {*} val The value to test
247
- *
248
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
249
- */ const isURLSearchParams = kindOfTest('URLSearchParams');
250
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
251
- 'ReadableStream',
252
- 'Request',
253
- 'Response',
254
- 'Headers'
255
- ].map(kindOfTest);
256
- /**
257
- * Trim excess whitespace off the beginning and end of a string
258
- *
259
- * @param {String} str The String to trim
260
- *
261
- * @returns {String} The String freed of excess whitespace
262
- */ const trim = (str)=>str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
263
- /**
264
- * Iterate over an Array or an Object invoking a function for each item.
265
- *
266
- * If `obj` is an Array callback will be called passing
267
- * the value, index, and complete array for each item.
268
- *
269
- * If 'obj' is an Object callback will be called passing
270
- * the value, key, and complete object for each property.
271
- *
272
- * @param {Object|Array} obj The object to iterate
273
- * @param {Function} fn The callback to invoke for each item
274
- *
275
- * @param {Boolean} [allOwnKeys = false]
276
- * @returns {any}
277
- */ function forEach(obj, fn, { allOwnKeys = false } = {}) {
278
- // Don't bother if no value provided
279
- if (null == obj) return;
280
- let i;
281
- let l;
282
- // Force an array if not already something iterable
283
- if ('object' != typeof obj) /*eslint no-param-reassign:0*/ obj = [
284
- obj
285
- ];
286
- if (isArray(obj)) // Iterate over array values
287
- for(i = 0, l = obj.length; i < l; i++)fn.call(null, obj[i], i, obj);
288
- else {
289
- // Iterate over object keys
290
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
291
- const len = keys.length;
292
- let key;
293
- for(i = 0; i < len; i++){
294
- key = keys[i];
295
- 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(', ');
296
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;
297
277
  }
298
278
  }
299
- function findKey(obj, key) {
300
- key = key.toLowerCase();
301
- const keys = Object.keys(obj);
302
- let i = keys.length;
303
- let _key;
304
- while(i-- > 0){
305
- _key = keys[i];
306
- 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
+ // }
307
285
  }
308
- return null;
309
286
  }
310
- const _global = (()=>{
311
- /*eslint no-undef:0*/ if ("undefined" != typeof globalThis) return globalThis;
312
- return "undefined" != typeof self ? self : 'undefined' != typeof window ? window : global;
313
- })();
314
- const isContextDefined = (context)=>!isUndefined(context) && context !== _global;
315
- /**
316
- * Accepts varargs expecting each argument to be an object, then
317
- * immutably merges the properties of each object and returns result.
318
- *
319
- * When multiple objects contain the same key the later object in
320
- * the arguments list will take precedence.
321
- *
322
- * Example:
323
- *
324
- * ```js
325
- * var result = merge({foo: 123}, {foo: 456});
326
- * console.log(result.foo); // outputs 456
327
- * ```
328
- *
329
- * @param {Object} obj1 Object to merge
330
- *
331
- * @returns {Object} Result of all merge properties
332
- */ function utils_merge() {
333
- const { caseless } = isContextDefined(this) && this || {};
334
- const result = {};
335
- const assignValue = (val, key)=>{
336
- const targetKey = caseless && findKey(result, key) || key;
337
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) result[targetKey] = utils_merge(result[targetKey], val);
338
- else if (isPlainObject(val)) result[targetKey] = utils_merge({}, val);
339
- else if (isArray(val)) result[targetKey] = val.slice();
340
- else result[targetKey] = val;
341
- };
342
- for(let i = 0, l = arguments.length; i < l; i++)arguments[i] && forEach(arguments[i], assignValue);
343
- 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
+ }
344
291
  }
345
- /**
346
- * Extends object a by mutably adding to it the properties of object b.
347
- *
348
- * @param {Object} a The object to be extended
349
- * @param {Object} b The object to copy properties from
350
- * @param {Object} thisArg The object to bind function to
351
- *
352
- * @param {Boolean} [allOwnKeys]
353
- * @returns {Object} The resulting value of object a
354
- */ const extend = (a, b, thisArg, { allOwnKeys } = {})=>{
355
- forEach(b, (val, key)=>{
356
- if (thisArg && isFunction(val)) a[key] = bind(val, thisArg);
357
- else a[key] = val;
358
- }, {
359
- allOwnKeys
360
- });
361
- return a;
362
- };
363
- /**
364
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
365
- *
366
- * @param {string} content with BOM
367
- *
368
- * @returns {string} content value without BOM
369
- */ const stripBOM = (content)=>{
370
- if (0xFEFF === content.charCodeAt(0)) content = content.slice(1);
371
- return content;
372
- };
373
- /**
374
- * Inherit the prototype methods from one constructor into another
375
- * @param {function} constructor
376
- * @param {function} superConstructor
377
- * @param {object} [props]
378
- * @param {object} [descriptors]
379
- *
380
- * @returns {void}
381
- */ const inherits = (constructor, superConstructor, props, descriptors)=>{
382
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
383
- constructor.prototype.constructor = constructor;
384
- Object.defineProperty(constructor, 'super', {
385
- value: superConstructor.prototype
386
- });
387
- 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);
388
335
  };
389
- /**
390
- * Resolve object with deep prototype chain to a flat object
391
- * @param {Object} sourceObj source object
392
- * @param {Object} [destObj]
393
- * @param {Function|Boolean} [filter]
394
- * @param {Function} [propFilter]
395
- *
396
- * @returns {Object}
397
- */ const toFlatObject = (sourceObj, destObj, filter, propFilter)=>{
398
- let props;
399
- let i;
400
- let prop;
401
- const merged = {};
402
- destObj = destObj || {};
403
- // eslint-disable-next-line no-eq-null,eqeqeq
404
- if (null == sourceObj) return destObj;
405
- do {
406
- props = Object.getOwnPropertyNames(sourceObj);
407
- i = props.length;
408
- while(i-- > 0){
409
- prop = props[i];
410
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
411
- destObj[prop] = sourceObj[prop];
412
- merged[prop] = true;
413
- }
414
- }
415
- sourceObj = false !== filter && getPrototypeOf(sourceObj);
416
- }while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
417
- 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;
418
686
  };
687
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
419
688
  /**
420
- * Determines whether a string ends with the characters of a specified string
689
+ * Determine if a value is an Array
421
690
  *
422
- * @param {String} str
423
- * @param {String} searchString
424
- * @param {Number} [position= 0]
691
+ * @param {Object} val The value to test
425
692
  *
426
- * @returns {boolean}
427
- */ const endsWith = (str, searchString, position)=>{
428
- str = String(str);
429
- if (void 0 === position || position > str.length) position = str.length;
430
- position -= searchString.length;
431
- const lastIndex = str.indexOf(searchString, position);
432
- return -1 !== lastIndex && lastIndex === position;
433
- };
693
+ * @returns {boolean} True if value is an Array, otherwise false
694
+ */ const { isArray } = Array;
434
695
  /**
435
- * Returns new array from array like object or null if failed
696
+ * Determine if a value is undefined
436
697
  *
437
- * @param {*} [thing]
698
+ * @param {*} val The value to test
438
699
  *
439
- * @returns {?Array}
440
- */ const toArray = (thing)=>{
441
- if (!thing) return null;
442
- if (isArray(thing)) return thing;
443
- let i = thing.length;
444
- if (!isNumber(i)) return null;
445
- const arr = new Array(i);
446
- while(i-- > 0)arr[i] = thing[i];
447
- return arr;
448
- };
700
+ * @returns {boolean} True if the value is undefined, otherwise false
701
+ */ const isUndefined = typeOfTest('undefined');
449
702
  /**
450
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
451
- * thing passed in is an instance of Uint8Array
703
+ * Determine if a value is a Buffer
452
704
  *
453
- * @param {TypedArray}
705
+ * @param {*} val The value to test
454
706
  *
455
- * @returns {Array}
456
- */ // eslint-disable-next-line func-names
457
- 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
+ }
458
711
  /**
459
- * For each entry in the object, call the function with the key and value.
712
+ * Determine if a value is an ArrayBuffer
460
713
  *
461
- * @param {Object<any, any>} obj - The object to iterate over.
462
- * @param {Function} fn - The function to call for each entry.
714
+ * @param {*} val The value to test
463
715
  *
464
- * @returns {void}
465
- */ const forEachEntry = (obj, fn)=>{
466
- const generator = obj && obj[Symbol.iterator];
467
- const iterator = generator.call(obj);
468
- let result;
469
- while((result = iterator.next()) && !result.done){
470
- const pair = result.value;
471
- fn.call(obj, pair[0], pair[1]);
472
- }
473
- };
716
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
717
+ */ const isArrayBuffer = kindOfTest('ArrayBuffer');
474
718
  /**
475
- * It takes a regular expression and a string, and returns an array of all the matches
719
+ * Determine if a value is a view on an ArrayBuffer
476
720
  *
477
- * @param {string} regExp - The regular expression to match against.
478
- * @param {string} str - The string to search.
721
+ * @param {*} val The value to test
479
722
  *
480
- * @returns {Array<boolean>}
481
- */ const matchAll = (regExp, str)=>{
482
- let matches;
483
- const arr = [];
484
- while(null !== (matches = regExp.exec(str)))arr.push(matches);
485
- return arr;
486
- };
487
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement');
488
- const toCamelCase = (str)=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function(m, p1, p2) {
489
- return p1.toUpperCase() + p2;
490
- });
491
- /* Creating a function that will check if an object has a property. */ const utils_hasOwnProperty = (({ hasOwnProperty })=>(obj, prop)=>hasOwnProperty.call(obj, prop))(Object.prototype);
723
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
724
+ */ function isArrayBufferView(val) {
725
+ let result;
726
+ result = 'undefined' != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(val) : val && val.buffer && isArrayBuffer(val.buffer);
727
+ return result;
728
+ }
492
729
  /**
493
- * Determine if a value is a RegExp object
730
+ * Determine if a value is a String
494
731
  *
495
732
  * @param {*} val The value to test
496
733
  *
497
- * @returns {boolean} True if value is a RegExp object, otherwise false
498
- */ const isRegExp = kindOfTest('RegExp');
499
- const reduceDescriptors = (obj, reducer)=>{
500
- const descriptors = Object.getOwnPropertyDescriptors(obj);
501
- const reducedDescriptors = {};
502
- forEach(descriptors, (descriptor, name)=>{
503
- let ret;
504
- if (false !== (ret = reducer(descriptor, name, obj))) reducedDescriptors[name] = ret || descriptor;
505
- });
506
- Object.defineProperties(obj, reducedDescriptors);
507
- };
734
+ * @returns {boolean} True if value is a String, otherwise false
735
+ */ const isString = typeOfTest('string');
508
736
  /**
509
- * Makes all methods read-only
510
- * @param {Object} obj
511
- */ const freezeMethods = (obj)=>{
512
- reduceDescriptors(obj, (descriptor, name)=>{
513
- // skip restricted props in strict mode
514
- if (isFunction(obj) && -1 !== [
515
- 'arguments',
516
- 'caller',
517
- 'callee'
518
- ].indexOf(name)) return false;
519
- const value = obj[name];
520
- if (!isFunction(value)) return;
521
- descriptor.enumerable = false;
522
- if ('writable' in descriptor) {
523
- descriptor.writable = false;
524
- return;
525
- }
526
- if (!descriptor.set) descriptor.set = ()=>{
527
- throw Error('Can not rewrite read-only method \'' + name + '\'');
528
- };
529
- });
530
- };
531
- const toObjectSet = (arrayOrString, delimiter)=>{
532
- const obj = {};
533
- const define = (arr)=>{
534
- arr.forEach((value)=>{
535
- obj[value] = true;
536
- });
537
- };
538
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
539
- return obj;
540
- };
541
- const noop = ()=>{};
542
- const toFiniteNumber = (value, defaultValue)=>null != value && Number.isFinite(value = +value) ? value : defaultValue;
543
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
544
- const DIGIT = '0123456789';
545
- const ALPHABET = {
546
- DIGIT,
547
- ALPHA,
548
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
549
- };
550
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT)=>{
551
- let str = '';
552
- const { length } = alphabet;
553
- while(size--)str += alphabet[Math.random() * length | 0];
554
- return str;
555
- };
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');
556
742
  /**
557
- * If the thing is a FormData object, return true, otherwise return false.
743
+ * Determine if a value is a Number
558
744
  *
559
- * @param {unknown} thing - The thing to check.
745
+ * @param {*} val The value to test
560
746
  *
561
- * @returns {boolean}
562
- */ function isSpecCompliantForm(thing) {
563
- return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
564
- }
565
- const toJSONObject = (obj)=>{
566
- const stack = new Array(10);
747
+ * @returns {boolean} True if value is a Number, otherwise false
748
+ */ const isNumber = typeOfTest('number');
749
+ /**
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;
756
+ /**
757
+ * Determine if a value is a Boolean
758
+ *
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
764
+ *
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) {
1139
+ return !!(thing && isFunction(thing.append) && 'FormData' === thing[Symbol.toStringTag] && thing[Symbol.iterator]);
1140
+ }
1141
+ const toJSONObject = (obj)=>{
1142
+ const stack = new Array(10);
567
1143
  const visit = (source, i)=>{
568
1144
  if (isObject(source)) {
569
1145
  if (stack.indexOf(source) >= 0) return;
@@ -610,7 +1186,7 @@ const asap = 'undefined' != typeof queueMicrotask ? queueMicrotask.bind(_global)
610
1186
  isNumber,
611
1187
  isBoolean,
612
1188
  isObject,
613
- isPlainObject,
1189
+ isPlainObject: utils_isPlainObject,
614
1190
  isReadableStream,
615
1191
  isRequest,
616
1192
  isResponse,
@@ -1808,7 +2384,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1808
2384
  * @param {Object} config2
1809
2385
  *
1810
2386
  * @returns {Object} New object resulting from merging config2 to config1
1811
- */ function mergeConfig(config1, config2) {
2387
+ */ function mergeConfig_mergeConfig(config1, config2) {
1812
2388
  // eslint-disable-next-line no-param-reassign
1813
2389
  config2 = config2 || {};
1814
2390
  const config = {};
@@ -1878,7 +2454,7 @@ const headersToObject = (thing)=>thing instanceof AxiosHeaders ? {
1878
2454
  return config;
1879
2455
  }
1880
2456
  /* ESM default export */ const resolveConfig = (config)=>{
1881
- const newConfig = mergeConfig({}, config);
2457
+ const newConfig = mergeConfig_mergeConfig({}, config);
1882
2458
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1883
2459
  newConfig.headers = headers = AxiosHeaders.from(headers);
1884
2460
  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
@@ -2470,960 +3046,393 @@ const Axios_validators = helpers_validator.validators;
2470
3046
  try {
2471
3047
  if (err.stack) {
2472
3048
  if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) err.stack += '\n' + stack;
2473
- } else err.stack = stack;
2474
- } catch (e) {
2475
- // ignore the case where "stack" is an un-writable property
2476
- }
2477
- }
2478
- throw err;
2479
- }
2480
- }
2481
- _request(configOrUrl, config) {
2482
- /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API
2483
- if ('string' == typeof configOrUrl) {
2484
- config = config || {};
2485
- config.url = configOrUrl;
2486
- } else config = configOrUrl || {};
2487
- config = mergeConfig(this.defaults, config);
2488
- const { transitional, paramsSerializer, headers } = config;
2489
- if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
2490
- silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
2491
- forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
2492
- clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean)
2493
- }, false);
2494
- if (null != paramsSerializer) {
2495
- if (utils.isFunction(paramsSerializer)) config.paramsSerializer = {
2496
- serialize: paramsSerializer
2497
- };
2498
- else helpers_validator.assertOptions(paramsSerializer, {
2499
- encode: Axios_validators.function,
2500
- serialize: Axios_validators.function
2501
- }, true);
2502
- }
2503
- // Set config.method
2504
- config.method = (config.method || this.defaults.method || 'get').toLowerCase();
2505
- // Flatten headers
2506
- let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
2507
- headers && utils.forEach([
2508
- 'delete',
2509
- 'get',
2510
- 'head',
2511
- 'post',
2512
- 'put',
2513
- 'patch',
2514
- 'common'
2515
- ], (method)=>{
2516
- delete headers[method];
2517
- });
2518
- config.headers = AxiosHeaders.concat(contextHeaders, headers);
2519
- // filter out skipped interceptors
2520
- const requestInterceptorChain = [];
2521
- let synchronousRequestInterceptors = true;
2522
- this.interceptors.request.forEach(function(interceptor) {
2523
- if ('function' == typeof interceptor.runWhen && false === interceptor.runWhen(config)) return;
2524
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2525
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2526
- });
2527
- const responseInterceptorChain = [];
2528
- this.interceptors.response.forEach(function(interceptor) {
2529
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2530
- });
2531
- let promise;
2532
- let i = 0;
2533
- let len;
2534
- if (!synchronousRequestInterceptors) {
2535
- const chain = [
2536
- dispatchRequest.bind(this),
2537
- void 0
2538
- ];
2539
- chain.unshift.apply(chain, requestInterceptorChain);
2540
- chain.push.apply(chain, responseInterceptorChain);
2541
- len = chain.length;
2542
- promise = Promise.resolve(config);
2543
- while(i < len)promise = promise.then(chain[i++], chain[i++]);
2544
- return promise;
2545
- }
2546
- len = requestInterceptorChain.length;
2547
- let newConfig = config;
2548
- i = 0;
2549
- while(i < len){
2550
- const onFulfilled = requestInterceptorChain[i++];
2551
- const onRejected = requestInterceptorChain[i++];
2552
- try {
2553
- newConfig = onFulfilled(newConfig);
2554
- } catch (error) {
2555
- onRejected.call(this, error);
2556
- break;
2557
- }
2558
- }
2559
- try {
2560
- promise = dispatchRequest.call(this, newConfig);
2561
- } catch (error) {
2562
- return Promise.reject(error);
2563
- }
2564
- i = 0;
2565
- len = responseInterceptorChain.length;
2566
- while(i < len)promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2567
- return promise;
2568
- }
2569
- getUri(config) {
2570
- config = mergeConfig(this.defaults, config);
2571
- const fullPath = buildFullPath(config.baseURL, config.url);
2572
- return buildURL(fullPath, config.params, config.paramsSerializer);
2573
- }
2574
- }
2575
- // Provide aliases for supported request methods
2576
- utils.forEach([
2577
- 'delete',
2578
- 'get',
2579
- 'head',
2580
- 'options'
2581
- ], function(method) {
2582
- /*eslint func-names:0*/ Axios_Axios.prototype[method] = function(url, config) {
2583
- return this.request(mergeConfig(config || {}, {
2584
- method,
2585
- url,
2586
- data: (config || {}).data
2587
- }));
2588
- };
2589
- });
2590
- utils.forEach([
2591
- 'post',
2592
- 'put',
2593
- 'patch'
2594
- ], function(method) {
2595
- /*eslint func-names:0*/ function generateHTTPMethod(isForm) {
2596
- return function(url, data, config) {
2597
- return this.request(mergeConfig(config || {}, {
2598
- method,
2599
- headers: isForm ? {
2600
- 'Content-Type': 'multipart/form-data'
2601
- } : {},
2602
- url,
2603
- data
2604
- }));
2605
- };
2606
- }
2607
- Axios_Axios.prototype[method] = generateHTTPMethod();
2608
- Axios_Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2609
- });
2610
- /* ESM default export */ const Axios = Axios_Axios;
2611
- /**
2612
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2613
- *
2614
- * @param {Function} executor The executor function.
2615
- *
2616
- * @returns {CancelToken}
2617
- */ class CancelToken_CancelToken {
2618
- constructor(executor){
2619
- if ('function' != typeof executor) throw new TypeError('executor must be a function.');
2620
- let resolvePromise;
2621
- this.promise = new Promise(function(resolve) {
2622
- resolvePromise = resolve;
2623
- });
2624
- const token = this;
2625
- // eslint-disable-next-line func-names
2626
- this.promise.then((cancel)=>{
2627
- if (!token._listeners) return;
2628
- let i = token._listeners.length;
2629
- while(i-- > 0)token._listeners[i](cancel);
2630
- token._listeners = null;
2631
- });
2632
- // eslint-disable-next-line func-names
2633
- this.promise.then = (onfulfilled)=>{
2634
- let _resolve;
2635
- // eslint-disable-next-line func-names
2636
- const promise = new Promise((resolve)=>{
2637
- token.subscribe(resolve);
2638
- _resolve = resolve;
2639
- }).then(onfulfilled);
2640
- promise.cancel = function() {
2641
- token.unsubscribe(_resolve);
2642
- };
2643
- return promise;
2644
- };
2645
- executor(function(message, config, request) {
2646
- if (token.reason) // Cancellation has already been requested
2647
- return;
2648
- token.reason = new CanceledError(message, config, request);
2649
- resolvePromise(token.reason);
2650
- });
2651
- }
2652
- /**
2653
- * Throws a `CanceledError` if cancellation has been requested.
2654
- */ throwIfRequested() {
2655
- if (this.reason) throw this.reason;
2656
- }
2657
- /**
2658
- * Subscribe to the cancel signal
2659
- */ subscribe(listener) {
2660
- if (this.reason) {
2661
- listener(this.reason);
2662
- return;
2663
- }
2664
- if (this._listeners) this._listeners.push(listener);
2665
- else this._listeners = [
2666
- listener
2667
- ];
2668
- }
2669
- /**
2670
- * Unsubscribe from the cancel signal
2671
- */ unsubscribe(listener) {
2672
- if (!this._listeners) return;
2673
- const index = this._listeners.indexOf(listener);
2674
- if (-1 !== index) this._listeners.splice(index, 1);
2675
- }
2676
- toAbortSignal() {
2677
- const controller = new AbortController();
2678
- const abort = (err)=>{
2679
- controller.abort(err);
2680
- };
2681
- this.subscribe(abort);
2682
- controller.signal.unsubscribe = ()=>this.unsubscribe(abort);
2683
- return controller.signal;
2684
- }
2685
- /**
2686
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2687
- * cancels the `CancelToken`.
2688
- */ static source() {
2689
- let cancel;
2690
- const token = new CancelToken_CancelToken(function(c) {
2691
- cancel = c;
2692
- });
2693
- return {
2694
- token,
2695
- cancel
2696
- };
2697
- }
2698
- }
2699
- /* ESM default export */ const CancelToken = CancelToken_CancelToken;
2700
- /**
2701
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2702
- *
2703
- * Common use case would be to use `Function.prototype.apply`.
2704
- *
2705
- * ```js
2706
- * function f(x, y, z) {}
2707
- * var args = [1, 2, 3];
2708
- * f.apply(null, args);
2709
- * ```
2710
- *
2711
- * With `spread` this example can be re-written.
2712
- *
2713
- * ```js
2714
- * spread(function(x, y, z) {})([1, 2, 3]);
2715
- * ```
2716
- *
2717
- * @param {Function} callback
2718
- *
2719
- * @returns {Function}
2720
- */ function spread(callback) {
2721
- return function(arr) {
2722
- return callback.apply(null, arr);
2723
- };
2724
- }
2725
- /**
2726
- * Determines whether the payload is an error thrown by Axios
2727
- *
2728
- * @param {*} payload The value to test
2729
- *
2730
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2731
- */ function isAxiosError(payload) {
2732
- return utils.isObject(payload) && true === payload.isAxiosError;
2733
- }
2734
- const HttpStatusCode = {
2735
- Continue: 100,
2736
- SwitchingProtocols: 101,
2737
- Processing: 102,
2738
- EarlyHints: 103,
2739
- Ok: 200,
2740
- Created: 201,
2741
- Accepted: 202,
2742
- NonAuthoritativeInformation: 203,
2743
- NoContent: 204,
2744
- ResetContent: 205,
2745
- PartialContent: 206,
2746
- MultiStatus: 207,
2747
- AlreadyReported: 208,
2748
- ImUsed: 226,
2749
- MultipleChoices: 300,
2750
- MovedPermanently: 301,
2751
- Found: 302,
2752
- SeeOther: 303,
2753
- NotModified: 304,
2754
- UseProxy: 305,
2755
- Unused: 306,
2756
- TemporaryRedirect: 307,
2757
- PermanentRedirect: 308,
2758
- BadRequest: 400,
2759
- Unauthorized: 401,
2760
- PaymentRequired: 402,
2761
- Forbidden: 403,
2762
- NotFound: 404,
2763
- MethodNotAllowed: 405,
2764
- NotAcceptable: 406,
2765
- ProxyAuthenticationRequired: 407,
2766
- RequestTimeout: 408,
2767
- Conflict: 409,
2768
- Gone: 410,
2769
- LengthRequired: 411,
2770
- PreconditionFailed: 412,
2771
- PayloadTooLarge: 413,
2772
- UriTooLong: 414,
2773
- UnsupportedMediaType: 415,
2774
- RangeNotSatisfiable: 416,
2775
- ExpectationFailed: 417,
2776
- ImATeapot: 418,
2777
- MisdirectedRequest: 421,
2778
- UnprocessableEntity: 422,
2779
- Locked: 423,
2780
- FailedDependency: 424,
2781
- TooEarly: 425,
2782
- UpgradeRequired: 426,
2783
- PreconditionRequired: 428,
2784
- TooManyRequests: 429,
2785
- RequestHeaderFieldsTooLarge: 431,
2786
- UnavailableForLegalReasons: 451,
2787
- InternalServerError: 500,
2788
- NotImplemented: 501,
2789
- BadGateway: 502,
2790
- ServiceUnavailable: 503,
2791
- GatewayTimeout: 504,
2792
- HttpVersionNotSupported: 505,
2793
- VariantAlsoNegotiates: 506,
2794
- InsufficientStorage: 507,
2795
- LoopDetected: 508,
2796
- NotExtended: 510,
2797
- NetworkAuthenticationRequired: 511
2798
- };
2799
- Object.entries(HttpStatusCode).forEach(([key, value])=>{
2800
- HttpStatusCode[value] = key;
2801
- });
2802
- /* ESM default export */ const helpers_HttpStatusCode = HttpStatusCode;
2803
- /**
2804
- * Create an instance of Axios
2805
- *
2806
- * @param {Object} defaultConfig The default config for the instance
2807
- *
2808
- * @returns {Axios} A new instance of Axios
2809
- */ function createInstance(defaultConfig) {
2810
- const context = new Axios(defaultConfig);
2811
- const instance = bind(Axios.prototype.request, context);
2812
- // Copy axios.prototype to instance
2813
- utils.extend(instance, Axios.prototype, context, {
2814
- allOwnKeys: true
2815
- });
2816
- // Copy context to instance
2817
- utils.extend(instance, context, null, {
2818
- allOwnKeys: true
2819
- });
2820
- // Factory for creating new instances
2821
- instance.create = function(instanceConfig) {
2822
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2823
- };
2824
- return instance;
2825
- }
2826
- // Create the default instance to be exported
2827
- const axios = createInstance(defaults);
2828
- // Expose Axios class to allow class inheritance
2829
- axios.Axios = Axios;
2830
- // Expose Cancel & CancelToken
2831
- axios.CanceledError = CanceledError;
2832
- axios.CancelToken = CancelToken;
2833
- axios.isCancel = isCancel;
2834
- axios.VERSION = VERSION;
2835
- axios.toFormData = toFormData;
2836
- // Expose AxiosError class
2837
- axios.AxiosError = core_AxiosError;
2838
- // alias for CanceledError for backward compatibility
2839
- axios.Cancel = axios.CanceledError;
2840
- // Expose all/spread
2841
- axios.all = function(promises) {
2842
- return Promise.all(promises);
2843
- };
2844
- axios.spread = spread;
2845
- // Expose isAxiosError
2846
- axios.isAxiosError = isAxiosError;
2847
- // Expose mergeConfig
2848
- axios.mergeConfig = mergeConfig;
2849
- axios.AxiosHeaders = AxiosHeaders;
2850
- axios.formToJSON = (thing)=>formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
2851
- axios.getAdapter = adapters_adapters.getAdapter;
2852
- axios.HttpStatusCode = helpers_HttpStatusCode;
2853
- axios.default = axios;
2854
- // this module should only have a default export
2855
- /* ESM default export */ const lib_axios = axios;
2856
- // This module is intended to unwrap Axios default export as named.
2857
- // Keep top-level export same with static properties
2858
- // so that it can keep same with es module or cjs
2859
- 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;
2860
- // EXTERNAL MODULE: os (ignored)
2861
- var os_ignored_ = __webpack_require__("?e2b1");
2862
- // EXTERNAL MODULE: crypto (ignored)
2863
- __webpack_require__("?c628");
2864
- // EXTERNAL MODULE: jsonwebtoken (ignored)
2865
- __webpack_require__("?9452");
2866
- class APIResource {
2867
- constructor(client){
2868
- this._client = client;
2869
- }
2870
- }
2871
- /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource {
2872
- /**
2873
- * Create a new agent. | 调用接口创建一个新的智能体。
2874
- * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en
2875
- * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh
2876
- * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。
2877
- * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。
2878
- * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。
2879
- * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。
2880
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2881
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2882
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2883
- * @returns Information about the created bot. | 创建的 Bot 信息。
2884
- */ async create(params, options) {
2885
- const apiUrl = '/v1/bot/create';
2886
- const result = await this._client.post(apiUrl, params, false, options);
2887
- return result.data;
2888
- }
2889
- /**
2890
- * Update the configuration of an agent. | 调用接口修改智能体的配置。
2891
- * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en
2892
- * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh
2893
- * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。
2894
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。
2895
- * @param params.name - Optional The name of the agent. | Bot 的名称。
2896
- * @param params.description - Optional The description of the agent. | Bot 的描述信息。
2897
- * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。
2898
- * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。
2899
- * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。
2900
- * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。
2901
- * @returns Undefined | 无返回值
2902
- */ async update(params, options) {
2903
- const apiUrl = '/v1/bot/update';
2904
- const result = await this._client.post(apiUrl, params, false, options);
2905
- return result.data;
2906
- }
2907
- /**
2908
- * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。
2909
- * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en
2910
- * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh
2911
- * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。
2912
- * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。
2913
- * @param params.page_size - Optional Pagination size. | 分页大小。
2914
- * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。
2915
- * @returns List of published bots. | 已发布的 Bot 列表。
2916
- */ async list(params, options) {
2917
- const apiUrl = '/v1/space/published_bots_list';
2918
- const result = await this._client.get(apiUrl, params, false, options);
2919
- return result.data;
2920
- }
2921
- /**
2922
- * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。
2923
- * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en
2924
- * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh
2925
- * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。
2926
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。
2927
- * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。
2928
- * @returns Undefined | 无返回值
2929
- */ async publish(params, options) {
2930
- const apiUrl = '/v1/bot/publish';
2931
- const result = await this._client.post(apiUrl, params, false, options);
2932
- return result.data;
2933
- }
2934
- /**
2935
- * Get the configuration information of the agent. | 获取指定智能体的配置信息。
2936
- * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en
2937
- * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh
2938
- * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。
2939
- * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。
2940
- * @returns Information about the bot. | Bot 的配置信息。
2941
- */ async retrieve(params, options) {
2942
- const apiUrl = '/v1/bot/get_online_info';
2943
- const result = await this._client.get(apiUrl, params, false, options);
2944
- return result.data;
2945
- }
2946
- }
2947
- /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) {
2948
- let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '';
2949
- try {
2950
- return JSON.parse(jsonString);
2951
- } catch (error) {
2952
- return defaultValue;
2953
- }
2954
- }
2955
- function sleep(ms) {
2956
- return new Promise((resolve)=>{
2957
- setTimeout(resolve, ms);
2958
- });
2959
- }
2960
- function isBrowser() {
2961
- return 'undefined' != typeof window;
2962
- }
2963
- function esm_isPlainObject(obj) {
2964
- if ('object' != typeof obj || null === obj) return false;
2965
- const proto = Object.getPrototypeOf(obj);
2966
- if (null === proto) return true;
2967
- let baseProto = proto;
2968
- while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto);
2969
- return proto === baseProto;
2970
- }
2971
- function esm_mergeConfig() {
2972
- for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key];
2973
- return objects.reduce((result, obj)=>{
2974
- if (void 0 === obj) return result || {};
2975
- for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
2976
- if (esm_isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = esm_mergeConfig(result[key] || {}, obj[key]);
2977
- else result[key] = obj[key];
2978
- }
2979
- return result;
2980
- }, {});
2981
- }
2982
- function isPersonalAccessToken(token) {
2983
- return null == token ? void 0 : token.startsWith('pat_');
2984
- }
2985
- /* eslint-disable max-params */ class CozeError extends Error {
2986
- }
2987
- class APIError extends CozeError {
2988
- static makeMessage(status, errorBody, message, headers) {
2989
- if (!errorBody && message) return message;
2990
- if (errorBody) {
2991
- const list = [];
2992
- const { code, msg, error } = errorBody;
2993
- if (code) list.push(`code: ${code}`);
2994
- if (msg) list.push(`msg: ${msg}`);
2995
- if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`);
2996
- const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']);
2997
- if (logId) list.push(`logid: ${logId}`);
2998
- const help_doc = null == error ? void 0 : error.help_doc;
2999
- if (help_doc) list.push(`help doc: ${help_doc}`);
3000
- return list.join(', ');
3001
- }
3002
- if (status) return `http status code: ${status} (no body)`;
3003
- return '(no status code or body)';
3004
- }
3005
- static generate(status, errorResponse, message, headers) {
3006
- if (!status) return new APIConnectionError({
3007
- cause: castToError(errorResponse)
3008
- });
3009
- const error = errorResponse;
3010
- // https://www.coze.cn/docs/developer_guides/coze_error_codes
3011
- if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers);
3012
- if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers);
3013
- if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers);
3014
- if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers);
3015
- if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers);
3016
- if (408 === status) return new TimeoutError(status, error, message, headers);
3017
- if (502 === status) return new GatewayError(status, error, message, headers);
3018
- if (status >= 500) return new InternalServerError(status, error, message, headers);
3019
- return new APIError(status, error, message, headers);
3020
- }
3021
- constructor(status, error, message, headers){
3022
- var _error_error, _error_error1;
3023
- super(`${APIError.makeMessage(status, error, message, headers)}`);
3024
- this.status = status;
3025
- this.headers = headers;
3026
- this.logid = null == headers ? void 0 : headers['x-tt-logid'];
3027
- // this.error = error;
3028
- this.code = null == error ? void 0 : error.code;
3029
- this.msg = null == error ? void 0 : error.msg;
3030
- this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail;
3031
- this.help_doc = null == error ? void 0 : null === (_error_error1 = error.error) || void 0 === _error_error1 ? void 0 : _error_error1.help_doc;
3032
- this.rawError = error;
3033
- }
3034
- }
3035
- class APIConnectionError extends APIError {
3036
- constructor({ message, cause }){
3037
- super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0;
3038
- // if (cause) {
3039
- // this.cause = cause;
3040
- // }
3041
- }
3042
- }
3043
- class APIUserAbortError extends APIError {
3044
- constructor(message){
3045
- super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0;
3046
- }
3047
- }
3048
- class BadRequestError extends APIError {
3049
- constructor(...args){
3050
- super(...args), this.name = 'BadRequestError', this.status = 400;
3051
- }
3052
- }
3053
- class AuthenticationError extends APIError {
3054
- constructor(...args){
3055
- super(...args), this.name = 'AuthenticationError', this.status = 401;
3056
- }
3057
- }
3058
- class PermissionDeniedError extends APIError {
3059
- constructor(...args){
3060
- super(...args), this.name = 'PermissionDeniedError', this.status = 403;
3061
- }
3062
- }
3063
- class NotFoundError extends APIError {
3064
- constructor(...args){
3065
- super(...args), this.name = 'NotFoundError', this.status = 404;
3066
- }
3067
- }
3068
- class TimeoutError extends APIError {
3069
- constructor(...args){
3070
- super(...args), this.name = 'TimeoutError', this.status = 408;
3071
- }
3072
- }
3073
- class RateLimitError extends APIError {
3074
- constructor(...args){
3075
- super(...args), this.name = 'RateLimitError', this.status = 429;
3076
- }
3077
- }
3078
- class InternalServerError extends APIError {
3079
- constructor(...args){
3080
- super(...args), this.name = 'InternalServerError', this.status = 500;
3081
- }
3082
- }
3083
- class GatewayError extends APIError {
3084
- constructor(...args){
3085
- super(...args), this.name = 'GatewayError', this.status = 502;
3086
- }
3087
- }
3088
- const castToError = (err)=>{
3089
- if (err instanceof Error) return err;
3090
- return new Error(err);
3091
- };
3092
- class Messages extends APIResource {
3093
- /**
3094
- * Get the list of messages in a chat. | 获取对话中的消息列表。
3095
- * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en
3096
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh
3097
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3098
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3099
- * @returns An array of chat messages. | 对话消息数组。
3100
- */ async list(conversation_id, chat_id, options) {
3101
- const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3102
- const result = await this._client.get(apiUrl, void 0, false, options);
3103
- return result.data;
3104
- }
3105
- }
3106
- const uuid = ()=>(Math.random() * new Date().getTime()).toString();
3107
- const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({
3108
- ...i,
3109
- content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content
3110
- }));
3111
- class Chat extends APIResource {
3112
- /**
3113
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3114
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3115
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3116
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3117
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3118
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3119
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3120
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。
3121
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3122
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3123
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3124
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3125
- * @returns The data of the created chat. | 创建的对话数据。
3126
- */ async create(params, options) {
3127
- if (!params.user_id) params.user_id = uuid();
3128
- const { conversation_id, ...rest } = params;
3129
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3130
- const payload = {
3131
- ...rest,
3132
- additional_messages: handleAdditionalMessages(params.additional_messages),
3133
- stream: false
3134
- };
3135
- const result = await this._client.post(apiUrl, payload, false, options);
3136
- return result.data;
3137
- }
3138
- /**
3139
- * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文
3140
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3141
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3142
- * @param params - Required The parameters for creating a chat session. | 创建会话的参数。
3143
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3144
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3145
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3146
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3147
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3148
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3149
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3150
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3151
- * @returns
3152
- */ async createAndPoll(params, options) {
3153
- if (!params.user_id) params.user_id = uuid();
3154
- const { conversation_id, ...rest } = params;
3155
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3156
- const payload = {
3157
- ...rest,
3158
- additional_messages: handleAdditionalMessages(params.additional_messages),
3159
- stream: false
3160
- };
3161
- const result = await this._client.post(apiUrl, payload, false, options);
3162
- const chatId = result.data.id;
3163
- const conversationId = result.data.conversation_id;
3164
- let chat;
3165
- while(true){
3166
- await sleep(100);
3167
- chat = await this.retrieve(conversationId, chatId);
3168
- if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break;
3169
- }
3170
- const messageList = await this.messages.list(conversationId, chatId);
3171
- return {
3172
- chat,
3173
- messages: messageList
3174
- };
3175
- }
3176
- /**
3177
- * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。
3178
- * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en
3179
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh
3180
- * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。
3181
- * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。
3182
- * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。
3183
- * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。
3184
- * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。
3185
- * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。
3186
- * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。
3187
- * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。
3188
- * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。
3189
- * @returns A stream of chat data. | 对话数据流。
3190
- */ async *stream(params, options) {
3191
- if (!params.user_id) params.user_id = uuid();
3192
- const { conversation_id, ...rest } = params;
3193
- const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`;
3194
- const payload = {
3195
- ...rest,
3196
- additional_messages: handleAdditionalMessages(params.additional_messages),
3197
- stream: true
3198
- };
3199
- const result = await this._client.post(apiUrl, payload, true, options);
3200
- for await (const message of result)if ("done" === message.event) {
3201
- const ret = {
3202
- event: message.event,
3203
- data: '[DONE]'
3204
- };
3205
- yield ret;
3206
- } else try {
3207
- const ret = {
3208
- event: message.event,
3209
- data: JSON.parse(message.data)
3210
- };
3211
- yield ret;
3212
- } catch (error) {
3213
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3214
- }
3215
- }
3216
- /**
3217
- * Get the detailed information of the chat. | 查看对话的详细信息。
3218
- * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en
3219
- * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh
3220
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3221
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3222
- * @returns The data of the retrieved chat. | 检索到的对话数据。
3223
- */ async retrieve(conversation_id, chat_id, options) {
3224
- const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`;
3225
- const result = await this._client.post(apiUrl, void 0, false, options);
3226
- return result.data;
3227
- }
3228
- /**
3229
- * Cancel a chat session. | 取消对话会话。
3230
- * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en
3231
- * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh
3232
- * @param conversation_id - Required The ID of the conversation. | 会话 ID。
3233
- * @param chat_id - Required The ID of the chat. | 对话 ID。
3234
- * @returns The data of the canceled chat. | 取消的对话数据。
3235
- */ async cancel(conversation_id, chat_id, options) {
3236
- const apiUrl = '/v3/chat/cancel';
3237
- const payload = {
3238
- conversation_id,
3239
- chat_id
3240
- };
3241
- const result = await this._client.post(apiUrl, payload, false, options);
3242
- return result.data;
3243
- }
3244
- /**
3245
- * Submit tool outputs for a chat session. | 提交对话会话的工具输出。
3246
- * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en
3247
- * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh
3248
- * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。
3249
- * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。
3250
- * @param params.chat_id - Required The ID of the chat. | 对话 ID。
3251
- * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。
3252
- * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。
3253
- * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。
3254
- */ async *submitToolOutputs(params, options) {
3255
- const { conversation_id, chat_id, ...rest } = params;
3256
- const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`;
3257
- const payload = {
3258
- ...rest
3259
- };
3260
- if (false === params.stream) {
3261
- const response = await this._client.post(apiUrl, payload, false, options);
3262
- return response.data;
3049
+ } else err.stack = stack;
3050
+ } catch (e) {
3051
+ // ignore the case where "stack" is an un-writable property
3052
+ }
3053
+ }
3054
+ throw err;
3263
3055
  }
3264
- {
3265
- const result = await this._client.post(apiUrl, payload, true, options);
3266
- for await (const message of result)if ("done" === message.event) {
3267
- const ret = {
3268
- event: message.event,
3269
- data: '[DONE]'
3270
- };
3271
- yield ret;
3272
- } else try {
3273
- const ret = {
3274
- event: message.event,
3275
- data: JSON.parse(message.data)
3276
- };
3277
- yield ret;
3056
+ }
3057
+ _request(configOrUrl, config) {
3058
+ /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API
3059
+ if ('string' == typeof configOrUrl) {
3060
+ config = config || {};
3061
+ config.url = configOrUrl;
3062
+ } else config = configOrUrl || {};
3063
+ config = mergeConfig_mergeConfig(this.defaults, config);
3064
+ const { transitional, paramsSerializer, headers } = config;
3065
+ if (void 0 !== transitional) helpers_validator.assertOptions(transitional, {
3066
+ silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
3067
+ forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean),
3068
+ clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean)
3069
+ }, false);
3070
+ if (null != paramsSerializer) {
3071
+ if (utils.isFunction(paramsSerializer)) config.paramsSerializer = {
3072
+ serialize: paramsSerializer
3073
+ };
3074
+ else helpers_validator.assertOptions(paramsSerializer, {
3075
+ encode: Axios_validators.function,
3076
+ serialize: Axios_validators.function
3077
+ }, true);
3078
+ }
3079
+ // Set config.method
3080
+ config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3081
+ // Flatten headers
3082
+ let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
3083
+ headers && utils.forEach([
3084
+ 'delete',
3085
+ 'get',
3086
+ 'head',
3087
+ 'post',
3088
+ 'put',
3089
+ 'patch',
3090
+ 'common'
3091
+ ], (method)=>{
3092
+ delete headers[method];
3093
+ });
3094
+ config.headers = AxiosHeaders.concat(contextHeaders, headers);
3095
+ // filter out skipped interceptors
3096
+ const requestInterceptorChain = [];
3097
+ let synchronousRequestInterceptors = true;
3098
+ this.interceptors.request.forEach(function(interceptor) {
3099
+ if ('function' == typeof interceptor.runWhen && false === interceptor.runWhen(config)) return;
3100
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3101
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3102
+ });
3103
+ const responseInterceptorChain = [];
3104
+ this.interceptors.response.forEach(function(interceptor) {
3105
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3106
+ });
3107
+ let promise;
3108
+ let i = 0;
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);
3278
3130
  } catch (error) {
3279
- throw new CozeError(`Could not parse message into JSON:${message.data}`);
3131
+ onRejected.call(this, error);
3132
+ break;
3280
3133
  }
3281
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;
3282
3144
  }
3283
- constructor(...args){
3284
- 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);
3285
3149
  }
3286
3150
  }
3287
- var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) {
3288
- ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created";
3289
- ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress";
3290
- ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed";
3291
- ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed";
3292
- ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action";
3293
- ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta";
3294
- ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed";
3295
- ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta";
3296
- ChatEventType["DONE"] = "done";
3297
- ChatEventType["ERROR"] = "error";
3298
- return ChatEventType;
3299
- }({});
3300
- class messages_Messages extends APIResource {
3301
- /**
3302
- * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。
3303
- * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en
3304
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh
3305
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3306
- * @param params - Required The parameters for creating a message | 创建消息所需的参数
3307
- * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。
3308
- * @param params.content - Required The content of the message. | 消息的内容。
3309
- * @param params.content_type - Required The type of the message content. | 消息内容的类型。
3310
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3311
- * @returns Information about the new message. | 消息详情。
3312
- */ async create(conversation_id, params, options) {
3313
- const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`;
3314
- const response = await this._client.post(apiUrl, params, false, options);
3315
- return response.data;
3316
- }
3317
- /**
3318
- * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。
3319
- * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en
3320
- * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh
3321
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3322
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3323
- * @param params - Required The parameters for modifying a message | 修改消息所需的参数
3324
- * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。
3325
- * @param params.content - Optional The content of the message. | 消息的内容。
3326
- * @param params.content_type - Optional The type of the message content. | 消息内容的类型。
3327
- * @returns Information about the modified message. | 消息详情。
3328
- */ // eslint-disable-next-line max-params
3329
- async update(conversation_id, message_id, params, options) {
3330
- const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`;
3331
- const response = await this._client.post(apiUrl, params, false, options);
3332
- return response.message;
3333
- }
3334
- /**
3335
- * Get the detailed information of specified message. | 查看指定消息的详细信息。
3336
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en
3337
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh
3338
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3339
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3340
- * @returns Information about the message. | 消息详情。
3341
- */ async retrieve(conversation_id, message_id, options) {
3342
- const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`;
3343
- const response = await this._client.get(apiUrl, null, false, options);
3344
- 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
+ };
3345
3182
  }
3346
- /**
3347
- * List messages in a conversation. | 列出会话中的消息。
3348
- * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en
3349
- * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh
3350
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3351
- * @param params - Optional The parameters for listing messages | 列出消息所需的参数
3352
- * @param params.order - Optional The order of the messages. | 消息的顺序。
3353
- * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。
3354
- * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。
3355
- * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。
3356
- * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。
3357
- * @returns A list of messages. | 消息列表。
3358
- */ async list(conversation_id, params, options) {
3359
- const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`;
3360
- const response = await this._client.post(apiUrl, params, false, options);
3361
- 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
+ });
3362
3227
  }
3363
3228
  /**
3364
- * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。
3365
- * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en
3366
- * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh
3367
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3368
- * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。
3369
- * @returns Details of the deleted message. | 已删除的消息详情。
3370
- */ async delete(conversation_id, message_id, options) {
3371
- const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`;
3372
- const response = await this._client.post(apiUrl, void 0, false, options);
3373
- return response.data;
3229
+ * Throws a `CanceledError` if cancellation has been requested.
3230
+ */ throwIfRequested() {
3231
+ if (this.reason) throw this.reason;
3374
3232
  }
3375
- }
3376
- class Conversations extends APIResource {
3377
3233
  /**
3378
- * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。
3379
- * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en
3380
- * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh
3381
- * @param params - Required The parameters for creating a conversation | 创建会话所需的参数
3382
- * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。
3383
- * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。
3384
- * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。
3385
- * @returns Information about the created conversation. | 会话的基础信息。
3386
- */ async create(params, options) {
3387
- const apiUrl = '/v1/conversation/create';
3388
- const response = await this._client.post(apiUrl, params, false, options);
3389
- 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
+ ];
3390
3244
  }
3391
3245
  /**
3392
- * Get the information of specific conversation. | 通过会话 ID 查看会话信息。
3393
- * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en
3394
- * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh
3395
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3396
- * @returns Information about the conversation. | 会话的基础信息。
3397
- */ async retrieve(conversation_id, options) {
3398
- const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`;
3399
- const response = await this._client.get(apiUrl, null, false, options);
3400
- 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);
3401
3251
  }
3402
- /**
3403
- * List all conversations. | 列出 Bot 下所有会话。
3404
- * @param params
3405
- * @param params.bot_id - Required Bot ID. | Bot ID。
3406
- * @param params.page_num - Optional The page number. | 页码,默认值为 1。
3407
- * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。
3408
- * @returns Information about the conversations. | 会话的信息。
3409
- */ async list(params, options) {
3410
- const apiUrl = '/v1/conversations';
3411
- const response = await this._client.get(apiUrl, params, false, options);
3412
- 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;
3413
3260
  }
3414
3261
  /**
3415
- * Clear a conversation. | 清空会话。
3416
- * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。
3417
- * @returns Information about the conversation session. | 会话的会话 ID。
3418
- */ async clear(conversation_id, options) {
3419
- const apiUrl = `/v1/conversations/${conversation_id}/clear`;
3420
- const response = await this._client.post(apiUrl, null, false, options);
3421
- return response.data;
3422
- }
3423
- constructor(...args){
3424
- 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
+ };
3425
3273
  }
3426
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;
3427
3436
  class Files extends APIResource {
3428
3437
  /**
3429
3438
  * Upload files to Coze platform. | 调用接口上传文件到扣子。
@@ -3586,7 +3595,7 @@ class Documents extends APIResource {
3586
3595
  * @returns ListDocumentData | 知识库文件列表
3587
3596
  */ list(params, options) {
3588
3597
  const apiUrl = '/open_api/knowledge/document/list';
3589
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3598
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3590
3599
  headers: documents_headers
3591
3600
  }));
3592
3601
  return response;
@@ -3604,7 +3613,7 @@ class Documents extends APIResource {
3604
3613
  * @returns DocumentInfo[] | 已上传文件的基本信息
3605
3614
  */ async create(params, options) {
3606
3615
  const apiUrl = '/open_api/knowledge/document/create';
3607
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3616
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3608
3617
  headers: documents_headers
3609
3618
  }));
3610
3619
  return response.document_infos;
@@ -3620,7 +3629,7 @@ class Documents extends APIResource {
3620
3629
  * @returns void | 无返回
3621
3630
  */ async delete(params, options) {
3622
3631
  const apiUrl = '/open_api/knowledge/document/delete';
3623
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3632
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3624
3633
  headers: documents_headers
3625
3634
  }));
3626
3635
  }
@@ -3636,7 +3645,7 @@ class Documents extends APIResource {
3636
3645
  * @returns void | 无返回
3637
3646
  */ async update(params, options) {
3638
3647
  const apiUrl = '/open_api/knowledge/document/update';
3639
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3648
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3640
3649
  headers: documents_headers
3641
3650
  }));
3642
3651
  }
@@ -3664,7 +3673,7 @@ class documents_Documents extends APIResource {
3664
3673
  * @returns ListDocumentData | 知识库文件列表
3665
3674
  */ list(params, options) {
3666
3675
  const apiUrl = '/open_api/knowledge/document/list';
3667
- const response = this._client.get(apiUrl, params, false, esm_mergeConfig(options, {
3676
+ const response = this._client.get(apiUrl, params, false, mergeConfig(options, {
3668
3677
  headers: documents_documents_headers
3669
3678
  }));
3670
3679
  return response;
@@ -3680,7 +3689,7 @@ class documents_Documents extends APIResource {
3680
3689
  * @returns DocumentInfo[] | 已上传文件的基本信息
3681
3690
  */ async create(params, options) {
3682
3691
  const apiUrl = '/open_api/knowledge/document/create';
3683
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3692
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3684
3693
  headers: documents_documents_headers
3685
3694
  }));
3686
3695
  return response.document_infos;
@@ -3694,7 +3703,7 @@ class documents_Documents extends APIResource {
3694
3703
  * @returns void | 无返回
3695
3704
  */ async delete(params, options) {
3696
3705
  const apiUrl = '/open_api/knowledge/document/delete';
3697
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3706
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3698
3707
  headers: documents_documents_headers
3699
3708
  }));
3700
3709
  }
@@ -3708,7 +3717,7 @@ class documents_Documents extends APIResource {
3708
3717
  * @returns void | 无返回
3709
3718
  */ async update(params, options) {
3710
3719
  const apiUrl = '/open_api/knowledge/document/update';
3711
- await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3720
+ await this._client.post(apiUrl, params, false, mergeConfig(options, {
3712
3721
  headers: documents_documents_headers
3713
3722
  }));
3714
3723
  }
@@ -3772,7 +3781,7 @@ class Speech extends APIResource {
3772
3781
  * @returns Speech synthesis data
3773
3782
  */ async create(params, options) {
3774
3783
  const apiUrl = '/v1/audio/speech';
3775
- const response = await this._client.post(apiUrl, params, false, esm_mergeConfig(options, {
3784
+ const response = await this._client.post(apiUrl, params, false, mergeConfig(options, {
3776
3785
  responseType: 'arraybuffer'
3777
3786
  }));
3778
3787
  return response;
@@ -3785,23 +3794,26 @@ class Rooms extends APIResource {
3785
3794
  return response.data;
3786
3795
  }
3787
3796
  }
3788
- class esm_Audio extends APIResource {
3797
+ class audio_Audio extends APIResource {
3789
3798
  constructor(...args){
3790
3799
  super(...args), this.rooms = new Rooms(this._client), this.voices = new Voices(this._client), this.speech = new Speech(this._client);
3791
3800
  }
3792
3801
  }
3793
- var package_namespaceObject = JSON.parse('{"name":"@coze/api","version":"1.0.15","description":"Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中","keywords":["coze","ai","nodejs","sdk","chatbot","typescript"],"homepage":"https://github.com/coze-dev/coze-js/tree/main/packages/coze-js","bugs":{"url":"https://github.com/coze-dev/coze-js/issues"},"repository":{"type":"git","url":"https://github.com/coze-dev/coze-js.git","directory":"packages/coze-js"},"license":"MIT","author":"Leeight <leeight@gmail.com>","type":"module","exports":{".":{"require":"./dist/cjs/index.cjs","import":"./dist/esm/index.js","types":"./dist/types/index.d.ts"}},"main":"dist/cjs/index.cjs","module":"dist/esm/index.js","browser":{"crypto":false,"os":false,"jsonwebtoken":false},"types":"dist/types/index.d.ts","files":["dist","LICENSE","README.md","!**/*.tsbuildinfo"],"scripts":{"build":"rm -rf dist && rslib build","format":"prettier --write .","lint":"eslint ./ --cache --quiet","prepublishOnly":"npm run build","start":"rm -rf dist && rslib build -w","test":"vitest","test:cov":"vitest --coverage --run"},"dependencies":{"jsonwebtoken":"^9.0.2"},"devDependencies":{"@coze-infra/eslint-config":"workspace:*","@coze-infra/ts-config":"workspace:*","@coze-infra/vitest-config":"workspace:*","@rslib/core":"0.0.18","@swc/core":"^1.3.14","@types/jsonwebtoken":"^9.0.0","@types/node":"^20","@types/uuid":"^9.0.1","@types/whatwg-fetch":"^0.0.33","@vitest/coverage-v8":"~2.1.4","axios":"^1.7.7","typescript":"^5.5.3","vitest":"~2.1.4"},"peerDependencies":{"axios":"^1.7.1"}}'); // CONCATENATED MODULE: ./src/version.ts
3794
- 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.16-beta.1","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;
3795
3807
  const getEnv = ()=>{
3796
3808
  const nodeVersion = process.version.slice(1); // Remove 'v' prefix
3797
3809
  const { platform } = process;
3798
3810
  let osName = platform.toLowerCase();
3799
- let osVersion = os_ignored_.release();
3811
+ let osVersion = os_ignored_default().release();
3800
3812
  if ('darwin' === platform) {
3801
3813
  osName = 'macos';
3802
3814
  // Try to parse the macOS version
3803
3815
  try {
3804
- const darwinVersion = os_ignored_.release().split('.');
3816
+ const darwinVersion = os_ignored_default().release().split('.');
3805
3817
  if (darwinVersion.length >= 2) {
3806
3818
  const majorVersion = parseInt(darwinVersion[0], 10);
3807
3819
  if (!isNaN(majorVersion) && majorVersion >= 9) {
@@ -3814,10 +3826,10 @@ const getEnv = ()=>{
3814
3826
  }
3815
3827
  } else if ('win32' === platform) {
3816
3828
  osName = 'windows';
3817
- osVersion = os_ignored_.release();
3829
+ osVersion = os_ignored_default().release();
3818
3830
  } else if ('linux' === platform) {
3819
3831
  osName = 'linux';
3820
- osVersion = os_ignored_.release();
3832
+ osVersion = os_ignored_default().release();
3821
3833
  }
3822
3834
  return {
3823
3835
  osName,
@@ -3827,12 +3839,12 @@ const getEnv = ()=>{
3827
3839
  };
3828
3840
  const getUserAgent = ()=>{
3829
3841
  const { nodeVersion, osName, osVersion } = getEnv();
3830
- return `coze-js/${esm_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3842
+ return `coze-js/${version_version} node/${nodeVersion} ${osName}/${osVersion}`.toLowerCase();
3831
3843
  };
3832
3844
  const getNodeClientUserAgent = ()=>{
3833
3845
  const { osVersion, nodeVersion, osName } = getEnv();
3834
3846
  const ua = {
3835
- version: esm_version,
3847
+ version: version_version,
3836
3848
  lang: 'node',
3837
3849
  lang_version: nodeVersion,
3838
3850
  os_name: osName,
@@ -3840,15 +3852,17 @@ const getNodeClientUserAgent = ()=>{
3840
3852
  };
3841
3853
  return JSON.stringify(ua);
3842
3854
  };
3843
- /* eslint-disable @typescript-eslint/no-explicit-any */ const esm_handleError = (error)=>{
3855
+ /* eslint-disable @typescript-eslint/no-explicit-any */ const fetcher_handleError = (error)=>{
3844
3856
  if (!error.isAxiosError && (!error.code || !error.message)) return new CozeError(`Unexpected error: ${error.message}`);
3845
3857
  if ('ECONNABORTED' === error.code && error.message.includes('timeout') || 'ETIMEDOUT' === error.code) {
3846
3858
  var _error_response;
3847
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);
3848
3860
  }
3849
3861
  if ('ERR_CANCELED' === error.code) return new APIUserAbortError(error.message);
3850
- var _error_response1, _error_response2, _error_response3;
3851
- 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
+ }
3852
3866
  };
3853
3867
  async function fetchAPI(url) {
3854
3868
  let options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
@@ -3864,7 +3878,7 @@ async function fetchAPI(url) {
3864
3878
  adapter: options.isStreaming ? 'fetch' : void 0,
3865
3879
  ...options
3866
3880
  }).catch((error)=>{
3867
- throw esm_handleError(error);
3881
+ throw fetcher_handleError(error);
3868
3882
  });
3869
3883
  return {
3870
3884
  async *stream () {
@@ -3902,7 +3916,7 @@ async function fetchAPI(url) {
3902
3916
  buffer = lines[lines.length - 1]; // Keep the last incomplete line in the buffer
3903
3917
  }
3904
3918
  } catch (error) {
3905
- esm_handleError(error);
3919
+ fetcher_handleError(error);
3906
3920
  }
3907
3921
  },
3908
3922
  json: ()=>response.data,
@@ -3926,8 +3940,8 @@ function isAxiosStatic(instance) {
3926
3940
  }
3927
3941
  /**
3928
3942
  * default coze base URL is api.coze.com
3929
- */ const COZE_COM_BASE_URL = 'https://api.coze.com';
3930
- /* eslint-disable max-params */ class APIClient {
3943
+ */ const constant_COZE_COM_BASE_URL = 'https://api.coze.com';
3944
+ /* eslint-disable max-params */ class core_APIClient {
3931
3945
  async getToken() {
3932
3946
  if ('function' == typeof this.token) return await this.token();
3933
3947
  return this.token;
@@ -3937,11 +3951,11 @@ function isAxiosStatic(instance) {
3937
3951
  const headers = {
3938
3952
  authorization: `Bearer ${token}`
3939
3953
  };
3940
- if (!isBrowser()) {
3954
+ if (!utils_isBrowser()) {
3941
3955
  headers['User-Agent'] = getUserAgent();
3942
3956
  headers['X-Coze-Client-User-Agent'] = getNodeClientUserAgent();
3943
3957
  }
3944
- const config = esm_mergeConfig(this.axiosOptions, options, {
3958
+ const config = mergeConfig(this.axiosOptions, options, {
3945
3959
  headers
3946
3960
  });
3947
3961
  config.method = method;
@@ -3965,7 +3979,7 @@ function isAxiosStatic(instance) {
3965
3979
  if (contentType && contentType.includes('application/json')) {
3966
3980
  const result = await json();
3967
3981
  const { code, msg } = result;
3968
- 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);
3969
3983
  }
3970
3984
  return stream();
3971
3985
  }
@@ -3973,7 +3987,7 @@ function isAxiosStatic(instance) {
3973
3987
  {
3974
3988
  const result = await json();
3975
3989
  const { code, msg } = result;
3976
- 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);
3977
3991
  return result;
3978
3992
  }
3979
3993
  }
@@ -4005,31 +4019,35 @@ function isAxiosStatic(instance) {
4005
4019
  }
4006
4020
  constructor(config){
4007
4021
  this._config = config;
4008
- this.baseURL = config.baseURL || COZE_COM_BASE_URL;
4022
+ this.baseURL = config.baseURL || constant_COZE_COM_BASE_URL;
4009
4023
  this.token = config.token;
4010
4024
  this.axiosOptions = config.axiosOptions || {};
4011
4025
  this.axiosInstance = config.axiosInstance;
4012
4026
  this.debug = config.debug || false;
4013
4027
  this.allowPersonalAccessTokenInBrowser = config.allowPersonalAccessTokenInBrowser || false;
4014
4028
  this.headers = config.headers;
4015
- if (isBrowser() && 'function' != typeof this.token && isPersonalAccessToken(this.token) && !this.allowPersonalAccessTokenInBrowser) throw new CozeError('Browser environments do not support authentication using Personal Access Token (PAT) by default.\nas it may expose secret API keys. \n\nPlease use OAuth2.0 authentication mechanism. see:\nhttps://www.coze.com/docs/developer_guides/oauth_apps?_lang=en \n\nIf you need to force use, please set the `allowPersonalAccessTokenInBrowser` option to `true`. \n\ne.g new CozeAPI({ token, allowPersonalAccessTokenInBrowser: true });\n\n');
4016
- }
4017
- }
4018
- APIClient.APIError = APIError;
4019
- APIClient.BadRequestError = BadRequestError;
4020
- APIClient.AuthenticationError = AuthenticationError;
4021
- APIClient.PermissionDeniedError = PermissionDeniedError;
4022
- APIClient.NotFoundError = NotFoundError;
4023
- APIClient.RateLimitError = RateLimitError;
4024
- APIClient.InternalServerError = InternalServerError;
4025
- APIClient.GatewayError = GatewayError;
4026
- APIClient.TimeoutError = TimeoutError;
4027
- APIClient.UserAbortError = APIUserAbortError;
4028
- 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 {
4029
4047
  constructor(...args){
4030
4048
  super(...args), this.bots = new Bots(this), this.chat = new Chat(this), this.conversations = new Conversations(this), this.files = new Files(this), /**
4031
4049
  * @deprecated
4032
- */ this.knowledge = new Knowledge(this), this.datasets = new Datasets(this), this.workflows = new Workflows(this), this.workspaces = new WorkSpaces(this), this.audio = new esm_Audio(this);
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);
4033
4051
  }
4034
4052
  }
4035
4053
  /**
@@ -9261,7 +9279,7 @@ var setPrototypeOf = setPrototypeOf$2, _Object$setPrototypeOf = getDefaultExport
9261
9279
  }, stringPad = {
9262
9280
  start: createMethod(!1),
9263
9281
  end: createMethod(!0)
9264
- }, 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;
9265
9283
  $$F({
9266
9284
  target: "String",
9267
9285
  proto: !0,
@@ -38414,7 +38432,7 @@ var VERTC = _createClass(function e() {
38414
38432
  + * @param milliseconds The time to sleep in milliseconds
38415
38433
  + * @throws {Error} If milliseconds is negative
38416
38434
  + * @returns Promise that resolves after the specified duration
38417
- + */ const utils_sleep = (milliseconds)=>{
38435
+ + */ const src_utils_sleep = (milliseconds)=>{
38418
38436
  if (milliseconds < 0) throw new Error('Sleep duration must be non-negative');
38419
38437
  return new Promise((resolve)=>setTimeout(resolve, milliseconds));
38420
38438
  };