/**
 * Get the current page's canonical URL.
 *
 * @return {string|undefined}
 */
function canonical() {
    var tags = document.getElementsByTagName('link');
    var canon = '';
    Array.prototype.slice.call(tags).forEach(function (tag) {
        if (tag.getAttribute('rel') === 'canonical') {
            canon = tag.getAttribute('href');
        }
    });
    return canon;
}
/**
 * Return the canonical path for the page.
 */
function canonicalPath() {
    var canon = canonical();
    if (!canon) {
        return window.location.pathname;
    }
    var a = document.createElement('a');
    a.href = canon;
    var pathname = !a.pathname.startsWith('/') ? '/' + a.pathname : a.pathname;
    return pathname;
}
/**
 * Return the canonical URL for the page concat the given `search`
 * and strip the hash.
 */
export function canonicalUrl(search) {
    if (search === void 0) { search = ''; }
    var canon = canonical();
    if (canon) {
        return canon.includes('?') ? canon : "" + canon + search;
    }
    var url = window.location.href;
    var i = url.indexOf('#');
    return i === -1 ? url : url.slice(0, i);
}
/**
 * Return a default `options.context.page` object.
 *
 * https://segment.com/docs/spec/page/#properties
 */
export function pageDefaults() {
    return {
        path: canonicalPath(),
        referrer: document.referrer,
        search: location.search,
        title: document.title,
        url: canonicalUrl(location.search),
    };
}
function enrichPageContext(ctx) {
    var event = ctx.event;
    event.context = event.context || {};
    var pageContext = pageDefaults();
    if (event.context.page) {
        pageContext = Object.assign({}, pageContext, event.context.page);
    }
    event.context = Object.assign({}, event.context, {
        page: pageContext,
    });
    ctx.event = event;
    return ctx;
}
export var pageEnrichment = {
    name: 'Page Enrichment',
    version: '0.1.0',
    isLoaded: function () { return true; },
    load: function () { return Promise.resolve(); },
    type: 'enrichment',
    page: function (ctx) {
        ctx.event.properties = Object.assign({}, pageDefaults(), ctx.event.properties);
        if (ctx.event.name) {
            ctx.event.properties.name = ctx.event.name;
        }
        return enrichPageContext(ctx);
    },
    alias: enrichPageContext,
    track: enrichPageContext,
    identify: enrichPageContext,
    group: enrichPageContext,
};
//# sourceMappingURL=index.js.map