vue-resource.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  1. /*!
  2. * vue-resource v1.5.0
  3. * https://github.com/pagekit/vue-resource
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global.VueResource = factory());
  10. }(this, (function () { 'use strict';
  11. /**
  12. * Promises/A+ polyfill v1.1.4 (https://github.com/bramstein/promis)
  13. */
  14. var RESOLVED = 0;
  15. var REJECTED = 1;
  16. var PENDING = 2;
  17. function Promise$1(executor) {
  18. this.state = PENDING;
  19. this.value = undefined;
  20. this.deferred = [];
  21. var promise = this;
  22. try {
  23. executor(function (x) {
  24. promise.resolve(x);
  25. }, function (r) {
  26. promise.reject(r);
  27. });
  28. } catch (e) {
  29. promise.reject(e);
  30. }
  31. }
  32. Promise$1.reject = function (r) {
  33. return new Promise$1(function (resolve, reject) {
  34. reject(r);
  35. });
  36. };
  37. Promise$1.resolve = function (x) {
  38. return new Promise$1(function (resolve, reject) {
  39. resolve(x);
  40. });
  41. };
  42. Promise$1.all = function all(iterable) {
  43. return new Promise$1(function (resolve, reject) {
  44. var count = 0, result = [];
  45. if (iterable.length === 0) {
  46. resolve(result);
  47. }
  48. function resolver(i) {
  49. return function (x) {
  50. result[i] = x;
  51. count += 1;
  52. if (count === iterable.length) {
  53. resolve(result);
  54. }
  55. };
  56. }
  57. for (var i = 0; i < iterable.length; i += 1) {
  58. Promise$1.resolve(iterable[i]).then(resolver(i), reject);
  59. }
  60. });
  61. };
  62. Promise$1.race = function race(iterable) {
  63. return new Promise$1(function (resolve, reject) {
  64. for (var i = 0; i < iterable.length; i += 1) {
  65. Promise$1.resolve(iterable[i]).then(resolve, reject);
  66. }
  67. });
  68. };
  69. var p = Promise$1.prototype;
  70. p.resolve = function resolve(x) {
  71. var promise = this;
  72. if (promise.state === PENDING) {
  73. if (x === promise) {
  74. throw new TypeError('Promise settled with itself.');
  75. }
  76. var called = false;
  77. try {
  78. var then = x && x['then'];
  79. if (x !== null && typeof x === 'object' && typeof then === 'function') {
  80. then.call(x, function (x) {
  81. if (!called) {
  82. promise.resolve(x);
  83. }
  84. called = true;
  85. }, function (r) {
  86. if (!called) {
  87. promise.reject(r);
  88. }
  89. called = true;
  90. });
  91. return;
  92. }
  93. } catch (e) {
  94. if (!called) {
  95. promise.reject(e);
  96. }
  97. return;
  98. }
  99. promise.state = RESOLVED;
  100. promise.value = x;
  101. promise.notify();
  102. }
  103. };
  104. p.reject = function reject(reason) {
  105. var promise = this;
  106. if (promise.state === PENDING) {
  107. if (reason === promise) {
  108. throw new TypeError('Promise settled with itself.');
  109. }
  110. promise.state = REJECTED;
  111. promise.value = reason;
  112. promise.notify();
  113. }
  114. };
  115. p.notify = function notify() {
  116. var promise = this;
  117. nextTick(function () {
  118. if (promise.state !== PENDING) {
  119. while (promise.deferred.length) {
  120. var deferred = promise.deferred.shift(),
  121. onResolved = deferred[0],
  122. onRejected = deferred[1],
  123. resolve = deferred[2],
  124. reject = deferred[3];
  125. try {
  126. if (promise.state === RESOLVED) {
  127. if (typeof onResolved === 'function') {
  128. resolve(onResolved.call(undefined, promise.value));
  129. } else {
  130. resolve(promise.value);
  131. }
  132. } else if (promise.state === REJECTED) {
  133. if (typeof onRejected === 'function') {
  134. resolve(onRejected.call(undefined, promise.value));
  135. } else {
  136. reject(promise.value);
  137. }
  138. }
  139. } catch (e) {
  140. reject(e);
  141. }
  142. }
  143. }
  144. });
  145. };
  146. p.then = function then(onResolved, onRejected) {
  147. var promise = this;
  148. return new Promise$1(function (resolve, reject) {
  149. promise.deferred.push([onResolved, onRejected, resolve, reject]);
  150. promise.notify();
  151. });
  152. };
  153. p.catch = function (onRejected) {
  154. return this.then(undefined, onRejected);
  155. };
  156. /**
  157. * Promise adapter.
  158. */
  159. if (typeof Promise === 'undefined') {
  160. window.Promise = Promise$1;
  161. }
  162. function PromiseObj(executor, context) {
  163. if (executor instanceof Promise) {
  164. this.promise = executor;
  165. } else {
  166. this.promise = new Promise(executor.bind(context));
  167. }
  168. this.context = context;
  169. }
  170. PromiseObj.all = function (iterable, context) {
  171. return new PromiseObj(Promise.all(iterable), context);
  172. };
  173. PromiseObj.resolve = function (value, context) {
  174. return new PromiseObj(Promise.resolve(value), context);
  175. };
  176. PromiseObj.reject = function (reason, context) {
  177. return new PromiseObj(Promise.reject(reason), context);
  178. };
  179. PromiseObj.race = function (iterable, context) {
  180. return new PromiseObj(Promise.race(iterable), context);
  181. };
  182. var p$1 = PromiseObj.prototype;
  183. p$1.bind = function (context) {
  184. this.context = context;
  185. return this;
  186. };
  187. p$1.then = function (fulfilled, rejected) {
  188. if (fulfilled && fulfilled.bind && this.context) {
  189. fulfilled = fulfilled.bind(this.context);
  190. }
  191. if (rejected && rejected.bind && this.context) {
  192. rejected = rejected.bind(this.context);
  193. }
  194. return new PromiseObj(this.promise.then(fulfilled, rejected), this.context);
  195. };
  196. p$1.catch = function (rejected) {
  197. if (rejected && rejected.bind && this.context) {
  198. rejected = rejected.bind(this.context);
  199. }
  200. return new PromiseObj(this.promise.catch(rejected), this.context);
  201. };
  202. p$1.finally = function (callback) {
  203. return this.then(function (value) {
  204. callback.call(this);
  205. return value;
  206. }, function (reason) {
  207. callback.call(this);
  208. return Promise.reject(reason);
  209. }
  210. );
  211. };
  212. /**
  213. * Utility functions.
  214. */
  215. var ref = {};
  216. var hasOwnProperty = ref.hasOwnProperty;
  217. var ref$1 = [];
  218. var slice = ref$1.slice;
  219. var debug = false, ntick;
  220. var inBrowser = typeof window !== 'undefined';
  221. function Util (ref) {
  222. var config = ref.config;
  223. var nextTick = ref.nextTick;
  224. ntick = nextTick;
  225. debug = config.debug || !config.silent;
  226. }
  227. function warn(msg) {
  228. if (typeof console !== 'undefined' && debug) {
  229. console.warn('[VueResource warn]: ' + msg);
  230. }
  231. }
  232. function error(msg) {
  233. if (typeof console !== 'undefined') {
  234. console.error(msg);
  235. }
  236. }
  237. function nextTick(cb, ctx) {
  238. return ntick(cb, ctx);
  239. }
  240. function trim(str) {
  241. return str ? str.replace(/^\s*|\s*$/g, '') : '';
  242. }
  243. function trimEnd(str, chars) {
  244. if (str && chars === undefined) {
  245. return str.replace(/\s+$/, '');
  246. }
  247. if (!str || !chars) {
  248. return str;
  249. }
  250. return str.replace(new RegExp(("[" + chars + "]+$")), '');
  251. }
  252. function toLower(str) {
  253. return str ? str.toLowerCase() : '';
  254. }
  255. function toUpper(str) {
  256. return str ? str.toUpperCase() : '';
  257. }
  258. var isArray = Array.isArray;
  259. function isString(val) {
  260. return typeof val === 'string';
  261. }
  262. function isFunction(val) {
  263. return typeof val === 'function';
  264. }
  265. function isObject(obj) {
  266. return obj !== null && typeof obj === 'object';
  267. }
  268. function isPlainObject(obj) {
  269. return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype;
  270. }
  271. function isBlob(obj) {
  272. return typeof Blob !== 'undefined' && obj instanceof Blob;
  273. }
  274. function isFormData(obj) {
  275. return typeof FormData !== 'undefined' && obj instanceof FormData;
  276. }
  277. function when(value, fulfilled, rejected) {
  278. var promise = PromiseObj.resolve(value);
  279. if (arguments.length < 2) {
  280. return promise;
  281. }
  282. return promise.then(fulfilled, rejected);
  283. }
  284. function options(fn, obj, opts) {
  285. opts = opts || {};
  286. if (isFunction(opts)) {
  287. opts = opts.call(obj);
  288. }
  289. return merge(fn.bind({$vm: obj, $options: opts}), fn, {$options: opts});
  290. }
  291. function each(obj, iterator) {
  292. var i, key;
  293. if (isArray(obj)) {
  294. for (i = 0; i < obj.length; i++) {
  295. iterator.call(obj[i], obj[i], i);
  296. }
  297. } else if (isObject(obj)) {
  298. for (key in obj) {
  299. if (hasOwnProperty.call(obj, key)) {
  300. iterator.call(obj[key], obj[key], key);
  301. }
  302. }
  303. }
  304. return obj;
  305. }
  306. var assign = Object.assign || _assign;
  307. function merge(target) {
  308. var args = slice.call(arguments, 1);
  309. args.forEach(function (source) {
  310. _merge(target, source, true);
  311. });
  312. return target;
  313. }
  314. function defaults(target) {
  315. var args = slice.call(arguments, 1);
  316. args.forEach(function (source) {
  317. for (var key in source) {
  318. if (target[key] === undefined) {
  319. target[key] = source[key];
  320. }
  321. }
  322. });
  323. return target;
  324. }
  325. function _assign(target) {
  326. var args = slice.call(arguments, 1);
  327. args.forEach(function (source) {
  328. _merge(target, source);
  329. });
  330. return target;
  331. }
  332. function _merge(target, source, deep) {
  333. for (var key in source) {
  334. if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
  335. if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
  336. target[key] = {};
  337. }
  338. if (isArray(source[key]) && !isArray(target[key])) {
  339. target[key] = [];
  340. }
  341. _merge(target[key], source[key], deep);
  342. } else if (source[key] !== undefined) {
  343. target[key] = source[key];
  344. }
  345. }
  346. }
  347. /**
  348. * Root Prefix Transform.
  349. */
  350. function root (options$$1, next) {
  351. var url = next(options$$1);
  352. if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) {
  353. url = trimEnd(options$$1.root, '/') + '/' + url;
  354. }
  355. return url;
  356. }
  357. /**
  358. * Query Parameter Transform.
  359. */
  360. function query (options$$1, next) {
  361. var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1);
  362. each(options$$1.params, function (value, key) {
  363. if (urlParams.indexOf(key) === -1) {
  364. query[key] = value;
  365. }
  366. });
  367. query = Url.params(query);
  368. if (query) {
  369. url += (url.indexOf('?') == -1 ? '?' : '&') + query;
  370. }
  371. return url;
  372. }
  373. /**
  374. * URL Template v2.0.6 (https://github.com/bramstein/url-template)
  375. */
  376. function expand(url, params, variables) {
  377. var tmpl = parse(url), expanded = tmpl.expand(params);
  378. if (variables) {
  379. variables.push.apply(variables, tmpl.vars);
  380. }
  381. return expanded;
  382. }
  383. function parse(template) {
  384. var operators = ['+', '#', '.', '/', ';', '?', '&'], variables = [];
  385. return {
  386. vars: variables,
  387. expand: function expand(context) {
  388. return template.replace(/\{([^{}]+)\}|([^{}]+)/g, function (_, expression, literal) {
  389. if (expression) {
  390. var operator = null, values = [];
  391. if (operators.indexOf(expression.charAt(0)) !== -1) {
  392. operator = expression.charAt(0);
  393. expression = expression.substr(1);
  394. }
  395. expression.split(/,/g).forEach(function (variable) {
  396. var tmp = /([^:*]*)(?::(\d+)|(\*))?/.exec(variable);
  397. values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
  398. variables.push(tmp[1]);
  399. });
  400. if (operator && operator !== '+') {
  401. var separator = ',';
  402. if (operator === '?') {
  403. separator = '&';
  404. } else if (operator !== '#') {
  405. separator = operator;
  406. }
  407. return (values.length !== 0 ? operator : '') + values.join(separator);
  408. } else {
  409. return values.join(',');
  410. }
  411. } else {
  412. return encodeReserved(literal);
  413. }
  414. });
  415. }
  416. };
  417. }
  418. function getValues(context, operator, key, modifier) {
  419. var value = context[key], result = [];
  420. if (isDefined(value) && value !== '') {
  421. if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  422. value = value.toString();
  423. if (modifier && modifier !== '*') {
  424. value = value.substring(0, parseInt(modifier, 10));
  425. }
  426. result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
  427. } else {
  428. if (modifier === '*') {
  429. if (Array.isArray(value)) {
  430. value.filter(isDefined).forEach(function (value) {
  431. result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
  432. });
  433. } else {
  434. Object.keys(value).forEach(function (k) {
  435. if (isDefined(value[k])) {
  436. result.push(encodeValue(operator, value[k], k));
  437. }
  438. });
  439. }
  440. } else {
  441. var tmp = [];
  442. if (Array.isArray(value)) {
  443. value.filter(isDefined).forEach(function (value) {
  444. tmp.push(encodeValue(operator, value));
  445. });
  446. } else {
  447. Object.keys(value).forEach(function (k) {
  448. if (isDefined(value[k])) {
  449. tmp.push(encodeURIComponent(k));
  450. tmp.push(encodeValue(operator, value[k].toString()));
  451. }
  452. });
  453. }
  454. if (isKeyOperator(operator)) {
  455. result.push(encodeURIComponent(key) + '=' + tmp.join(','));
  456. } else if (tmp.length !== 0) {
  457. result.push(tmp.join(','));
  458. }
  459. }
  460. }
  461. } else {
  462. if (operator === ';') {
  463. result.push(encodeURIComponent(key));
  464. } else if (value === '' && (operator === '&' || operator === '?')) {
  465. result.push(encodeURIComponent(key) + '=');
  466. } else if (value === '') {
  467. result.push('');
  468. }
  469. }
  470. return result;
  471. }
  472. function isDefined(value) {
  473. return value !== undefined && value !== null;
  474. }
  475. function isKeyOperator(operator) {
  476. return operator === ';' || operator === '&' || operator === '?';
  477. }
  478. function encodeValue(operator, value, key) {
  479. value = (operator === '+' || operator === '#') ? encodeReserved(value) : encodeURIComponent(value);
  480. if (key) {
  481. return encodeURIComponent(key) + '=' + value;
  482. } else {
  483. return value;
  484. }
  485. }
  486. function encodeReserved(str) {
  487. return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
  488. if (!/%[0-9A-Fa-f]/.test(part)) {
  489. part = encodeURI(part);
  490. }
  491. return part;
  492. }).join('');
  493. }
  494. /**
  495. * URL Template (RFC 6570) Transform.
  496. */
  497. function template (options) {
  498. var variables = [], url = expand(options.url, options.params, variables);
  499. variables.forEach(function (key) {
  500. delete options.params[key];
  501. });
  502. return url;
  503. }
  504. /**
  505. * Service for URL templating.
  506. */
  507. function Url(url, params) {
  508. var self = this || {}, options$$1 = url, transform;
  509. if (isString(url)) {
  510. options$$1 = {url: url, params: params};
  511. }
  512. options$$1 = merge({}, Url.options, self.$options, options$$1);
  513. Url.transforms.forEach(function (handler) {
  514. if (isString(handler)) {
  515. handler = Url.transform[handler];
  516. }
  517. if (isFunction(handler)) {
  518. transform = factory(handler, transform, self.$vm);
  519. }
  520. });
  521. return transform(options$$1);
  522. }
  523. /**
  524. * Url options.
  525. */
  526. Url.options = {
  527. url: '',
  528. root: null,
  529. params: {}
  530. };
  531. /**
  532. * Url transforms.
  533. */
  534. Url.transform = {template: template, query: query, root: root};
  535. Url.transforms = ['template', 'query', 'root'];
  536. /**
  537. * Encodes a Url parameter string.
  538. *
  539. * @param {Object} obj
  540. */
  541. Url.params = function (obj) {
  542. var params = [], escape = encodeURIComponent;
  543. params.add = function (key, value) {
  544. if (isFunction(value)) {
  545. value = value();
  546. }
  547. if (value === null) {
  548. value = '';
  549. }
  550. this.push(escape(key) + '=' + escape(value));
  551. };
  552. serialize(params, obj);
  553. return params.join('&').replace(/%20/g, '+');
  554. };
  555. /**
  556. * Parse a URL and return its components.
  557. *
  558. * @param {String} url
  559. */
  560. Url.parse = function (url) {
  561. var el = document.createElement('a');
  562. if (document.documentMode) {
  563. el.href = url;
  564. url = el.href;
  565. }
  566. el.href = url;
  567. return {
  568. href: el.href,
  569. protocol: el.protocol ? el.protocol.replace(/:$/, '') : '',
  570. port: el.port,
  571. host: el.host,
  572. hostname: el.hostname,
  573. pathname: el.pathname.charAt(0) === '/' ? el.pathname : '/' + el.pathname,
  574. search: el.search ? el.search.replace(/^\?/, '') : '',
  575. hash: el.hash ? el.hash.replace(/^#/, '') : ''
  576. };
  577. };
  578. function factory(handler, next, vm) {
  579. return function (options$$1) {
  580. return handler.call(vm, options$$1, next);
  581. };
  582. }
  583. function serialize(params, obj, scope) {
  584. var array = isArray(obj), plain = isPlainObject(obj), hash;
  585. each(obj, function (value, key) {
  586. hash = isObject(value) || isArray(value);
  587. if (scope) {
  588. key = scope + '[' + (plain || hash ? key : '') + ']';
  589. }
  590. if (!scope && array) {
  591. params.add(value.name, value.value);
  592. } else if (hash) {
  593. serialize(params, value, key);
  594. } else {
  595. params.add(key, value);
  596. }
  597. });
  598. }
  599. /**
  600. * XDomain client (Internet Explorer).
  601. */
  602. function xdrClient (request) {
  603. return new PromiseObj(function (resolve) {
  604. var xdr = new XDomainRequest(), handler = function (ref) {
  605. var type = ref.type;
  606. var status = 0;
  607. if (type === 'load') {
  608. status = 200;
  609. } else if (type === 'error') {
  610. status = 500;
  611. }
  612. resolve(request.respondWith(xdr.responseText, {status: status}));
  613. };
  614. request.abort = function () { return xdr.abort(); };
  615. xdr.open(request.method, request.getUrl());
  616. if (request.timeout) {
  617. xdr.timeout = request.timeout;
  618. }
  619. xdr.onload = handler;
  620. xdr.onabort = handler;
  621. xdr.onerror = handler;
  622. xdr.ontimeout = handler;
  623. xdr.onprogress = function () {};
  624. xdr.send(request.getBody());
  625. });
  626. }
  627. /**
  628. * CORS Interceptor.
  629. */
  630. var SUPPORTS_CORS = inBrowser && 'withCredentials' in new XMLHttpRequest();
  631. function cors (request) {
  632. if (inBrowser) {
  633. var orgUrl = Url.parse(location.href);
  634. var reqUrl = Url.parse(request.getUrl());
  635. if (reqUrl.protocol !== orgUrl.protocol || reqUrl.host !== orgUrl.host) {
  636. request.crossOrigin = true;
  637. request.emulateHTTP = false;
  638. if (!SUPPORTS_CORS) {
  639. request.client = xdrClient;
  640. }
  641. }
  642. }
  643. }
  644. /**
  645. * Form data Interceptor.
  646. */
  647. function form (request) {
  648. if (isFormData(request.body)) {
  649. request.headers.delete('Content-Type');
  650. } else if (isObject(request.body) && request.emulateJSON) {
  651. request.body = Url.params(request.body);
  652. request.headers.set('Content-Type', 'application/x-www-form-urlencoded');
  653. }
  654. }
  655. /**
  656. * JSON Interceptor.
  657. */
  658. function json (request) {
  659. var type = request.headers.get('Content-Type') || '';
  660. if (isObject(request.body) && type.indexOf('application/json') === 0) {
  661. request.body = JSON.stringify(request.body);
  662. }
  663. return function (response) {
  664. return response.bodyText ? when(response.text(), function (text) {
  665. var type = response.headers.get('Content-Type') || '';
  666. if (type.indexOf('application/json') === 0 || isJson(text)) {
  667. try {
  668. response.body = JSON.parse(text);
  669. } catch (e) {
  670. response.body = null;
  671. }
  672. } else {
  673. response.body = text;
  674. }
  675. return response;
  676. }) : response;
  677. };
  678. }
  679. function isJson(str) {
  680. var start = str.match(/^\s*(\[|\{)/);
  681. var end = {'[': /]\s*$/, '{': /}\s*$/};
  682. return start && end[start[1]].test(str);
  683. }
  684. /**
  685. * JSONP client (Browser).
  686. */
  687. function jsonpClient (request) {
  688. return new PromiseObj(function (resolve) {
  689. var name = request.jsonp || 'callback', callback = request.jsonpCallback || '_jsonp' + Math.random().toString(36).substr(2), body = null, handler, script;
  690. handler = function (ref) {
  691. var type = ref.type;
  692. var status = 0;
  693. if (type === 'load' && body !== null) {
  694. status = 200;
  695. } else if (type === 'error') {
  696. status = 500;
  697. }
  698. if (status && window[callback]) {
  699. delete window[callback];
  700. document.body.removeChild(script);
  701. }
  702. resolve(request.respondWith(body, {status: status}));
  703. };
  704. window[callback] = function (result) {
  705. body = JSON.stringify(result);
  706. };
  707. request.abort = function () {
  708. handler({type: 'abort'});
  709. };
  710. request.params[name] = callback;
  711. if (request.timeout) {
  712. setTimeout(request.abort, request.timeout);
  713. }
  714. script = document.createElement('script');
  715. script.src = request.getUrl();
  716. script.type = 'text/javascript';
  717. script.async = true;
  718. script.onload = handler;
  719. script.onerror = handler;
  720. document.body.appendChild(script);
  721. });
  722. }
  723. /**
  724. * JSONP Interceptor.
  725. */
  726. function jsonp (request) {
  727. if (request.method == 'JSONP') {
  728. request.client = jsonpClient;
  729. }
  730. }
  731. /**
  732. * Before Interceptor.
  733. */
  734. function before (request) {
  735. if (isFunction(request.before)) {
  736. request.before.call(this, request);
  737. }
  738. }
  739. /**
  740. * HTTP method override Interceptor.
  741. */
  742. function method (request) {
  743. if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) {
  744. request.headers.set('X-HTTP-Method-Override', request.method);
  745. request.method = 'POST';
  746. }
  747. }
  748. /**
  749. * Header Interceptor.
  750. */
  751. function header (request) {
  752. var headers = assign({}, Http.headers.common,
  753. !request.crossOrigin ? Http.headers.custom : {},
  754. Http.headers[toLower(request.method)]
  755. );
  756. each(headers, function (value, name) {
  757. if (!request.headers.has(name)) {
  758. request.headers.set(name, value);
  759. }
  760. });
  761. }
  762. /**
  763. * XMLHttp client (Browser).
  764. */
  765. function xhrClient (request) {
  766. return new PromiseObj(function (resolve) {
  767. var xhr = new XMLHttpRequest(), handler = function (event) {
  768. var response = request.respondWith(
  769. 'response' in xhr ? xhr.response : xhr.responseText, {
  770. status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug
  771. statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText)
  772. });
  773. each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) {
  774. response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1));
  775. });
  776. resolve(response);
  777. };
  778. request.abort = function () { return xhr.abort(); };
  779. xhr.open(request.method, request.getUrl(), true);
  780. if (request.timeout) {
  781. xhr.timeout = request.timeout;
  782. }
  783. if (request.responseType && 'responseType' in xhr) {
  784. xhr.responseType = request.responseType;
  785. }
  786. if (request.withCredentials || request.credentials) {
  787. xhr.withCredentials = true;
  788. }
  789. if (!request.crossOrigin) {
  790. request.headers.set('X-Requested-With', 'XMLHttpRequest');
  791. }
  792. // deprecated use downloadProgress
  793. if (isFunction(request.progress) && request.method === 'GET') {
  794. xhr.addEventListener('progress', request.progress);
  795. }
  796. if (isFunction(request.downloadProgress)) {
  797. xhr.addEventListener('progress', request.downloadProgress);
  798. }
  799. // deprecated use uploadProgress
  800. if (isFunction(request.progress) && /^(POST|PUT)$/i.test(request.method)) {
  801. xhr.upload.addEventListener('progress', request.progress);
  802. }
  803. if (isFunction(request.uploadProgress) && xhr.upload) {
  804. xhr.upload.addEventListener('progress', request.uploadProgress);
  805. }
  806. request.headers.forEach(function (value, name) {
  807. xhr.setRequestHeader(name, value);
  808. });
  809. xhr.onload = handler;
  810. xhr.onabort = handler;
  811. xhr.onerror = handler;
  812. xhr.ontimeout = handler;
  813. xhr.send(request.getBody());
  814. });
  815. }
  816. /**
  817. * Http client (Node).
  818. */
  819. function nodeClient (request) {
  820. var client = require('got');
  821. return new PromiseObj(function (resolve) {
  822. var url = request.getUrl();
  823. var body = request.getBody();
  824. var method = request.method;
  825. var headers = {}, handler;
  826. request.headers.forEach(function (value, name) {
  827. headers[name] = value;
  828. });
  829. client(url, {body: body, method: method, headers: headers}).then(handler = function (resp) {
  830. var response = request.respondWith(resp.body, {
  831. status: resp.statusCode,
  832. statusText: trim(resp.statusMessage)
  833. });
  834. each(resp.headers, function (value, name) {
  835. response.headers.set(name, value);
  836. });
  837. resolve(response);
  838. }, function (error$$1) { return handler(error$$1.response); });
  839. });
  840. }
  841. /**
  842. * Base client.
  843. */
  844. function Client (context) {
  845. var reqHandlers = [sendRequest], resHandlers = [];
  846. if (!isObject(context)) {
  847. context = null;
  848. }
  849. function Client(request) {
  850. while (reqHandlers.length) {
  851. var handler = reqHandlers.pop();
  852. if (isFunction(handler)) {
  853. var response = (void 0), next = (void 0);
  854. response = handler.call(context, request, function (val) { return next = val; }) || next;
  855. if (isObject(response)) {
  856. return new PromiseObj(function (resolve, reject) {
  857. resHandlers.forEach(function (handler) {
  858. response = when(response, function (response) {
  859. return handler.call(context, response) || response;
  860. }, reject);
  861. });
  862. when(response, resolve, reject);
  863. }, context);
  864. }
  865. if (isFunction(response)) {
  866. resHandlers.unshift(response);
  867. }
  868. } else {
  869. warn(("Invalid interceptor of type " + (typeof handler) + ", must be a function"));
  870. }
  871. }
  872. }
  873. Client.use = function (handler) {
  874. reqHandlers.push(handler);
  875. };
  876. return Client;
  877. }
  878. function sendRequest(request) {
  879. var client = request.client || (inBrowser ? xhrClient : nodeClient);
  880. return client(request);
  881. }
  882. /**
  883. * HTTP Headers.
  884. */
  885. var Headers = function Headers(headers) {
  886. var this$1 = this;
  887. this.map = {};
  888. each(headers, function (value, name) { return this$1.append(name, value); });
  889. };
  890. Headers.prototype.has = function has (name) {
  891. return getName(this.map, name) !== null;
  892. };
  893. Headers.prototype.get = function get (name) {
  894. var list = this.map[getName(this.map, name)];
  895. return list ? list.join() : null;
  896. };
  897. Headers.prototype.getAll = function getAll (name) {
  898. return this.map[getName(this.map, name)] || [];
  899. };
  900. Headers.prototype.set = function set (name, value) {
  901. this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
  902. };
  903. Headers.prototype.append = function append (name, value) {
  904. var list = this.map[getName(this.map, name)];
  905. if (list) {
  906. list.push(trim(value));
  907. } else {
  908. this.set(name, value);
  909. }
  910. };
  911. Headers.prototype.delete = function delete$1 (name) {
  912. delete this.map[getName(this.map, name)];
  913. };
  914. Headers.prototype.deleteAll = function deleteAll () {
  915. this.map = {};
  916. };
  917. Headers.prototype.forEach = function forEach (callback, thisArg) {
  918. var this$1 = this;
  919. each(this.map, function (list, name) {
  920. each(list, function (value) { return callback.call(thisArg, value, name, this$1); });
  921. });
  922. };
  923. function getName(map, name) {
  924. return Object.keys(map).reduce(function (prev, curr) {
  925. return toLower(name) === toLower(curr) ? curr : prev;
  926. }, null);
  927. }
  928. function normalizeName(name) {
  929. if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
  930. throw new TypeError('Invalid character in header field name');
  931. }
  932. return trim(name);
  933. }
  934. /**
  935. * HTTP Response.
  936. */
  937. var Response = function Response(body, ref) {
  938. var url = ref.url;
  939. var headers = ref.headers;
  940. var status = ref.status;
  941. var statusText = ref.statusText;
  942. this.url = url;
  943. this.ok = status >= 200 && status < 300;
  944. this.status = status || 0;
  945. this.statusText = statusText || '';
  946. this.headers = new Headers(headers);
  947. this.body = body;
  948. if (isString(body)) {
  949. this.bodyText = body;
  950. } else if (isBlob(body)) {
  951. this.bodyBlob = body;
  952. if (isBlobText(body)) {
  953. this.bodyText = blobText(body);
  954. }
  955. }
  956. };
  957. Response.prototype.blob = function blob () {
  958. return when(this.bodyBlob);
  959. };
  960. Response.prototype.text = function text () {
  961. return when(this.bodyText);
  962. };
  963. Response.prototype.json = function json () {
  964. return when(this.text(), function (text) { return JSON.parse(text); });
  965. };
  966. Object.defineProperty(Response.prototype, 'data', {
  967. get: function get() {
  968. return this.body;
  969. },
  970. set: function set(body) {
  971. this.body = body;
  972. }
  973. });
  974. function blobText(body) {
  975. return new PromiseObj(function (resolve) {
  976. var reader = new FileReader();
  977. reader.readAsText(body);
  978. reader.onload = function () {
  979. resolve(reader.result);
  980. };
  981. });
  982. }
  983. function isBlobText(body) {
  984. return body.type.indexOf('text') === 0 || body.type.indexOf('json') !== -1;
  985. }
  986. /**
  987. * HTTP Request.
  988. */
  989. var Request = function Request(options$$1) {
  990. this.body = null;
  991. this.params = {};
  992. assign(this, options$$1, {
  993. method: toUpper(options$$1.method || 'GET')
  994. });
  995. if (!(this.headers instanceof Headers)) {
  996. this.headers = new Headers(this.headers);
  997. }
  998. };
  999. Request.prototype.getUrl = function getUrl () {
  1000. return Url(this);
  1001. };
  1002. Request.prototype.getBody = function getBody () {
  1003. return this.body;
  1004. };
  1005. Request.prototype.respondWith = function respondWith (body, options$$1) {
  1006. return new Response(body, assign(options$$1 || {}, {url: this.getUrl()}));
  1007. };
  1008. /**
  1009. * Service for sending network requests.
  1010. */
  1011. var COMMON_HEADERS = {'Accept': 'application/json, text/plain, */*'};
  1012. var JSON_CONTENT_TYPE = {'Content-Type': 'application/json;charset=utf-8'};
  1013. function Http(options$$1) {
  1014. var self = this || {}, client = Client(self.$vm);
  1015. defaults(options$$1 || {}, self.$options, Http.options);
  1016. Http.interceptors.forEach(function (handler) {
  1017. if (isString(handler)) {
  1018. handler = Http.interceptor[handler];
  1019. }
  1020. if (isFunction(handler)) {
  1021. client.use(handler);
  1022. }
  1023. });
  1024. return client(new Request(options$$1)).then(function (response) {
  1025. return response.ok ? response : PromiseObj.reject(response);
  1026. }, function (response) {
  1027. if (response instanceof Error) {
  1028. error(response);
  1029. }
  1030. return PromiseObj.reject(response);
  1031. });
  1032. }
  1033. Http.options = {};
  1034. Http.headers = {
  1035. put: JSON_CONTENT_TYPE,
  1036. post: JSON_CONTENT_TYPE,
  1037. patch: JSON_CONTENT_TYPE,
  1038. delete: JSON_CONTENT_TYPE,
  1039. common: COMMON_HEADERS,
  1040. custom: {}
  1041. };
  1042. Http.interceptor = {before: before, method: method, jsonp: jsonp, json: json, form: form, header: header, cors: cors};
  1043. Http.interceptors = ['before', 'method', 'jsonp', 'json', 'form', 'header', 'cors'];
  1044. ['get', 'delete', 'head', 'jsonp'].forEach(function (method$$1) {
  1045. Http[method$$1] = function (url, options$$1) {
  1046. return this(assign(options$$1 || {}, {url: url, method: method$$1}));
  1047. };
  1048. });
  1049. ['post', 'put', 'patch'].forEach(function (method$$1) {
  1050. Http[method$$1] = function (url, body, options$$1) {
  1051. return this(assign(options$$1 || {}, {url: url, method: method$$1, body: body}));
  1052. };
  1053. });
  1054. /**
  1055. * Service for interacting with RESTful services.
  1056. */
  1057. function Resource(url, params, actions, options$$1) {
  1058. var self = this || {}, resource = {};
  1059. actions = assign({},
  1060. Resource.actions,
  1061. actions
  1062. );
  1063. each(actions, function (action, name) {
  1064. action = merge({url: url, params: assign({}, params)}, options$$1, action);
  1065. resource[name] = function () {
  1066. return (self.$http || Http)(opts(action, arguments));
  1067. };
  1068. });
  1069. return resource;
  1070. }
  1071. function opts(action, args) {
  1072. var options$$1 = assign({}, action), params = {}, body;
  1073. switch (args.length) {
  1074. case 2:
  1075. params = args[0];
  1076. body = args[1];
  1077. break;
  1078. case 1:
  1079. if (/^(POST|PUT|PATCH)$/i.test(options$$1.method)) {
  1080. body = args[0];
  1081. } else {
  1082. params = args[0];
  1083. }
  1084. break;
  1085. case 0:
  1086. break;
  1087. default:
  1088. throw 'Expected up to 2 arguments [params, body], got ' + args.length + ' arguments';
  1089. }
  1090. options$$1.body = body;
  1091. options$$1.params = assign({}, options$$1.params, params);
  1092. return options$$1;
  1093. }
  1094. Resource.actions = {
  1095. get: {method: 'GET'},
  1096. save: {method: 'POST'},
  1097. query: {method: 'GET'},
  1098. update: {method: 'PUT'},
  1099. remove: {method: 'DELETE'},
  1100. delete: {method: 'DELETE'}
  1101. };
  1102. /**
  1103. * Install plugin.
  1104. */
  1105. function plugin(Vue) {
  1106. if (plugin.installed) {
  1107. return;
  1108. }
  1109. Util(Vue);
  1110. Vue.url = Url;
  1111. Vue.http = Http;
  1112. Vue.resource = Resource;
  1113. Vue.Promise = PromiseObj;
  1114. Object.defineProperties(Vue.prototype, {
  1115. $url: {
  1116. get: function get() {
  1117. return options(Vue.url, this, this.$options.url);
  1118. }
  1119. },
  1120. $http: {
  1121. get: function get() {
  1122. return options(Vue.http, this, this.$options.http);
  1123. }
  1124. },
  1125. $resource: {
  1126. get: function get() {
  1127. return Vue.resource.bind(this);
  1128. }
  1129. },
  1130. $promise: {
  1131. get: function get() {
  1132. var this$1 = this;
  1133. return function (executor) { return new Vue.Promise(executor, this$1); };
  1134. }
  1135. }
  1136. });
  1137. }
  1138. if (typeof window !== 'undefined' && window.Vue) {
  1139. window.Vue.use(plugin);
  1140. }
  1141. return plugin;
  1142. })));