var _a;
import { __awaiter, __generator } from "tslib";
import { isServer } from '../../core/environment';
import { loadScript } from '../../lib/load-script';
export var path = (_a = process.env.LEGACY_INTEGRATIONS_PATH) !== null && _a !== void 0 ? _a : 'https://cdn.segment.com/next-integrations';
export function remoteMiddlewares(ctx, settings) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var remoteMiddleware, names, scripts, middleware;
        var _this = this;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (isServer()) {
                        return [2 /*return*/, []];
                    }
                    remoteMiddleware = (_a = settings.enabledMiddleware) !== null && _a !== void 0 ? _a : {};
                    names = Object.keys(remoteMiddleware);
                    scripts = names.map(function (name) { return __awaiter(_this, void 0, void 0, function () {
                        var nonNamespaced, fullPath, error_1;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    nonNamespaced = name.replace('@segment/', '');
                                    fullPath = path + "/middleware/" + nonNamespaced + "/latest/" + nonNamespaced + ".js.gz";
                                    _a.label = 1;
                                case 1:
                                    _a.trys.push([1, 3, , 4]);
                                    return [4 /*yield*/, loadScript(fullPath)
                                        // @ts-ignore
                                    ];
                                case 2:
                                    _a.sent();
                                    // @ts-ignore
                                    return [2 /*return*/, window[nonNamespaced + "Middleware"]];
                                case 3:
                                    error_1 = _a.sent();
                                    ctx.log('error', error_1);
                                    ctx.stats.increment('failed_remote_middleware');
                                    return [3 /*break*/, 4];
                                case 4: return [2 /*return*/];
                            }
                        });
                    }); });
                    return [4 /*yield*/, Promise.all(scripts)];
                case 1:
                    middleware = _b.sent();
                    middleware = middleware.filter(Boolean);
                    return [2 /*return*/, middleware];
            }
        });
    });
}
//# sourceMappingURL=index.js.map