"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("@builder.io/react");
var importReact = function () { return Promise.resolve().then(function () { return require('@builder.io/react'); }); };
var importShopify = function () { return Promise.resolve().then(function () { return require('@builder.io/shopify/react'); }); };
var importShopifyJs = function () { return Promise.resolve().then(function () { return require('@builder.io/shopify/js'); }); };
var importWidgets = function () { return Promise.resolve().then(function () { return require('@builder.io/widgets'); }); };
var useSolid = location.href.includes('builder.format=solid') && !react_1.Builder.isEditing;
react_1.Builder.isStatic = true;
function wrapInDiv(el) {
    var newDiv = document.createElement('div');
    var currentChildren = Array.from(el.children);
    for (var _i = 0, currentChildren_1 = currentChildren; _i < currentChildren_1.length; _i++) {
        var child = currentChildren_1[_i];
        newDiv.appendChild(child);
    }
    el.appendChild(newDiv);
    return newDiv;
}
// Credit: https://stackoverflow.com/a/25673911
function wrapHistoryPropertyWithCustomEvent(property) {
    try {
        var anyHistory = history;
        var originalFunction_1 = anyHistory[property];
        anyHistory[property] = function () {
            var rv = originalFunction_1.apply(this, arguments);
            var event = new CustomEvent(property, {
                detail: {
                    arguments: arguments,
                },
            });
            window.dispatchEvent(event);
            return rv;
        };
    }
    catch (err) {
        console.error('Error wrapping history method', property, err);
    }
}
var addedHistoryChangeEvent = false;
function addHistoryChangeEvent() {
    if (addedHistoryChangeEvent) {
        return;
    }
    addedHistoryChangeEvent = true;
    wrapHistoryPropertyWithCustomEvent('pushState');
    wrapHistoryPropertyWithCustomEvent('replaceState');
}
var componentName = process.env.ANGULAR ? 'builder-component-element' : 'builder-component';
if (react_1.Builder.isIframe) {
    importReact();
    importWidgets();
    importShopify();
    Promise.resolve().then(function () { return require('@builder.io/email'); });
}
if (process.env.NODE_ENV === 'development') {
    // Must use require here as import statements are only allowed
    // to exist at the top of a file.
    Promise.resolve().then(function () { return require('preact/debug'); });
}
function onReady(cb) {
    if (document.readyState !== 'loading') {
        cb();
    }
    else {
        document.addEventListener('DOMContentLoaded', cb);
    }
}
if (react_1.Builder.isBrowser && !customElements.get(componentName)) {
    var BuilderWC_1 = {
        Builder: react_1.Builder,
        builder: react_1.builder,
    };
    window.BuilderWC = BuilderWC_1;
    var builderWcLoadCallbacks = window.builderWcLoadCallbacks;
    if (builderWcLoadCallbacks) {
        if (typeof builderWcLoadCallbacks === 'function') {
            try {
                builderWcLoadCallbacks(BuilderWC_1);
            }
            catch (err) {
                console.error(err);
            }
        }
        else {
            try {
                builderWcLoadCallbacks.forEach(function (cb) {
                    try {
                        cb(BuilderWC_1);
                    }
                    catch (err) {
                        console.error(err);
                    }
                });
            }
            catch (err) {
                console.error(err);
            }
        }
    }
    /**
     * Iterate over API styles and add a new FontFace for each. This works around
     * a browser issue that can cause fonts to flash from server rendered HTML
     */
    var forceLoadFonts_1 = function () {
        try {
            var apiStyles = Array.from(document.querySelectorAll('.builder-api-styles'));
            if (!apiStyles.length || !document.fonts) {
                return;
            }
            apiStyles.forEach(function (element) {
                var styles = element.innerHTML;
                styles.replace(/(@font-face\s*{\s*font-family:\s*(.*?);[\s\S]+?url\((\S+)\)[\s\S]+?})/g, function (fullMatch, fontMatch, fontName, fontUrl) {
                    var _a;
                    var trimmedFontUrl = fontUrl
                        .replace(/"/g, '')
                        .replace(/'/g, '')
                        .trim();
                    var trimmedFontName = fontName
                        .replace(/"/g, '')
                        .replace(/'/g, '')
                        .trim();
                    var weight = (_a = fullMatch.match(/font-weight:\s*(\d+)/)) === null || _a === void 0 ? void 0 : _a[1];
                    var font = new FontFace(trimmedFontName, "url(\"" + trimmedFontUrl + "\")", {
                        weight: weight || '400',
                    });
                    if (!document.fonts.has(font)) {
                        document.fonts.add(font);
                    }
                    return '';
                });
            });
        }
        catch (err) {
            console.warn('Could not load Builder fonts', err);
        }
    };
    var inject = function () {
        forceLoadFonts_1();
        var selector = '.builder-component-wrap.builder-to-embed';
        var matches = document.querySelectorAll(selector);
        for (var i = 0; i < matches.length; i++) {
            var el = matches[i];
            var attrs = el.attributes;
            var newEl = document.createElement(componentName);
            for (var i_1 = attrs.length - 1; i_1 >= 0; i_1--) {
                var attr = attrs[i_1];
                if (attr.name.indexOf('data-') === 0) {
                    var name_1 = attr.name.indexOf('data-') === 0 ? attr.name.slice(5) : attr.name;
                    var value = attr.value;
                    // TODO: allow properties too
                    newEl.setAttribute(name_1, value);
                }
            }
            el.classList.remove('builder-to-embed');
            // Transfer children
            for (var i_2 = 0; i_2 < el.children.length; i_2++) {
                var child = el.children[i_2];
                child.remove();
                // newEl.appendChild(child)
            }
            el.innerHTML = '';
            el.appendChild(newEl);
        }
    };
    inject();
    onReady(inject);
    var BuilderPageElement = /** @class */ (function (_super) {
        __extends(BuilderPageElement, _super);
        function BuilderPageElement() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.previousName = '';
            _this.subscriptions = [];
            // TODO: do this in core SDK
            _this.trackedClick = false;
            _this.prerender = !react_1.Builder.isEditing;
            _this._options = {};
            _this.connected = false;
            _this.updateFromRouteChange = function () {
                var name = _this.modelName;
                react_1.builder
                    .get(name, __assign({ key: _this.key }, _this.options))
                    .promise()
                    .then(function (data) {
                    _this.loadPreact(data);
                });
            };
            _this.loadSolid = function (data, fresh) {
                if (fresh === void 0) { fresh = false; }
                var _a, _b;
                // TODO: eval solid JS into this dom element as the entry point
                if ((_b = (_a = data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.blocksJs) {
                    try {
                        var targetEl = _this.querySelector('.builder-component') || _this;
                        targetEl.innerHTML = '';
                        new Function('__BUILDER_TARGET_ELEMENT__', 'builder', 'Builder', 'context', data.data.blocksJs)(targetEl, react_1.builder, react_1.Builder, {
                            // TODO
                            showOpen: function () { return false; },
                        });
                        // this.querySelector('.builder-api-styles')?.remove();
                    }
                    catch (err) {
                        // TODO: fall back to Preact
                        console.error('Builder evaluated code error', err, { code: data.data.blocksJs });
                    }
                }
                else {
                    // TODO: fall back to Preact
                    new Error('blocksJS is not defined on the Builder content - cannot with Solid');
                }
            };
            _this.loadPreact = function (data, fresh) {
                if (fresh === void 0) { fresh = false; }
                return __awaiter(_this, void 0, void 0, function () {
                    var entry, name, getReactPromise, getWidgetsPromise, getShopifyPromise, getShopifyJsPromise, emailPromise, email, slot, hasFullData, BuilderPage, Shopify, shopify;
                    var _this = this;
                    var _a, _b, _c;
                    return __generator(this, function (_d) {
                        switch (_d.label) {
                            case 0:
                                if (useSolid && data && data.blocksJs) {
                                    return [2 /*return*/, this.loadSolid(data, fresh)];
                                }
                                entry = ((_a = data) === null || _a === void 0 ? void 0 : _a.id) || this.getAttribute('entry');
                                name = this.getAttribute('name') || this.getAttribute('model') || this.getAttribute('model-name');
                                getReactPromise = useSolid ? null : importReact();
                                getWidgetsPromise = useSolid ? null : importWidgets();
                                getShopifyPromise = useSolid ? null : importShopify();
                                getShopifyJsPromise = useSolid ? null : importShopifyJs();
                                emailPromise = null;
                                email = Boolean(name === 'email' ||
                                    this.getAttribute('email-mode') ||
                                    this.getAttribute('format') === 'email' ||
                                    (this.options && this.options.format === 'email'));
                                if (email) {
                                    emailPromise = Promise.resolve().then(function () { return require('@builder.io/email'); });
                                }
                                slot = this.getAttribute('slot');
                                hasFullData = Boolean((_c = (_b = data) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.blocks);
                                if (!((!this.prerender && !this.currentContent) ||
                                    (react_1.Builder.isIframe && (!react_1.builder.apiKey || react_1.builder.apiKey === 'DEMO')) ||
                                    hasFullData)) return [3 /*break*/, 4];
                                return [4 /*yield*/, getReactPromise];
                            case 1:
                                BuilderPage = (_d.sent()).BuilderPage;
                                return [4 /*yield*/, Promise.all([getWidgetsPromise, getShopifyPromise])];
                            case 2:
                                _d.sent();
                                return [4 /*yield*/, getShopifyJsPromise];
                            case 3:
                                Shopify = (_d.sent()).Shopify;
                                shopify = new Shopify({});
                                // Ensure styles don't load twice
                                BuilderPage.renderInto(wrapInDiv(this), __assign(__assign(__assign({}, { ref: function (ref) { return (_this.builderPageRef = ref); } }), { modelName: name, context: {
                                        shopify: shopify,
                                        liquid: shopify.liquid,
                                        apiKey: react_1.builder.apiKey,
                                    }, entry: entry, emailMode: (this.options || {}).emailMode || this.getAttribute('email-mode') === 'true', options: __assign(__assign({}, this.options), { key: this.key }) }), (hasFullData && {
                                    content: data,
                                })), this.getAttribute('hydrate') !== 'false', fresh);
                                return [2 /*return*/];
                            case 4:
                                react_1.builder
                                    .get(name, __assign(__assign({ key: this.getAttribute('key') ||
                                        (slot ? "slot:" + slot : null) ||
                                        (react_1.Builder.isEditing
                                            ? name
                                            : this.getAttribute('entry') ||
                                                (this.updateOnRouteChange ? name + ":" + location.pathname : undefined)) }, this.options), { entry: data ? data.id : this.options.entry || undefined, prerender: false }))
                                    .promise()
                                    .then(function (data) { return __awaiter(_this, void 0, void 0, function () {
                                    var BuilderPage, loadEvent, Shopify, shopify;
                                    var _this = this;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                if (useSolid) {
                                                    return [2 /*return*/, this.loadSolid(data)];
                                                }
                                                return [4 /*yield*/, getReactPromise];
                                            case 1:
                                                BuilderPage = (_a.sent()).BuilderPage;
                                                return [4 /*yield*/, Promise.all([getWidgetsPromise, getShopifyPromise])];
                                            case 2:
                                                _a.sent();
                                                if (!emailPromise) return [3 /*break*/, 4];
                                                return [4 /*yield*/, emailPromise];
                                            case 3:
                                                _a.sent();
                                                _a.label = 4;
                                            case 4:
                                                loadEvent = new CustomEvent('load', { detail: data });
                                                this.dispatchEvent(loadEvent);
                                                return [4 /*yield*/, getShopifyJsPromise];
                                            case 5:
                                                Shopify = (_a.sent()).Shopify;
                                                shopify = new Shopify({});
                                                BuilderPage.renderInto(wrapInDiv(this), __assign(__assign({}, { ref: function (ref) { return (_this.builderPageRef = ref); } }), { modelName: name, context: {
                                                        shopify: shopify,
                                                        liquid: shopify.liquid,
                                                        apiKey: react_1.builder.apiKey,
                                                    }, emailMode: (this.options || {}).emailMode ||
                                                        this.getAttribute('email-mode') === 'true', entry: data ? data.id : entry, options: __assign({ entry: data ? data.id : entry, initialContent: data ? [data] : undefined, 
                                                        // TODO: make this a settable property too
                                                        key: this.getAttribute('key') ||
                                                            (slot ? "slot:" + slot : null) ||
                                                            (react_1.Builder.isEditing
                                                                ? name
                                                                : (data && data.id) ||
                                                                    (this.updateOnRouteChange ? name + ":" + location.pathname : undefined)) }, this.options) }), this.getAttribute('hydrate') !== 'false', // TODO: query param override builder.hydrate
                                                fresh);
                                                if (react_1.Builder.isIframe) {
                                                    setTimeout(function () {
                                                        parent.postMessage({ type: 'builder.updateContent' }, '*');
                                                        setTimeout(function () {
                                                            parent.postMessage({ type: 'builder.sdkInjected', data: { modelName: name } }, '*');
                                                        }, 100);
                                                    }, 100);
                                                }
                                                return [2 /*return*/];
                                        }
                                    });
                                }); }, function (error) { return __awaiter(_this, void 0, void 0, function () {
                                    var BuilderPage, Shopify, shopify, errorEvent;
                                    var _this = this;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                if (!react_1.Builder.isEditing) return [3 /*break*/, 6];
                                                return [4 /*yield*/, getReactPromise];
                                            case 1:
                                                BuilderPage = (_a.sent()).BuilderPage;
                                                return [4 /*yield*/, Promise.all([getWidgetsPromise, getShopifyPromise])];
                                            case 2:
                                                _a.sent();
                                                if (!emailPromise) return [3 /*break*/, 4];
                                                return [4 /*yield*/, emailPromise];
                                            case 3:
                                                _a.sent();
                                                _a.label = 4;
                                            case 4: return [4 /*yield*/, getShopifyJsPromise];
                                            case 5:
                                                Shopify = (_a.sent()).Shopify;
                                                shopify = new Shopify({});
                                                BuilderPage.renderInto(wrapInDiv(this), __assign(__assign({}, {
                                                    ref: function (ref) { return (_this.builderPageRef = ref); },
                                                }), { context: {
                                                        shopify: shopify,
                                                        liquid: shopify.liquid,
                                                        apiKey: react_1.builder.apiKey,
                                                    }, modelName: name, entry: data ? data.id : entry, emailMode: (this.options || {}).emailMode ||
                                                        this.getAttribute('email-mode') === 'true', options: __assign({ entry: data ? data.id : entry, initialContent: data ? [data] : undefined, key: this.getAttribute('key') ||
                                                            (slot ? "slot:" + slot : null) ||
                                                            (react_1.Builder.isEditing
                                                                ? name
                                                                : (data && data.id) ||
                                                                    (this.updateOnRouteChange ? name + ":" + location.pathname : undefined)) }, this.options), fresh: fresh }), this.getAttribute('hydrate') !== 'false');
                                                return [3 /*break*/, 7];
                                            case 6:
                                                console.warn('Builder webcomponent error:', error);
                                                this.classList.add('builder-errored');
                                                this.classList.add('builder-loaded');
                                                this.classList.remove('builder-loading');
                                                errorEvent = new CustomEvent('error', { detail: error });
                                                this.dispatchEvent(errorEvent);
                                                _a.label = 7;
                                            case 7: return [2 /*return*/];
                                        }
                                    });
                                }); });
                                return [2 /*return*/];
                        }
                    });
                });
            };
            return _this;
        }
        Object.defineProperty(BuilderPageElement.prototype, "options", {
            get: function () {
                return __assign(__assign({ rev: this.getAttribute('rev') || undefined }, (useSolid ? { format: 'solid' } : {})), this._options);
            },
            set: function (options) {
                this._options = options;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BuilderPageElement.prototype, "updateOnRouteChange", {
            get: function () {
                return Boolean(this.hasAttribute('reload-on-route-change') &&
                    !this.getAttribute('entry') &&
                    this.getAttribute('reload-on-route-change') !== 'false' &&
                    !react_1.Builder.isEditing);
            },
            enumerable: true,
            configurable: true
        });
        BuilderPageElement.prototype.getOptionsFromAttribute = function () {
            var options = this.getAttribute('options');
            if (options && typeof options === 'string' && options.trim()[0] === '{') {
                // TODO: use JSON5
                this._options = JSON.parse(options);
            }
            var slot = this.getAttribute('slot');
            if (slot) {
                var options_1 = (this._options = this._options || {});
                var query = options_1.query || (options_1.query = {});
                query['data.slot'] = slot;
            }
        };
        Object.defineProperty(BuilderPageElement.prototype, "key", {
            get: function () {
                var slot = this.getAttribute('slot');
                return (this.getAttribute('key') ||
                    (slot ? "slot:" + slot : null) ||
                    (!react_1.Builder.isEditing && this.getAttribute('entry')) ||
                    (this.updateOnRouteChange ? name + ":" + location.pathname : undefined));
            },
            enumerable: true,
            configurable: true
        });
        BuilderPageElement.prototype.connectedCallback = function () {
            var _this = this;
            var _a;
            if (this.connected) {
                return;
            }
            this.connected = true;
            this.dispatchEvent(new CustomEvent('connected', { detail: { builder: react_1.builder, Builder: react_1.Builder }, bubbles: true }));
            if (react_1.Builder.isEditing && !location.href.includes('builder.stopPropagation=false')) {
                this.addEventListener('click', function (e) {
                    e.stopPropagation();
                });
            }
            if (this.hasAttribute('editing-only') &&
                this.getAttribute('editing-only') !== 'false' &&
                !(react_1.Builder.isEditing || react_1.Builder.isPreviewing)) {
                return;
            }
            if (this.updateOnRouteChange) {
                addHistoryChangeEvent();
                window.addEventListener('popstate', this.updateFromRouteChange);
                window.addEventListener('pushState', this.updateFromRouteChange);
                window.addEventListener('replaceState', this.updateFromRouteChange);
                this.subscriptions.push(function () {
                    window.removeEventListener('popstate', _this.updateFromRouteChange);
                    window.removeEventListener('pushState', _this.updateFromRouteChange);
                    window.removeEventListener('replaceState', _this.updateFromRouteChange);
                });
            }
            var prerenderAttr = this.getAttribute('prerender');
            if (prerenderAttr) {
                this.prerender = prerenderAttr === 'false' ? false : this.prerender;
            }
            (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({
                type: 'builder.isReactSdk',
                data: { value: true },
            }, '*');
            this.getOptionsFromAttribute();
            this.getContent();
        };
        BuilderPageElement.prototype.attributeChangedCallback = function () {
            // TODO: listen to properties too
            this.getOptionsFromAttribute();
            this.getContent();
        };
        BuilderPageElement.prototype.disconnectedCallback = function () {
            this.unsubscribe();
        };
        BuilderPageElement.prototype.loaded = function () {
            this.classList.add('builder-loaded');
        };
        Object.defineProperty(BuilderPageElement.prototype, "modelName", {
            get: function () {
                return this.getAttribute('name') || this.getAttribute('model');
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BuilderPageElement.prototype, "currentContent", {
            // When loaded from the server
            get: function () {
                var name = this.modelName;
                // TODO: get this to work with nested blocks
                var existing = this.querySelector("[data-builder-component=\"" + name + "\"]");
                if (existing) {
                    var id = existing.getAttribute('data-builder-content-id');
                    var variationId = existing.getAttribute('data-builder-variation-id');
                    if (id) {
                        return {
                            id: id,
                            testVariationId: variationId || undefined,
                        };
                    }
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        BuilderPageElement.prototype.getContent = function (fresh) {
            var _this = this;
            if (fresh === void 0) { fresh = false; }
            var token = this.getAttribute('token') || this.getAttribute('auth-token');
            if (token) {
                react_1.builder.authToken = token;
            }
            var key = this.getAttribute('api-key');
            if (key && key !== react_1.builder.apiKey) {
                react_1.builder.apiKey = key;
            }
            if (!react_1.builder.apiKey) {
                var subscription_1 = react_1.builder['apiKey$'].subscribe(function (key) {
                    if (key) {
                        _this.getContent();
                    }
                });
                this.subscriptions.push(function () { return subscription_1.unsubscribe(); });
                setTimeout(function () {
                    if (!react_1.builder.apiKey) {
                        throw new Error('Builder API key not found. Please see our docs for how to provide your API key https://builder.io/c/docs');
                    }
                }, 10000);
                // TODO: how test if actually editing. have a message to receive and flag that editing his happening
                if (!react_1.Builder.isIframe) {
                    return;
                }
            }
            var name = this.getAttribute('name') || this.getAttribute('model');
            // TODO: only judge this on key, or remove this line entirely as the
            // SDK handles this anyway
            if (name === this.previousName && !this.getAttribute('key')) {
                return false;
            }
            var entry = this.getAttribute('entry');
            var slot = this.getAttribute('slot');
            if (!this.prerender || !react_1.builder.apiKey || fresh) {
                var currentContent_1 = fresh ? null : this.currentContent;
                this.loadPreact(currentContent_1 ? currentContent_1 : entry ? { id: entry } : null, fresh);
                return;
            }
            if (!name) {
                return false;
            }
            var currentContent = fresh ? null : this.currentContent;
            if (currentContent && !react_1.Builder.isEditing) {
                this.data = currentContent;
                this.loaded();
                this.loadPreact(this.data);
                return;
            }
            this.previousName = name;
            this.classList.add('builder-loading');
            var unsubscribed = false;
            react_1.builder
                .get(name, __assign(__assign({ key: this.getAttribute('key') ||
                    (slot ? "slot:" + slot : null) ||
                    (!react_1.Builder.isEditing && this.getAttribute('entry')) ||
                    (this.updateOnRouteChange ? name + ":" + location.pathname : undefined), entry: entry || undefined }, this.options), { prerender: true }))
                .promise()
                .then(function (data) {
                if (unsubscribed) {
                    console.warn('Unsubscribe did not work!');
                    return;
                }
                _this.classList.remove('builder-loading');
                _this.loaded();
                if (!data) {
                    _this.classList.add('builder-no-content-found');
                    var loadEvent = new CustomEvent('load', { detail: data });
                    _this.dispatchEvent(loadEvent);
                    return;
                }
                if (!_this.classList.contains('builder-editor-injected')) {
                    _this.data = data;
                    if (data.data && data.data.html) {
                        _this.innerHTML = data.data.html;
                        _this.findAndRunScripts();
                        var loadEvent = new CustomEvent('htmlload', { detail: data });
                        _this.dispatchEvent(loadEvent);
                    }
                    _this.loadPreact(data);
                }
            }, function (error) {
                // Server render failed, not the end of the world, load react anyway
                _this.loadPreact();
            });
        };
        BuilderPageElement.prototype.findAndRunScripts = function () {
            var scripts = this.getElementsByTagName('script');
            for (var i = 0; i < scripts.length; i++) {
                var script = scripts[i];
                if (script.src) {
                    var newScript = document.createElement('script');
                    newScript.async = true;
                    newScript.src = script.src;
                    document.head.appendChild(newScript);
                }
                else {
                    try {
                        new Function(script.innerText)();
                    }
                    catch (error) {
                        console.warn('Builder custom code component error:', error);
                    }
                }
            }
        };
        BuilderPageElement.prototype.unsubscribe = function () {
            if (this.subscriptions) {
                this.subscriptions.forEach(function (fn) { return fn(); });
                this.subscriptions = [];
            }
        };
        return BuilderPageElement;
    }(HTMLElement));
    customElements.define(componentName, BuilderPageElement);
    var BuilderInit = /** @class */ (function (_super) {
        __extends(BuilderInit, _super);
        function BuilderInit() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BuilderInit.prototype.init = function () {
            var key = this.getAttribute('api-key') || this.getAttribute('key');
            var canTrack = this.getAttribute('canTrack') !== 'false';
            if (key && react_1.builder.apiKey !== key) {
                react_1.builder.apiKey = key;
            }
            if (react_1.builder.canTrack !== canTrack) {
                react_1.builder.canTrack = canTrack;
            }
        };
        BuilderInit.prototype.connectedCallback = function () {
            this.init();
        };
        BuilderInit.prototype.attributeChangedCallback = function () {
            this.init();
        };
        return BuilderInit;
    }(HTMLElement));
    customElements.define('builder-init', BuilderInit);
}
window.dispatchEvent(new CustomEvent('builder:load', { detail: { builder: react_1.builder, Builder: react_1.Builder } }));
//# sourceMappingURL=elements.js.map