text.js 4.42 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/* inspired by http://github.com/requirejs/text */
/*global XMLHttpRequest, XDomainRequest */

define(['module'], function (module) {
    'use strict';

    var xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
        bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
        stripReg = /!strip$/i,
        defaultConfig = module.config && module.config() || {};

    /**
     * Strips <?xml ...?> declarations so that external SVG and XML documents can be
     * added to a document without worry.
     * Also, if the string is an HTML document, only the part inside the body tag is returned.
     *
     * @param {String} external
     * @returns {String}
     */
    function stripContent(external) {
        var matches;

        if (!external) {
            return '';
        }

        matches = external.match(bodyRegExp);
        external = matches ?
            matches[1] :
            external.replace(xmlRegExp, '');

        return external;
    }

    /**
     * Checks that url match current location
     *
     * @param {String} url
     * @returns {Boolean}
     */
    function sameDomain(url) {
        var uProtocol, uHostName, uPort,
            xdRegExp = /^([\w:]+)?\/\/([^\/\\]+)/i,
            location = window.location,
            match = xdRegExp.exec(url);

        if (!match) {
            return true;
        }
        uProtocol = match[1];
        uHostName = match[2];

        uHostName = uHostName.split(':');
        uPort = uHostName[1] || '';
        uHostName = uHostName[0];

        return (!uProtocol || uProtocol === location.protocol) &&
            (!uHostName || uHostName.toLowerCase() === location.hostname.toLowerCase()) &&
            (!uPort && !uHostName || uPort === location.port);
    }

    /**
     * @returns {XMLHttpRequest|XDomainRequest|null}
     */
    function createRequest(url) {
        var xhr = new XMLHttpRequest();

        if (!sameDomain(url) && typeof XDomainRequest !== 'undefined') {
            xhr = new XDomainRequest();
        }

        return xhr;
    }

    /**
     * XHR requester. Returns value to callback.
     *
     * @param {String} url
     * @param {Function} callback
     * @param {Function} fail
     * @param {Object} headers
     */
    function getContent(url, callback, fail, headers) {
        var xhr = createRequest(url),
            header;

        xhr.open('GET', url);

        /*eslint-disable max-depth */
        if ('setRequestHeader' in xhr && headers) {
            for (header in headers) {
                if (headers.hasOwnProperty(header)) {
                    xhr.setRequestHeader(header.toLowerCase(), headers[header]);
                }
            }
        }

        /**
         * @inheritdoc
         */
        xhr.onreadystatechange = function () {
            var status, err;

            //Do not explicitly handle errors, those should be
            //visible via console output in the browser.
            if (xhr.readyState === 4) {
                status = xhr.status || 0;

                if (status > 399 && status < 600) {
                    //An http 4xx or 5xx error. Signal an error.
                    err = new Error(url + ' HTTP status: ' + status);
                    err.xhr = xhr;

                    if (fail) {
                        fail(err);
                    }
                } else {
                    callback(xhr.responseText);

                    if (defaultConfig.onXhrComplete) {
                        defaultConfig.onXhrComplete(xhr, url);
                    }
                }
            }
        };

        /*eslint-enable max-depth */

        if (defaultConfig.onXhr) {
            defaultConfig.onXhr(xhr, url);
        }

        xhr.send();
    }

    /**
     * Main method used by RequireJs.
     *
     * @param {String} name - has format: some.module.filext!strip
     * @param {Function} req
     * @param {Function|undefined} onLoad
     */
    function loadContent(name, req, onLoad) {

        var toStrip = stripReg.test(name),
            url = req.toUrl(name.replace(stripReg, '')),
            headers = defaultConfig.headers;

        getContent(url, function (content) {
                content = toStrip ? stripContent(content) : content;
                onLoad(content);
            }, onLoad.error, headers);
    }

    return {
        load: loadContent,
        get: getContent
    };
});