"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrameSnapshot = exports.trace = void 0;
exports.trace = __importStar(require("../common/traceEvents"));
class FrameSnapshot {
    constructor(contextEntry, events, index) {
        this.contextEntry = contextEntry;
        this._snapshots = events;
        this._index = index;
    }
    traceEvent() {
        return this._snapshots[this._index];
    }
    serialize() {
        const visit = (n, snapshotIndex) => {
            // Text node.
            if (typeof n === 'string')
                return escapeText(n);
            if (!n._string) {
                if (Array.isArray(n[0])) {
                    // Node reference.
                    const referenceIndex = snapshotIndex - n[0][0];
                    if (referenceIndex >= 0 && referenceIndex < snapshotIndex) {
                        const nodes = snapshotNodes(this._snapshots[referenceIndex].snapshot);
                        const nodeIndex = n[0][1];
                        if (nodeIndex >= 0 && nodeIndex < nodes.length)
                            n._string = visit(nodes[nodeIndex], referenceIndex);
                    }
                }
                else if (typeof n[0] === 'string') {
                    // Element node.
                    const builder = [];
                    builder.push('<', n[0]);
                    for (const [attr, value] of Object.entries(n[1] || {}))
                        builder.push(' ', attr, '="', escapeAttribute(value), '"');
                    builder.push('>');
                    for (let i = 2; i < n.length; i++)
                        builder.push(visit(n[i], snapshotIndex));
                    if (!autoClosing.has(n[0]))
                        builder.push('</', n[0], '>');
                    n._string = builder.join('');
                }
                else {
                    // Why are we here? Let's not throw, just in case.
                    n._string = '';
                }
            }
            return n._string;
        };
        const snapshot = this._snapshots[this._index].snapshot;
        let html = visit(snapshot.html, this._index);
        if (snapshot.doctype)
            html = `<!DOCTYPE ${snapshot.doctype}>` + html;
        html += `<script>${this.contextEntry.created.snapshotScript}</script>`;
        const resourcesByUrl = this.contextEntry.resourcesByUrl;
        const overriddenUrls = this.contextEntry.overriddenUrls;
        const resourceOverrides = {};
        for (const o of this._snapshots[this._index].snapshot.resourceOverrides)
            resourceOverrides[o.url] = o.sha1;
        return { html, resourcesByUrl, overriddenUrls: overriddenUrls, resourceOverrides };
    }
}
exports.FrameSnapshot = FrameSnapshot;
const autoClosing = new Set(['AREA', 'BASE', 'BR', 'COL', 'COMMAND', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR']);
const escaped = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;' };
function escapeAttribute(s) {
    return s.replace(/[&<>"']/ug, char => escaped[char]);
}
function escapeText(s) {
    return s.replace(/[&<]/ug, char => escaped[char]);
}
function snapshotNodes(snapshot) {
    if (!snapshot._nodes) {
        const nodes = [];
        const visit = (n) => {
            if (typeof n === 'string') {
                nodes.push(n);
            }
            else if (typeof n[0] === 'string') {
                for (let i = 2; i < n.length; i++)
                    visit(n[i]);
                nodes.push(n);
            }
        };
        visit(snapshot.html);
        snapshot._nodes = nodes;
    }
    return snapshot._nodes;
}
//# sourceMappingURL=frameSnapshot.js.map