"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withPageDataTags = exports.getPageData = void 0;
const exenv_1 = require("exenv");
const path_1 = require("./path");
const id = '__MICRO_PAGE_DATA__';
exports.getPageData = async () => {
    var _a, _b;
    if (!exenv_1.canUseDOM) {
        throw new Error('💣 PageData fetch can only be run on the browser');
    }
    const dataElement = document.getElementById(id);
    if (typeof ((_a = dataElement) === null || _a === void 0 ? void 0 : _a.href) === 'string') {
        const maybeDataPath = (_b = dataElement) === null || _b === void 0 ? void 0 : _b.href;
        const response = await fetch(maybeDataPath);
        return response.json();
    }
    return null;
};
exports.withPageDataTags = ({ name, data, rootPath, path, }) => {
    if (data === undefined) {
        return '';
    }
    const href = path_1.join(rootPath, path);
    return `<link id="${id}" data-chunk="${name}" rel="preload" as="fetch" href="${href}" crossorigin="anonymous">`;
};
