"use strict";
/**
 * Copyright (c) Microsoft Corporation.
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tracer = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const util = __importStar(require("util"));
const utils_1 = require("../../../utils/utils");
const browserContext_1 = require("../../browserContext");
const frames_1 = require("../../frames");
const helper_1 = require("../../helper");
const page_1 = require("../../page");
const traceSnapshotter_1 = require("./traceSnapshotter");
const fsAppendFileAsync = util.promisify(fs_1.default.appendFile.bind(fs_1.default));
const envTrace = utils_1.getFromENV('PWTRACE_RESOURCE_DIR');
class Tracer {
    constructor(context, traceDir) {
        this._eventListeners = [];
        this._disposed = false;
        this._pendingCalls = new Map();
        this._context = context;
        this._context.instrumentation.addListener(this);
        const resourcesDir = envTrace || path_1.default.join(traceDir, 'resources');
        const tracePrefix = path_1.default.join(traceDir, context._options._debugName);
        const traceFile = tracePrefix + '.trace';
        this._appendEventChain = utils_1.mkdirIfNeeded(traceFile).then(() => traceFile);
        this._snapshotter = new traceSnapshotter_1.TraceSnapshotter(context, resourcesDir, traceEvent => this._appendTraceEvent(traceEvent));
    }
    async start() {
        const event = {
            timestamp: utils_1.monotonicTime(),
            type: 'context-metadata',
            browserName: this._context._browser.options.name,
            isMobile: !!this._context._options.isMobile,
            deviceScaleFactor: this._context._options.deviceScaleFactor || 1,
            viewportSize: this._context._options.viewport || undefined,
            debugName: this._context._options._debugName,
        };
        this._appendTraceEvent(event);
        this._eventListeners = [
            helper_1.helper.addEventListener(this._context, browserContext_1.BrowserContext.Events.Page, this._onPage.bind(this)),
        ];
        await this._snapshotter.start();
    }
    async stop() {
        this._disposed = true;
        this._context.instrumentation.removeListener(this);
        helper_1.helper.removeEventListeners(this._eventListeners);
        await this._snapshotter.dispose();
        for (const { sdkObject, metadata } of this._pendingCalls.values())
            this.onAfterCall(sdkObject, metadata);
        // Ensure all writes are finished.
        await this._appendEventChain;
    }
    _captureSnapshot(name, sdkObject, metadata, element) {
        if (!sdkObject.attribution.page)
            return;
        const snapshotName = `${name}@${metadata.id}`;
        metadata.snapshots.push({ title: name, snapshotName });
        this._snapshotter.captureSnapshot(sdkObject.attribution.page, snapshotName, element);
    }
    async onBeforeCall(sdkObject, metadata) {
        this._captureSnapshot('before', sdkObject, metadata);
        this._pendingCalls.set(metadata.id, { sdkObject, metadata });
    }
    async onBeforeInputAction(sdkObject, metadata, element) {
        this._captureSnapshot('action', sdkObject, metadata, element);
    }
    async onAfterCall(sdkObject, metadata) {
        if (!this._pendingCalls.has(metadata.id))
            return;
        this._captureSnapshot('after', sdkObject, metadata);
        if (!sdkObject.attribution.page)
            return;
        const event = {
            timestamp: metadata.startTime,
            type: 'action',
            metadata,
        };
        this._appendTraceEvent(event);
        this._pendingCalls.delete(metadata.id);
    }
    onEvent(sdkObject, metadata) {
        if (!sdkObject.attribution.page)
            return;
        const event = {
            timestamp: metadata.startTime,
            type: 'event',
            metadata,
        };
        this._appendTraceEvent(event);
    }
    _onPage(page) {
        const pageId = page.guid;
        const event = {
            timestamp: utils_1.monotonicTime(),
            type: 'page-created',
            pageId,
        };
        this._appendTraceEvent(event);
        page.on(page_1.Page.Events.Dialog, (dialog) => {
            if (this._disposed)
                return;
            const event = {
                timestamp: utils_1.monotonicTime(),
                type: 'dialog-opened',
                pageId,
                dialogType: dialog.type(),
                message: dialog.message(),
            };
            this._appendTraceEvent(event);
        });
        page.on(page_1.Page.Events.InternalDialogClosed, (dialog) => {
            if (this._disposed)
                return;
            const event = {
                timestamp: utils_1.monotonicTime(),
                type: 'dialog-closed',
                pageId,
                dialogType: dialog.type(),
            };
            this._appendTraceEvent(event);
        });
        page.mainFrame().on(frames_1.Frame.Events.Navigation, (navigationEvent) => {
            if (this._disposed || page.mainFrame().url() === 'about:blank')
                return;
            const event = {
                timestamp: utils_1.monotonicTime(),
                type: 'navigation',
                pageId,
                url: navigationEvent.url,
                sameDocument: !navigationEvent.newDocument,
            };
            this._appendTraceEvent(event);
        });
        page.on(page_1.Page.Events.Load, () => {
            if (this._disposed || page.mainFrame().url() === 'about:blank')
                return;
            const event = {
                timestamp: utils_1.monotonicTime(),
                type: 'load',
                pageId,
            };
            this._appendTraceEvent(event);
        });
        page.on(page_1.Page.Events.ScreencastFrame, params => {
            const sha1 = utils_1.calculateSha1(params.buffer);
            const event = {
                type: 'page-screencast-frame',
                pageId: page.guid,
                sha1,
                pageTimestamp: params.timestamp,
                width: params.width,
                height: params.height,
                timestamp: utils_1.monotonicTime()
            };
            this._appendTraceEvent(event);
            this._snapshotter.onBlob({ sha1, buffer: params.buffer });
        });
        page.once(page_1.Page.Events.Close, () => {
            if (this._disposed)
                return;
            const event = {
                timestamp: utils_1.monotonicTime(),
                type: 'page-destroyed',
                pageId,
            };
            this._appendTraceEvent(event);
        });
    }
    _appendTraceEvent(event) {
        // Serialize all writes to the trace file.
        this._appendEventChain = this._appendEventChain.then(async (traceFile) => {
            await fsAppendFileAsync(traceFile, JSON.stringify(event) + '\n');
            return traceFile;
        });
    }
}
exports.Tracer = Tracer;
//# sourceMappingURL=tracer.js.map