import { __awaiter, __generator } from "tslib";
import jsdom, { JSDOM } from 'jsdom';
import { AnalyticsBrowser } from '../browser';
import { snippet } from '../tester/__fixtures__/segment-snippet';
import { pWhile } from '../lib/p-while';
import { mocked } from 'ts-jest/utils';
import unfetch from 'unfetch';
import { RemoteMetrics } from '../core/stats/remote-metrics';
var cdnResponse = {
    integrations: {
        Zapier: {
            type: 'server',
        },
        'Amazon S3': {},
        Amplitude: {
            type: 'browser',
        },
        Segmentio: {
            type: 'browser',
        },
        Iterable: {
            type: 'browser',
            name: 'Iterable',
        },
    },
};
var fetchSettings = Promise.resolve({
    json: function () { return Promise.resolve(cdnResponse); },
});
jest.mock('unfetch', function () {
    return jest.fn();
});
describe('standalone bundle', function () {
    var segmentDotCom = "zaySL4FGIiLsxt3I7omU5uLxXqxaBMPh";
    var jsd;
    beforeEach(function () {
        jest.restoreAllMocks();
        jest.resetAllMocks();
        jest.spyOn(console, 'warn').mockImplementationOnce(function () { });
        // @ts-ignore ignore Response required fields
        mocked(unfetch).mockImplementation(function () { return fetchSettings; });
        var html = ("\n    <!DOCTYPE html>\n      <head>\n        <script>\n          " + snippet(segmentDotCom, true) + "\n        </script>\n      </head>\n      <body>\n      </body>\n    </html>\n    ").trim();
        var virtualConsole = new jsdom.VirtualConsole();
        jsd = new JSDOM(html, {
            runScripts: 'dangerously',
            resources: 'usable',
            url: 'https://segment.com',
            virtualConsole: virtualConsole,
        });
        var windowSpy = jest.spyOn(global, 'window', 'get');
        var documentSpy = jest.spyOn(global, 'document', 'get');
        jest.spyOn(console, 'warn').mockImplementationOnce(function () { });
        windowSpy.mockImplementation(function () {
            return jsd.window;
        });
        documentSpy.mockImplementation(function () { return jsd.window.document; });
    });
    it('catches initialization errors and reports them', function () { return __awaiter(void 0, void 0, void 0, function () {
        var errorMessages, metrics;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    window.analyticsWriteKey = 'write_key_abc_123';
                    errorMessages = [];
                    metrics = [];
                    jest.spyOn(console, 'error').mockImplementationOnce(function () {
                        var args = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            args[_i] = arguments[_i];
                        }
                        errorMessages.push(args.join(','));
                    });
                    jest
                        .spyOn(RemoteMetrics.prototype, 'increment')
                        .mockImplementationOnce(function (metric, tags) {
                        metrics.push({
                            metric: metric,
                            tags: tags,
                        });
                    });
                    jest
                        .spyOn(AnalyticsBrowser, 'standalone')
                        .mockRejectedValueOnce(new Error('Ohhh nooo'));
                    return [4 /*yield*/, import('../standalone')];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, pWhile(function () { return errorMessages.length === 0; }, function () { })];
                case 2:
                    _a.sent();
                    expect(metrics).toMatchInlineSnapshot("\n      Array [\n        Object {\n          \"metric\": \"analytics_js.invoke.error\",\n          \"tags\": Array [\n            \"type:initialization\",\n            \"message:Ohhh nooo\",\n            \"name:Error\",\n            \"host:segment.com\",\n            \"wk:write_key_abc_123\",\n          ],\n        },\n      ]\n    ");
                    expect(errorMessages).toMatchInlineSnapshot("\n      Array [\n        \"[analytics.js],Failed to load Analytics.js,Error: Ohhh nooo\",\n      ]\n    ");
                    return [2 /*return*/];
            }
        });
    }); });
});
//# sourceMappingURL=standalone-errors.test.js.map