import { __awaiter, __generator } from "tslib";
import jsdom, { JSDOM } from 'jsdom';
import { AnalyticsBrowser, loadLegacySettings } from '../browser';
import { snippet } from '../tester/__fixtures__/segment-snippet';
import { install } from '../standalone-analytics';
import { mocked } from 'ts-jest/utils';
import unfetch from 'unfetch';
var track = jest.fn();
var identify = jest.fn();
var page = jest.fn();
var setAnonymousId = jest.fn();
var register = jest.fn();
jest.mock('../analytics', function () { return ({
    Analytics: function () { return ({
        track: track,
        identify: identify,
        page: page,
        setAnonymousId: setAnonymousId,
        register: register,
        emit: jest.fn(),
    }); },
}); });
var fetchSettings = Promise.resolve({
    json: function () {
        return Promise.resolve({
            integrations: {},
        });
    },
});
jest.mock('unfetch', function () {
    return jest.fn();
});
describe('standalone bundle', function () {
    var segmentDotCom = "zaySL4FGIiLsxt3I7omU5uLxXqxaBMPh";
    beforeEach(function () { return __awaiter(void 0, void 0, void 0, function () {
        var html, virtualConsole, jsd, windowSpy, documentSpy;
        return __generator(this, function (_a) {
            jest.restoreAllMocks();
            jest.resetAllMocks();
            html = ("\n    <!DOCTYPE html>\n      <head>\n        <script>\n          " + snippet(segmentDotCom, true, "\n            window.analytics.track('fruit basket', { fruits: ['\uD83C\uDF4C', '\uD83C\uDF47'] })\n            window.analytics.identify('netto', { employer: 'segment' })\n            window.analytics.setAnonymousId('anonNetto')\n          ") + "\n        </script>\n      </head>\n      <body>\n      </body>\n    </html>\n    ").trim();
            virtualConsole = new jsdom.VirtualConsole();
            jsd = new JSDOM(html, {
                runScripts: 'dangerously',
                resources: 'usable',
                url: 'https://segment.com',
                virtualConsole: virtualConsole,
            });
            windowSpy = jest.spyOn(global, 'window', 'get');
            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; });
            return [2 /*return*/];
        });
    }); });
    it('detects embedded write keys', function () { return __awaiter(void 0, void 0, void 0, function () {
        var fakeAjs, spy;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    window.analyticsWriteKey = 'write_key_abc_123';
                    fakeAjs = {
                        ready: function (cb) { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                cb();
                                return [2 /*return*/];
                            });
                        }); },
                    };
                    spy = jest
                        .spyOn(AnalyticsBrowser, 'standalone')
                        .mockResolvedValueOnce(fakeAjs);
                    return [4 /*yield*/, install()];
                case 1:
                    _a.sent();
                    expect(spy).toHaveBeenCalledWith('write_key_abc_123', {});
                    return [2 /*return*/];
            }
        });
    }); });
    it('derives the write key from scripts on the page', function () { return __awaiter(void 0, void 0, void 0, function () {
        var fakeAjs, spy;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    fakeAjs = {
                        ready: function (cb) { return __awaiter(void 0, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                cb();
                                return [2 /*return*/];
                            });
                        }); },
                    };
                    spy = jest
                        .spyOn(AnalyticsBrowser, 'standalone')
                        .mockResolvedValueOnce(fakeAjs);
                    return [4 /*yield*/, install()];
                case 1:
                    _a.sent();
                    expect(spy).toHaveBeenCalledWith(segmentDotCom, {});
                    return [2 /*return*/];
            }
        });
    }); });
    it('derives the CDN from scripts on the page', function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    // @ts-ignore ignore Response required fields
                    mocked(unfetch).mockImplementation(function () { return fetchSettings; });
                    return [4 /*yield*/, loadLegacySettings(segmentDotCom)];
                case 1:
                    _a.sent();
                    expect(unfetch).toHaveBeenCalledWith('https://cdn.foo.com/v1/projects/zaySL4FGIiLsxt3I7omU5uLxXqxaBMPh/settings');
                    return [2 /*return*/];
            }
        });
    }); });
    it('runs any buffered operations after load', function (done) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    // @ts-ignore ignore Response required fields
                    mocked(unfetch).mockImplementation(function () { return fetchSettings; });
                    return [4 /*yield*/, install()];
                case 1:
                    _a.sent();
                    setTimeout(function () {
                        expect(track).toHaveBeenCalledWith('fruit basket', {
                            fruits: ['🍌', '🍇'],
                        });
                        expect(identify).toHaveBeenCalledWith('netto', {
                            employer: 'segment',
                        });
                        expect(page).toHaveBeenCalled();
                        done();
                    }, 0);
                    return [2 /*return*/];
            }
        });
    }); });
    it('sets buffered anonymousId before loading destinations', function (done) { return __awaiter(void 0, void 0, void 0, function () {
        var operations;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    // @ts-ignore ignore Response required fields
                    mocked(unfetch).mockImplementation(function () { return fetchSettings; });
                    operations = [];
                    track.mockImplementationOnce(function () { return operations.push('track'); });
                    setAnonymousId.mockImplementationOnce(function () {
                        return operations.push('setAnonymousId');
                    });
                    register.mockImplementationOnce(function () { return operations.push('register'); });
                    return [4 /*yield*/, install()];
                case 1:
                    _a.sent();
                    setTimeout(function () {
                        expect(setAnonymousId).toHaveBeenCalledWith('anonNetto');
                        expect(operations).toEqual([
                            // should run before any plugin is registered
                            'setAnonymousId',
                            // should run before any events are sent downstream
                            'register',
                            // should run after all plugins have been registered
                            'track',
                        ]);
                        done();
                    }, 0);
                    return [2 /*return*/];
            }
        });
    }); });
});
//# sourceMappingURL=standalone-analytics.test.js.map