vue-resource.common.js 35 KB

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