@coze/realtime-api 1.0.4 → 1.0.5-alpha.126a93

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