///
///
'use strict';
import _Global = require('../Core/_Global');
import _Base = require('../Core/_Base');
import {Promise} from '../Promise';
import Scheduler = require('../Scheduler');
import XMLHttpRequestModule = require('xhr2');
function schedule(f, arg, priority) {
Scheduler.schedule(function xhr_callback() {
f(arg);
}, priority, null, "WinJS.xhr");
}
function noop() {
}
var schemeRegex = /^(\w+)\:\/\//;
export function xhr(options: WinJS.IXHROptions): WinJS.IPromise {
///
///
/// Wraps calls to XMLHttpRequest in a promise.
///
///
/// The options that are applied to the XMLHttpRequest object. They are: type,
/// url, user, password, headers, responseType, data, and customRequestInitializer.
///
///
/// A promise that returns the XMLHttpRequest object when it completes.
///
///
var req;
return new Promise(
function(c, e, p) {
///
var priority = Scheduler.currentPriority;
req = new XMLHttpRequestModule.XMLHttpRequest();
var isLocalRequest = false;
var schemeMatch = schemeRegex.exec(options.url.toLowerCase());
if (schemeMatch) {
if (schemeMatch[1] === 'file') {
isLocalRequest = true;
}
} else if (_Global.location.protocol === 'file:') {
isLocalRequest = true;
}
req.onreadystatechange = function() {
if (req._canceled) {
req.onreadystatechange = noop;
return;
}
if (req.readyState === 4) {
if ((req.status >= 200 && req.status < 300) || (isLocalRequest && req.status === 0)) {
schedule(c, req, priority);
} else {
schedule(e, req, priority);
}
req.onreadystatechange = noop;
} else {
schedule(p, req, priority);
}
};
req.open(
options.type || "GET",
options.url
// Promise based XHR does not support sync.
//
//true,
//options.user,
//options.password
);
//req.responseType = options.responseType || "";
Object.keys(options.headers || {}).forEach(function(k) {
req.setRequestHeader(k, options.headers[k]);
});
if (options.customRequestInitializer) {
options.customRequestInitializer(req);
}
if (options.data === undefined) {
req.send();
} else {
req.send(options.data);
}
},
function() {
req.onreadystatechange = noop;
req._canceled = true;
req.abort();
}
);
}