(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('dayjs'), require('@tencent-sdk/common'), require('@tencent-sdk/capi'), require('@tencent-sdk/cls')) :
    typeof define === 'function' && define.amd ? define(['exports', 'dayjs', '@tencent-sdk/common', '@tencent-sdk/capi', '@tencent-sdk/cls'], factory) :
    (factory((global.faas = {}),global.dayjs,global['@tencent-sdk/common'],global['@tencent-sdk/capi'],global['@tencent-sdk/cls']));
}(this, (function (exports,dayjs,common,capi,cls) { 'use strict';

    var dayjs__default = 'default' in dayjs ? dayjs['default'] : dayjs;

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */

    var __assign = function() {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };

    function __rest(s, e) {
        var t = {};
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
            t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }

    function __awaiter(thisArg, _arguments, P, generator) {
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

    function createCommonjsModule(fn, module) {
    	return module = { exports: {} }, fn(module, module.exports), module.exports;
    }

    var timezone = createCommonjsModule(function (module, exports) {
    !function(t,e){module.exports=e();}(commonjsGlobal,function(){var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,r){var o,u=r().utcOffset(),a=function(t,n,i){void 0===i&&(i={});var r=new Date(t);return function(t,n){void 0===n&&(n={});var i=n.timeZoneName||"short",r=t+"|"+i,o=e[r];return o||(o=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:i}),e[r]=o),o}(n,i).formatToParts(r)},f=function(e,n){for(var i=a(e,n),o=[],u=0;u<i.length;u+=1){var f=i[u],s=f.type,m=f.value,c=t[s];c>=0&&(o[c]=parseInt(m,10));}var d=o[3],v=24===d?0:d,h=o[0]+"-"+o[1]+"-"+o[2]+" "+v+":"+o[4]+":"+o[5]+":000",l=+e;return (r.utc(h).valueOf()-(l-=l%1e3))/6e4},s=i.prototype;s.tz=function(t,e){void 0===t&&(t=o);var n=this.utcOffset(),i=this.toDate().toLocaleString("en-US",{timeZone:t}),a=Math.round((this.toDate()-new Date(i))/1e3/60),f=r(i).$set("millisecond",this.$ms).utcOffset(u-a,!0);if(e){var s=f.utcOffset();f=f.add(n-s,"minute");}return f.$x.$timezone=t,f},s.offsetName=function(t){var e=this.$x.$timezone||r.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find(function(t){return "timezonename"===t.type.toLowerCase()});return n&&n.value};var m=s.startOf;s.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return m.call(this,t,e);var n=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"));return m.call(n,t,e).tz(this.$x.$timezone,!0)},r.tz=function(t,e,n){var i=n&&e,u=n||e||o,a=f(+r(),u);if("string"!=typeof t)return r(t).tz(u);var s=function(t,e,n){var i=t-60*e*1e3,r=f(i,n);if(e===r)return [i,e];var o=f(i-=60*(r-e)*1e3,n);return r===o?[i,r]:[t-60*Math.min(r,o)*1e3,Math.max(r,o)]}(r.utc(t,i).valueOf(),a,u),m=s[0],c=s[1],d=r(m).utcOffset(c);return d.$x.$timezone=u,d},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(t){o=t;};}});
    });

    var utc = createCommonjsModule(function (module, exports) {
    !function(t,i){module.exports=i();}(commonjsGlobal,function(){return function(t,i,e){var s=i.prototype;e.utc=function(t){return new i({date:t,utc:!0,args:arguments})},s.utc=function(t){var i=e(this.toDate(),{locale:this.$L,utc:!0});return t?i.add(this.utcOffset(),"minute"):i},s.local=function(){return e(this.toDate(),{locale:this.$L,utc:!1})};var f=s.parse;s.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),f.call(this,t);};var n=s.init;s.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds();}else n.call(this);};var u=s.utcOffset;s.utcOffset=function(t,i){var e=this.$utils().u;if(e(t))return this.$u?0:e(this.$offset)?u.call(this):this.$offset;var s=Math.abs(t)<=16?60*t:t,f=this;if(i)return f.$offset=s,f.$u=0===t,f;if(0!==t){var n=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(f=this.local().add(s+n,"minute")).$offset=s,f.$x.$localOffset=n;}else f=this.utc();return f};var o=s.format;s.format=function(t){var i=t||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return o.call(this,i)},s.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||(new Date).getTimezoneOffset());return this.$d.valueOf()-6e4*t},s.isUTC=function(){return !!this.$u},s.toISOString=function(){return this.toDate().toISOString()},s.toString=function(){return this.toDate().toUTCString()};var r=s.toDate;s.toDate=function(t){return "s"===t&&this.$offset?e(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():r.call(this)};var a=s.diff;s.diff=function(t,i,s){if(t&&this.$u===t.$u)return a.call(this,t,i,s);var f=this.local(),n=e(t).local();return a.call(f,n,i,s)};}});
    });

    dayjs__default.extend(timezone);
    dayjs__default.extend(utc);
    dayjs__default.tz.setDefault('Asia/Shanghai');
    var dtz = function (date) {
        if (date === void 0) { date = Date.now(); }
        return dayjs__default.tz(date);
    };
    var TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
    var TIME_FORMAT_TIMEZONE = 'YYYY-MM-DDTHH:mm:ssZ';
    function formatDate(date, withTimeout) {
        if (withTimeout === void 0) { withTimeout = false; }
        if (typeof date === 'number') {
            date = ("" + date).length === 10 ? date * 1000 : date;
        }
        return dtz(date).format(withTimeout ? TIME_FORMAT_TIMEZONE : TIME_FORMAT);
    }

    var ACTIONS = [
        'CreateFunction',
        'DeleteFunction',
        'GetFunction',
        'UpdateFunctionCode',
        'UpdateFunctionConfiguration',
        'CreateTrigger',
        'DeleteTrigger',
        'PublishVersion',
        'ListAliases',
        'CreateAlias',
        'UpdateAlias',
        'DeleteAlias',
        'GetAlias',
        'Invoke',
        'ListTriggers',
    ];
    var APIS = common.ApiFactory({
        serviceType: common.ServiceType.faas,
        version: '2018-04-16',
        actions: ACTIONS,
    });

    var StatusMap = {
        success: 'SCF_StatusCode=200',
        fail: 'SCF_StatusCode != 200 AND SCF_StatusCode != 202 AND SCF_StatusCode != 499',
        retry: 'SCF_RetryNum > 0',
        interrupt: 'SCF_StatusCode = 499',
        timeout: 'SCF_StatusCode = 433',
        exceed: 'SCF_StatusCode = 434',
        codeError: 'SCF_StatusCode = 500',
    };
    function formatWhere(_a) {
        var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c, status = _a.status, startTime = _a.startTime, endTime = _a.endTime;
        var where = "SCF_Namespace='" + namespace + "' AND SCF_Qualifier='" + qualifier + "'";
        if (startTime && endTime) {
            where += " AND (SCF_StartTime between " + startTime + " AND " + endTime + ")";
        }
        if (name) {
            where += " AND SCF_FunctionName='" + name + "'";
        }
        if (status) {
            where += " AND " + StatusMap[status] + "'";
        }
        return where;
    }
    function getSearchSql(options) {
        var where = formatWhere(options);
        var sql = "* | SELECT SCF_RequestId as requestId, SCF_RetryNum as retryNum, MAX(SCF_StartTime) as startTime WHERE " + where + " GROUP BY SCF_RequestId, SCF_RetryNum ORDER BY startTime desc";
        return sql;
    }

    var ACTIONS$1 = ['GetMonitorData'];
    var APIS$1 = common.ApiFactory({
        isV3: true,
        serviceType: common.ServiceType.monitor,
        version: '2018-07-24',
        actions: ACTIONS$1,
    });

    /**
     * 格式化监控数据
     * @param {MonitorData} data raw monitor data
     * @returns {FormatedMonitorData[]} 格式化后的监控数据
     */
    function formatMetricData(data) {
        var _a = data.DataPoints, DataPoints = _a === void 0 ? [] : _a;
        var list = [];
        DataPoints.forEach(function (point) {
            var _a = point.Timestamps, Timestamps = _a === void 0 ? [] : _a, _b = point.Values, Values = _b === void 0 ? [] : _b;
            Timestamps.forEach(function (time, i) {
                list.push({
                    time: formatDate(time),
                    value: Values[i],
                    timestamp: time,
                });
            });
        });
        return list;
    }
    var Monitor = /** @class */ (function () {
        function Monitor(_a) {
            var secretId = _a.secretId, secretKey = _a.secretKey, token = _a.token, _b = _a.region, region = _b === void 0 ? 'ap-guangzhou' : _b, _c = _a.debug, debug = _c === void 0 ? false : _c;
            this.credentials = {
                secretId: secretId,
                secretKey: secretKey,
                token: token,
            };
            this.region = region;
            this.capi = new capi.Capi({
                debug: debug,
                Region: region,
                ServiceType: common.ServiceType.monitor,
                SecretId: secretId,
                SecretKey: secretKey,
                Token: token,
            });
        }
        /**
         * 获取监控数据
         * @param {GetMonitorDataOptions} options 参数
         * @returns
         */
        Monitor.prototype.get = function (options) {
            return __awaiter(this, void 0, void 0, function () {
                var metric, name, _a, namespace, alias, _b, period, _c, interval, startTime, _d, endTime, _e, isRaw, endDate, startDate, formatedStartTime, formatedEndTime, dimensions, res;
                return __generator(this, function (_f) {
                    switch (_f.label) {
                        case 0:
                            metric = options.metric, name = options.name, _a = options.namespace, namespace = _a === void 0 ? 'default' : _a, alias = options.alias, _b = options.period, period = _b === void 0 ? 60 : _b, _c = options.interval, interval = _c === void 0 ? 900 : _c, startTime = options.startTime, _d = options.endTime, endTime = _d === void 0 ? Date.now() : _d, _e = options.isRaw, isRaw = _e === void 0 ? false : _e;
                            endDate = dtz(endTime);
                            startDate = startTime
                                ? dtz(startTime)
                                : endDate.add(0 - interval, 'second');
                            formatedStartTime = formatDate(startDate, true);
                            formatedEndTime = formatDate(endDate, true);
                            dimensions = [
                                {
                                    Name: 'namespace',
                                    Value: namespace,
                                },
                                {
                                    Name: 'functionName',
                                    Value: name,
                                },
                            ];
                            if (alias) {
                                dimensions.push({
                                    Name: 'alias',
                                    Value: alias,
                                });
                            }
                            return [4 /*yield*/, this.request({
                                    MetricName: metric,
                                    Action: 'GetMonitorData',
                                    Namespace: 'QCE/SCF_V2',
                                    Instances: [
                                        {
                                            Dimensions: dimensions,
                                        },
                                    ],
                                    Period: period,
                                    StartTime: formatedStartTime,
                                    EndTime: formatedEndTime,
                                })];
                        case 1:
                            res = _f.sent();
                            return [2 /*return*/, isRaw ? res : formatMetricData(res)];
                    }
                });
            });
        };
        Monitor.prototype.request = function (_a) {
            var Action = _a.Action, data = __rest(_a, ["Action"]);
            return __awaiter(this, void 0, void 0, function () {
                var result;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, APIS$1[Action](this.capi, common.pascalCaseProps(data))];
                        case 1:
                            result = _b.sent();
                            return [2 /*return*/, result];
                    }
                });
            });
        };
        return Monitor;
    }());

    (function (LogType) {
        LogType["none"] = "None";
        LogType["tail"] = "Tail";
    })(exports.LogType || (exports.LogType = {}));
    (function (InvokeType) {
        InvokeType["request"] = "RequestResponse";
        InvokeType["event"] = "Event";
    })(exports.InvokeType || (exports.InvokeType = {}));

    var FaaS = /** @class */ (function () {
        function FaaS(_a) {
            var secretId = _a.secretId, secretKey = _a.secretKey, token = _a.token, _b = _a.region, region = _b === void 0 ? 'ap-guangzhou' : _b, _c = _a.debug, debug = _c === void 0 ? false : _c;
            this.credentials = {
                secretId: secretId,
                secretKey: secretKey,
                token: token,
            };
            this.region = region;
            this.capi = new capi.Capi({
                debug: debug,
                Region: region,
                ServiceType: common.ServiceType.faas,
                SecretId: secretId,
                SecretKey: secretKey,
                Token: token,
            });
            this.cls = new cls.Cls({
                debug: debug,
                region: this.region,
                secretId: secretId,
                secretKey: secretKey,
                token: token,
            });
            this.monitor = new Monitor({
                debug: debug,
                region: this.region,
                secretId: secretId,
                secretKey: secretKey,
                token: token,
            });
            // 函数 CLS 配置缓存
            this.clsConfigCache = {};
        }
        /**
         * 设置当前地域
         * @param {string} region 地区
         */
        FaaS.prototype.setRegion = function (region) {
            this.region = region;
            this.capi.options.Region = region;
            this.cls.options.region = region;
        };
        /**
         * 获取当前地域
         * @returns {string} 地域
         */
        FaaS.prototype.getRegion = function () {
            return this.region;
        };
        FaaS.prototype.request = function (_a) {
            var Action = _a.Action, data = __rest(_a, ["Action"]);
            return __awaiter(this, void 0, void 0, function () {
                var result;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, APIS[Action](this.capi, common.pascalCaseProps(data))];
                        case 1:
                            result = _b.sent();
                            return [2 /*return*/, result];
                    }
                });
            });
        };
        /**
         *  获取 faas 详情
         * @param {GetFaasOptions} options 参数
         * @returns {Promise<FunctionInfo | null>} 函数详情，如果不存在则返回 null
         */
        FaaS.prototype.get = function (_a) {
            var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c, _d = _a.showCode, showCode = _d === void 0 ? false : _d, _e = _a.showTriggers, showTriggers = _e === void 0 ? false : _e;
            return __awaiter(this, void 0, void 0, function () {
                var Response_1, e_1;
                return __generator(this, function (_f) {
                    switch (_f.label) {
                        case 0:
                            _f.trys.push([0, 2, , 3]);
                            return [4 /*yield*/, this.request({
                                    Action: 'GetFunction',
                                    FunctionName: name,
                                    Namespace: namespace,
                                    Qualifier: qualifier,
                                    ShowCode: showCode ? 'TRUE' : 'FALSE',
                                    ShowTriggers: showTriggers ? 'TRUE' : 'FALSE',
                                })];
                        case 1:
                            Response_1 = _f.sent();
                            return [2 /*return*/, Response_1];
                        case 2:
                            e_1 = _f.sent();
                            if (e_1.code == 'ResourceNotFound.FunctionName' ||
                                e_1.code == 'ResourceNotFound.Function') {
                                return [2 /*return*/, null];
                            }
                            throw new common.CommonError({
                                type: 'API_FAAS_GetFunction',
                                message: e_1.message,
                                stack: e_1.stack,
                                reqId: e_1.reqId,
                                code: e_1.code,
                            });
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * 调用函数
         * @param {InvokeOptions} options 参数
         * @returns {Promise<InvokeResult>} 函数执行结果
         */
        FaaS.prototype.invoke = function (_a) {
            var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c, _d = _a.event, event = _d === void 0 ? {} : _d, _e = _a.logType, logType = _e === void 0 ? exports.LogType.tail : _e, _f = _a.invokeType, invokeType = _f === void 0 ? exports.InvokeType.request : _f;
            return __awaiter(this, void 0, void 0, function () {
                var detail, Result;
                return __generator(this, function (_g) {
                    switch (_g.label) {
                        case 0: return [4 /*yield*/, this.get({
                                name: name,
                                namespace: namespace,
                                qualifier: qualifier,
                            })];
                        case 1:
                            detail = _g.sent();
                            if (!detail) {
                                throw new common.CommonError({
                                    type: 'API_FAAS_get',
                                    code: "1001",
                                    message: "[FAAS] \u65E0\u6CD5\u627E\u5230\u6307\u5B9A\u51FD\u6570\uFF0C\u8BF7\u90E8\u7F72\u540E\u8C03\u7528\u6216\u68C0\u67E5\u51FD\u6570\u540D\u79F0",
                                });
                            }
                            return [4 /*yield*/, this.request({
                                    Action: 'Invoke',
                                    FunctionName: name,
                                    Namespace: namespace,
                                    Qualifier: qualifier,
                                    ClientContext: JSON.stringify(event),
                                    LogType: logType,
                                    InvocationType: invokeType,
                                })];
                        case 2:
                            Result = (_g.sent()).Result;
                            return [2 /*return*/, common.camelCaseProps(Result)];
                    }
                });
            });
        };
        /**
         * 获取 faas 的 CLS 配置
         * @param {FaasBaseConfig} options 参数
         * @returns {Promise<ClsConfig>} 函数 CLS 配置
         */
        FaaS.prototype.getClsConfig = function (_a) {
            var name = _a.name, _b = _a.namespace, namespace = _b === void 0 ? 'default' : _b, _c = _a.qualifier, qualifier = _c === void 0 ? '$LATEST' : _c;
            return __awaiter(this, void 0, void 0, function () {
                var cacheKey, detail, clsConfig;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            cacheKey = name + "-" + namespace + "-" + qualifier;
                            if (this.clsConfigCache[cacheKey]) {
                                return [2 /*return*/, this.clsConfigCache[cacheKey]];
                            }
                            return [4 /*yield*/, this.get({
                                    name: name,
                                    namespace: namespace,
                                    qualifier: qualifier,
                                })];
                        case 1:
                            detail = _d.sent();
                            if (!detail) {
                                throw new common.CommonError({
                                    type: 'API_FAAS_get',
                                    code: "1001",
                                    message: "[FAAS] \u65E0\u6CD5\u627E\u5230\u6307\u5B9A\u51FD\u6570\uFF0C\u8BF7\u90E8\u7F72\u540E\u8C03\u7528\u6216\u68C0\u67E5\u51FD\u6570\u540D\u79F0",
                                });
                            }
                            clsConfig = {
                                logsetId: detail.ClsLogsetId,
                                topicId: detail.ClsTopicId,
                            };
                            this.clsConfigCache[cacheKey] = clsConfig;
                            return [2 /*return*/, clsConfig];
                    }
                });
            });
        };
        /**
         * 获取函数日志列表，默认 近1个小时
         * 注意如果同时定义了 startTime 和 endTime，interval 参数将不起作用
         * @param {GetLogOptions} options 参数
         * @returns {Promise<SearchLogItem[]>} 日志列表
         */
        FaaS.prototype.getLogList = function (_a) {
            var name = _a.name, namespace = _a.namespace, qualifier = _a.qualifier, status = _a.status, _b = _a.endTime, endTime = _b === void 0 ? Date.now() : _b, _c = _a.interval, interval = _c === void 0 ? 600 : _c, _d = _a.limit, limit = _d === void 0 ? 10 : _d, startTime = _a.startTime;
            return __awaiter(this, void 0, void 0, function () {
                var _e, logsetId, topicId, startDate, endDate, sql, searchParameters, _f, results, logs, _loop_1, this_1, i, len;
                return __generator(this, function (_g) {
                    switch (_g.label) {
                        case 0: return [4 /*yield*/, this.getClsConfig({
                                name: name,
                                namespace: namespace,
                                qualifier: qualifier,
                            })];
                        case 1:
                            _e = _g.sent(), logsetId = _e.logsetId, topicId = _e.topicId;
                            if (!logsetId || !topicId) {
                                throw new common.CommonError({
                                    type: 'API_FAAS_getClsConfig',
                                    code: "1002",
                                    message: "[FAAS] \u65E0\u6CD5\u83B7\u53D6\u51FD\u6570 CLS \u914D\u7F6E\uFF0C\u8BF7\u68C0\u67E5\u51FD\u6570\u662F\u5426\u914D\u7F6E CLS \u529F\u80FD",
                                });
                            }
                            // 默认获取从当前到一个小时前时间段的日志
                            if (!endTime) {
                                endDate = dtz();
                            }
                            else {
                                endDate = dtz(endTime);
                            }
                            if (!startTime) {
                                startDate = dtz(endDate.valueOf() - Number(interval) * 1000);
                            }
                            else {
                                startDate = dtz(startTime);
                            }
                            sql = getSearchSql({
                                name: name,
                                namespace: namespace,
                                qualifier: qualifier,
                                status: status,
                                startTime: startDate.valueOf(),
                                endTime: endDate.valueOf(),
                            });
                            searchParameters = {
                                logset_id: logsetId,
                                topic_ids: topicId,
                                start_time: startDate.format(TIME_FORMAT),
                                end_time: endDate.format(TIME_FORMAT),
                                query_string: sql,
                                limit: limit || 10,
                                sort: 'desc',
                            };
                            return [4 /*yield*/, this.cls.searchLog(searchParameters)];
                        case 2:
                            _f = (_g.sent()).results, results = _f === void 0 ? [] : _f;
                            logs = [];
                            _loop_1 = function (i, len) {
                                var curReq, detailLog;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            curReq = results[i];
                                            curReq.startTime = formatDate(curReq.startTime);
                                            return [4 /*yield*/, this_1.getLogDetail({
                                                    logsetId: logsetId,
                                                    topicId: topicId,
                                                    reqId: curReq.requestId,
                                                    startTime: startDate.format(TIME_FORMAT),
                                                    endTime: endDate.format(TIME_FORMAT),
                                                })];
                                        case 1:
                                            detailLog = _a.sent();
                                            curReq.message = (detailLog || [])
                                                .map(function (_a) {
                                                var content = _a.content;
                                                try {
                                                    var info = JSON.parse(content);
                                                    if (info.SCF_Type === 'Custom') {
                                                        curReq.memoryUsage = info.SCF_MemUsage;
                                                        curReq.duration = info.SCF_Duration;
                                                    }
                                                    return info.SCF_Message;
                                                }
                                                catch (e) {
                                                    return '';
                                                }
                                            })
                                                .join('');
                                            logs.push(curReq);
                                            return [2 /*return*/];
                                    }
                                });
                            };
                            this_1 = this;
                            i = 0, len = results.length;
                            _g.label = 3;
                        case 3:
                            if (!(i < len)) return [3 /*break*/, 6];
                            return [5 /*yield**/, _loop_1(i, len)];
                        case 4:
                            _g.sent();
                            _g.label = 5;
                        case 5:
                            i++;
                            return [3 /*break*/, 3];
                        case 6: return [2 /*return*/, logs];
                    }
                });
            });
        };
        /**
         * 获取请求 ID日志详情，包含多条日志（流式日志），需要自定义拼接
         * @param {GetLogDetailOptions} options 参数
         * @returns {Promise<SearchLogDetailItem[]>} 日志详情列表
         */
        FaaS.prototype.getLogDetail = function (_a) {
            var startTime = _a.startTime, logsetId = _a.logsetId, topicId = _a.topicId, reqId = _a.reqId, _b = _a.endTime, endTime = _b === void 0 ? formatDate(Date.now()) : _b;
            return __awaiter(this, void 0, void 0, function () {
                var sql, searchParameters, _c, results;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            startTime =
                                startTime ||
                                    dtz(endTime)
                                        .add(-1, 'hour')
                                        .format(TIME_FORMAT);
                            sql = "SCF_RequestId:" + reqId + " AND SCF_RetryNum:0";
                            searchParameters = {
                                logset_id: logsetId,
                                topic_ids: topicId,
                                start_time: startTime,
                                end_time: endTime,
                                query_string: sql,
                                limit: 100,
                                sort: 'asc',
                            };
                            return [4 /*yield*/, this.cls.searchLog(searchParameters)];
                        case 1:
                            _c = (_d.sent()).results, results = _c === void 0 ? [] : _c;
                            return [2 /*return*/, results];
                    }
                });
            });
        };
        /**
         * 通过请求 ID 获取日志详情
         * @param {GetLogOptions} options 参数
         * @returns {Promise<SearchLogItem>} 单条日志详情
         */
        FaaS.prototype.getLogByReqId = function (_a) {
            var name = _a.name, namespace = _a.namespace, qualifier = _a.qualifier, _b = _a.endTime, endTime = _b === void 0 ? Date.now() : _b, reqId = _a.reqId;
            return __awaiter(this, void 0, void 0, function () {
                var _c, logsetId, topicId, endDate, detailLog, curReq;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0: return [4 /*yield*/, this.getClsConfig({
                                name: name,
                                namespace: namespace,
                                qualifier: qualifier,
                            })];
                        case 1:
                            _c = _d.sent(), logsetId = _c.logsetId, topicId = _c.topicId;
                            if (!logsetId || !topicId) {
                                throw new common.CommonError({
                                    type: 'API_FAAS_getLogByReqId',
                                    code: "1002",
                                    message: "[FAAS] \u65E0\u6CD5\u83B7\u53D6\u51FD\u6570 CLS \u914D\u7F6E\uFF0C\u8BF7\u68C0\u67E5\u51FD\u6570\u662F\u5426\u914D\u7F6E CLS \u529F\u80FD",
                                });
                            }
                            if (!reqId) {
                                throw new common.CommonError({
                                    type: 'API_FAAS_getLogByReqId',
                                    code: "1003",
                                    message: "[FAAS] \u53C2\u6570 reqId(\u8BF7\u6C42 ID) \u65E0\u6548",
                                });
                            }
                            endDate = dayjs__default(endTime);
                            console.log("[FAAS] \u901A\u8FC7\u8BF7\u6C42 ID \u83B7\u53D6\u65E5\u5FD7: " + reqId);
                            return [4 /*yield*/, this.getLogDetail({
                                    logsetId: logsetId,
                                    topicId: topicId,
                                    reqId: reqId,
                                    endTime: formatDate(endDate),
                                })];
                        case 2:
                            detailLog = _d.sent();
                            curReq = {
                                requestId: reqId,
                                retryNum: 0,
                                startTime: '',
                                memoryUsage: '',
                                duration: '',
                                message: '',
                            };
                            curReq.message = (detailLog || [])
                                .map(function (_a) {
                                var content = _a.content, timestamp = _a.timestamp;
                                try {
                                    var info = JSON.parse(content);
                                    if (info.SCF_Type === 'Custom') {
                                        curReq.memoryUsage = info.SCF_MemUsage;
                                        curReq.duration = info.SCF_Duration;
                                        curReq.startTime = timestamp;
                                    }
                                    return info.SCF_Message;
                                }
                                catch (e) {
                                    return '';
                                }
                            })
                                .join('');
                            return [2 /*return*/, curReq];
                    }
                });
            });
        };
        /**
         * 获取监控数据，默认获取 Invocation 指标
         * @param {GetMonitorDataOptions} options 参数
         * @returns
         */
        FaaS.prototype.getMetric = function (_a) {
            var _b = _a.metric, metric = _b === void 0 ? 'Invocation' : _b, rest = __rest(_a, ["metric"]);
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_c) {
                    return [2 /*return*/, this.monitor.get(__assign({ metric: metric }, rest))];
                });
            });
        };
        return FaaS;
    }());

    exports.FaaS = FaaS;
    exports.Monitor = Monitor;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=index.js.map
