ParseFile.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  3. var _Object$defineProperties = require("@babel/runtime-corejs3/core-js-stable/object/define-properties");
  4. var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors");
  5. var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
  6. var _filterInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/filter");
  7. var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols");
  8. var _Object$keys2 = require("@babel/runtime-corejs3/core-js-stable/object/keys");
  9. var _sliceInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/slice");
  10. var _reverseInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/reverse");
  11. var _Promise2 = require("@babel/runtime-corejs3/core-js-stable/promise");
  12. var _Object$setPrototypeOf = require("@babel/runtime-corejs3/core-js-stable/object/set-prototype-of");
  13. var _typeof3 = require("@babel/runtime-corejs3/helpers/typeof");
  14. var _forEachInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/for-each");
  15. var _Object$getPrototypeOf = require("@babel/runtime-corejs3/core-js-stable/object/get-prototype-of");
  16. var _Object$create = require("@babel/runtime-corejs3/core-js-stable/object/create");
  17. var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
  18. var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");
  19. _Object$defineProperty(exports, "__esModule", {
  20. value: true
  21. });
  22. exports.default = void 0;
  23. var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
  24. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));
  25. var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
  26. var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
  27. var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
  28. var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));
  29. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));
  30. var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
  31. var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
  32. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/classCallCheck"));
  33. var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/createClass"));
  34. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
  35. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  36. function ownKeys(object, enumerableOnly) {
  37. var keys = _Object$keys2(object);
  38. if (_Object$getOwnPropertySymbols) {
  39. var symbols = _Object$getOwnPropertySymbols(object);
  40. enumerableOnly && (symbols = _filterInstanceProperty(symbols).call(symbols, function (sym) {
  41. return _Object$getOwnPropertyDescriptor(object, sym).enumerable;
  42. })), keys.push.apply(keys, symbols);
  43. }
  44. return keys;
  45. }
  46. function _objectSpread(target) {
  47. for (var i = 1; i < arguments.length; i++) {
  48. var _context10, _context11;
  49. var source = null != arguments[i] ? arguments[i] : {};
  50. i % 2 ? _forEachInstanceProperty2(_context10 = ownKeys(Object(source), !0)).call(_context10, function (key) {
  51. (0, _defineProperty2.default)(target, key, source[key]);
  52. }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(target, _Object$getOwnPropertyDescriptors(source)) : _forEachInstanceProperty2(_context11 = ownKeys(Object(source))).call(_context11, function (key) {
  53. _Object$defineProperty(target, key, _Object$getOwnPropertyDescriptor(source, key));
  54. });
  55. }
  56. return target;
  57. }
  58. function _regeneratorRuntime() {
  59. "use strict";
  60. /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  61. _regeneratorRuntime = function () {
  62. return exports;
  63. };
  64. var exports = {},
  65. Op = Object.prototype,
  66. hasOwn = Op.hasOwnProperty,
  67. $Symbol = "function" == typeof _Symbol ? _Symbol : {},
  68. iteratorSymbol = $Symbol.iterator || "@@iterator",
  69. asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
  70. toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  71. function define(obj, key, value) {
  72. return _Object$defineProperty(obj, key, {
  73. value: value,
  74. enumerable: !0,
  75. configurable: !0,
  76. writable: !0
  77. }), obj[key];
  78. }
  79. try {
  80. define({}, "");
  81. } catch (err) {
  82. define = function (obj, key, value) {
  83. return obj[key] = value;
  84. };
  85. }
  86. function wrap(innerFn, outerFn, self, tryLocsList) {
  87. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
  88. generator = _Object$create(protoGenerator.prototype),
  89. context = new Context(tryLocsList || []);
  90. return generator._invoke = function (innerFn, self, context) {
  91. var state = "suspendedStart";
  92. return function (method, arg) {
  93. if ("executing" === state) throw new Error("Generator is already running");
  94. if ("completed" === state) {
  95. if ("throw" === method) throw arg;
  96. return doneResult();
  97. }
  98. for (context.method = method, context.arg = arg;;) {
  99. var delegate = context.delegate;
  100. if (delegate) {
  101. var delegateResult = maybeInvokeDelegate(delegate, context);
  102. if (delegateResult) {
  103. if (delegateResult === ContinueSentinel) continue;
  104. return delegateResult;
  105. }
  106. }
  107. if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
  108. if ("suspendedStart" === state) throw state = "completed", context.arg;
  109. context.dispatchException(context.arg);
  110. } else "return" === context.method && context.abrupt("return", context.arg);
  111. state = "executing";
  112. var record = tryCatch(innerFn, self, context);
  113. if ("normal" === record.type) {
  114. if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
  115. return {
  116. value: record.arg,
  117. done: context.done
  118. };
  119. }
  120. "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
  121. }
  122. };
  123. }(innerFn, self, context), generator;
  124. }
  125. function tryCatch(fn, obj, arg) {
  126. try {
  127. return {
  128. type: "normal",
  129. arg: fn.call(obj, arg)
  130. };
  131. } catch (err) {
  132. return {
  133. type: "throw",
  134. arg: err
  135. };
  136. }
  137. }
  138. exports.wrap = wrap;
  139. var ContinueSentinel = {};
  140. function Generator() {}
  141. function GeneratorFunction() {}
  142. function GeneratorFunctionPrototype() {}
  143. var IteratorPrototype = {};
  144. define(IteratorPrototype, iteratorSymbol, function () {
  145. return this;
  146. });
  147. var getProto = _Object$getPrototypeOf,
  148. NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  149. NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
  150. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = _Object$create(IteratorPrototype);
  151. function defineIteratorMethods(prototype) {
  152. var _context8;
  153. _forEachInstanceProperty2(_context8 = ["next", "throw", "return"]).call(_context8, function (method) {
  154. define(prototype, method, function (arg) {
  155. return this._invoke(method, arg);
  156. });
  157. });
  158. }
  159. function AsyncIterator(generator, PromiseImpl) {
  160. function invoke(method, arg, resolve, reject) {
  161. var record = tryCatch(generator[method], generator, arg);
  162. if ("throw" !== record.type) {
  163. var result = record.arg,
  164. value = result.value;
  165. return value && "object" == _typeof3(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
  166. invoke("next", value, resolve, reject);
  167. }, function (err) {
  168. invoke("throw", err, resolve, reject);
  169. }) : PromiseImpl.resolve(value).then(function (unwrapped) {
  170. result.value = unwrapped, resolve(result);
  171. }, function (error) {
  172. return invoke("throw", error, resolve, reject);
  173. });
  174. }
  175. reject(record.arg);
  176. }
  177. var previousPromise;
  178. this._invoke = function (method, arg) {
  179. function callInvokeWithMethodAndArg() {
  180. return new PromiseImpl(function (resolve, reject) {
  181. invoke(method, arg, resolve, reject);
  182. });
  183. }
  184. return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  185. };
  186. }
  187. function maybeInvokeDelegate(delegate, context) {
  188. var method = delegate.iterator[context.method];
  189. if (undefined === method) {
  190. if (context.delegate = null, "throw" === context.method) {
  191. if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
  192. context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
  193. }
  194. return ContinueSentinel;
  195. }
  196. var record = tryCatch(method, delegate.iterator, context.arg);
  197. if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
  198. var info = record.arg;
  199. return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
  200. }
  201. function pushTryEntry(locs) {
  202. var entry = {
  203. tryLoc: locs[0]
  204. };
  205. 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
  206. }
  207. function resetTryEntry(entry) {
  208. var record = entry.completion || {};
  209. record.type = "normal", delete record.arg, entry.completion = record;
  210. }
  211. function Context(tryLocsList) {
  212. this.tryEntries = [{
  213. tryLoc: "root"
  214. }], _forEachInstanceProperty2(tryLocsList).call(tryLocsList, pushTryEntry, this), this.reset(!0);
  215. }
  216. function values(iterable) {
  217. if (iterable) {
  218. var iteratorMethod = iterable[iteratorSymbol];
  219. if (iteratorMethod) return iteratorMethod.call(iterable);
  220. if ("function" == typeof iterable.next) return iterable;
  221. if (!isNaN(iterable.length)) {
  222. var i = -1,
  223. next = function next() {
  224. for (; ++i < iterable.length;) {
  225. if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
  226. }
  227. return next.value = undefined, next.done = !0, next;
  228. };
  229. return next.next = next;
  230. }
  231. }
  232. return {
  233. next: doneResult
  234. };
  235. }
  236. function doneResult() {
  237. return {
  238. value: undefined,
  239. done: !0
  240. };
  241. }
  242. return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
  243. var ctor = "function" == typeof genFun && genFun.constructor;
  244. return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
  245. }, exports.mark = function (genFun) {
  246. return _Object$setPrototypeOf ? _Object$setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = _Object$create(Gp), genFun;
  247. }, exports.awrap = function (arg) {
  248. return {
  249. __await: arg
  250. };
  251. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
  252. return this;
  253. }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  254. void 0 === PromiseImpl && (PromiseImpl = _Promise2);
  255. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  256. return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
  257. return result.done ? result.value : iter.next();
  258. });
  259. }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
  260. return this;
  261. }), define(Gp, "toString", function () {
  262. return "[object Generator]";
  263. }), exports.keys = function (object) {
  264. var keys = [];
  265. for (var key in object) {
  266. keys.push(key);
  267. }
  268. return _reverseInstanceProperty(keys).call(keys), function next() {
  269. for (; keys.length;) {
  270. var key = keys.pop();
  271. if (key in object) return next.value = key, next.done = !1, next;
  272. }
  273. return next.done = !0, next;
  274. };
  275. }, exports.values = values, Context.prototype = {
  276. constructor: Context,
  277. reset: function (skipTempReset) {
  278. var _context9;
  279. if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, _forEachInstanceProperty2(_context9 = this.tryEntries).call(_context9, resetTryEntry), !skipTempReset) for (var name in this) {
  280. "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+_sliceInstanceProperty2(name).call(name, 1)) && (this[name] = undefined);
  281. }
  282. },
  283. stop: function () {
  284. this.done = !0;
  285. var rootRecord = this.tryEntries[0].completion;
  286. if ("throw" === rootRecord.type) throw rootRecord.arg;
  287. return this.rval;
  288. },
  289. dispatchException: function (exception) {
  290. if (this.done) throw exception;
  291. var context = this;
  292. function handle(loc, caught) {
  293. return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
  294. }
  295. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  296. var entry = this.tryEntries[i],
  297. record = entry.completion;
  298. if ("root" === entry.tryLoc) return handle("end");
  299. if (entry.tryLoc <= this.prev) {
  300. var hasCatch = hasOwn.call(entry, "catchLoc"),
  301. hasFinally = hasOwn.call(entry, "finallyLoc");
  302. if (hasCatch && hasFinally) {
  303. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  304. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  305. } else if (hasCatch) {
  306. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  307. } else {
  308. if (!hasFinally) throw new Error("try statement without catch or finally");
  309. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  310. }
  311. }
  312. }
  313. },
  314. abrupt: function (type, arg) {
  315. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  316. var entry = this.tryEntries[i];
  317. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  318. var finallyEntry = entry;
  319. break;
  320. }
  321. }
  322. finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
  323. var record = finallyEntry ? finallyEntry.completion : {};
  324. return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
  325. },
  326. complete: function (record, afterLoc) {
  327. if ("throw" === record.type) throw record.arg;
  328. return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
  329. },
  330. finish: function (finallyLoc) {
  331. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  332. var entry = this.tryEntries[i];
  333. if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
  334. }
  335. },
  336. catch: function (tryLoc) {
  337. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  338. var entry = this.tryEntries[i];
  339. if (entry.tryLoc === tryLoc) {
  340. var record = entry.completion;
  341. if ("throw" === record.type) {
  342. var thrown = record.arg;
  343. resetTryEntry(entry);
  344. }
  345. return thrown;
  346. }
  347. }
  348. throw new Error("illegal catch attempt");
  349. },
  350. delegateYield: function (iterable, resultName, nextLoc) {
  351. return this.delegate = {
  352. iterator: values(iterable),
  353. resultName: resultName,
  354. nextLoc: nextLoc
  355. }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
  356. }
  357. }, exports;
  358. }
  359. var ParseError = require('./ParseError').default;
  360. var XHR = null;
  361. if (typeof XMLHttpRequest !== 'undefined') {
  362. XHR = XMLHttpRequest;
  363. }
  364. /*:: type Base64 = { base64: string };*/
  365. /*:: type Uri = { uri: string };*/
  366. /*:: type FileData = Array<number> | Base64 | Blob | Uri;*/
  367. /*:: export type FileSource =
  368. | {
  369. format: 'file',
  370. file: Blob,
  371. type: string,
  372. }
  373. | {
  374. format: 'base64',
  375. base64: string,
  376. type: string,
  377. }
  378. | {
  379. format: 'uri',
  380. uri: string,
  381. type: string,
  382. };*/
  383. function b64Digit(number
  384. /*: number*/
  385. )
  386. /*: string*/
  387. {
  388. if (number < 26) {
  389. return String.fromCharCode(65 + number);
  390. }
  391. if (number < 52) {
  392. return String.fromCharCode(97 + (number - 26));
  393. }
  394. if (number < 62) {
  395. return String.fromCharCode(48 + (number - 52));
  396. }
  397. if (number === 62) {
  398. return '+';
  399. }
  400. if (number === 63) {
  401. return '/';
  402. }
  403. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  404. }
  405. /**
  406. * A Parse.File is a local representation of a file that is saved to the Parse
  407. * cloud.
  408. *
  409. * @alias Parse.File
  410. */
  411. var ParseFile = /*#__PURE__*/function () {
  412. /**
  413. * @param name {String} The file's name. This will be prefixed by a unique
  414. * value once the file has finished saving. The file name must begin with
  415. * an alphanumeric character, and consist of alphanumeric characters,
  416. * periods, spaces, underscores, or dashes.
  417. * @param data {Array} The data for the file, as either:
  418. * 1. an Array of byte value Numbers, or
  419. * 2. an Object like { base64: "..." } with a base64-encoded String.
  420. * 3. an Object like { uri: "..." } with a uri String.
  421. * 4. a File object selected with a file upload control. (3) only works
  422. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  423. * For example:
  424. * <pre>
  425. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  426. * if (fileUploadControl.files.length > 0) {
  427. * var file = fileUploadControl.files[0];
  428. * var name = "photo.jpg";
  429. * var parseFile = new Parse.File(name, file);
  430. * parseFile.save().then(function() {
  431. * // The file has been saved to Parse.
  432. * }, function(error) {
  433. * // The file either could not be read, or could not be saved to Parse.
  434. * });
  435. * }</pre>
  436. * @param type {String} Optional Content-Type header to use for the file. If
  437. * this is omitted, the content type will be inferred from the name's
  438. * extension.
  439. * @param metadata {Object} Optional key value pairs to be stored with file object
  440. * @param tags {Object} Optional key value pairs to be stored with file object
  441. */
  442. function ParseFile(name
  443. /*: string*/
  444. , data
  445. /*:: ?: FileData*/
  446. , type
  447. /*:: ?: string*/
  448. , metadata
  449. /*:: ?: Object*/
  450. , tags
  451. /*:: ?: Object*/
  452. ) {
  453. (0, _classCallCheck2.default)(this, ParseFile);
  454. (0, _defineProperty2.default)(this, "_name", void 0);
  455. (0, _defineProperty2.default)(this, "_url", void 0);
  456. (0, _defineProperty2.default)(this, "_source", void 0);
  457. (0, _defineProperty2.default)(this, "_previousSave", void 0);
  458. (0, _defineProperty2.default)(this, "_data", void 0);
  459. (0, _defineProperty2.default)(this, "_requestTask", void 0);
  460. (0, _defineProperty2.default)(this, "_metadata", void 0);
  461. (0, _defineProperty2.default)(this, "_tags", void 0);
  462. var specifiedType = type || '';
  463. this._name = name;
  464. this._metadata = metadata || {};
  465. this._tags = tags || {};
  466. if (data !== undefined) {
  467. if ((0, _isArray.default)(data)) {
  468. this._data = ParseFile.encodeBase64(data);
  469. this._source = {
  470. format: 'base64',
  471. base64: this._data,
  472. type: specifiedType
  473. };
  474. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  475. this._source = {
  476. format: 'file',
  477. file: data,
  478. type: specifiedType
  479. };
  480. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  481. this._source = {
  482. format: 'uri',
  483. uri: data.uri,
  484. type: specifiedType
  485. };
  486. } else if (data && typeof data.base64 === 'string') {
  487. var _context, _context2, _context3;
  488. var base64 = (0, _slice.default)(_context = data.base64.split(',')).call(_context, -1)[0];
  489. var dataType = specifiedType || (0, _slice.default)(_context2 = (0, _slice.default)(_context3 = data.base64.split(';')).call(_context3, 0, 1)[0].split(':')).call(_context2, 1, 2)[0] || 'text/plain';
  490. this._data = base64;
  491. this._source = {
  492. format: 'base64',
  493. base64: base64,
  494. type: dataType
  495. };
  496. } else {
  497. throw new TypeError('Cannot create a Parse.File with that data.');
  498. }
  499. }
  500. }
  501. /**
  502. * Return the data for the file, downloading it if not already present.
  503. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  504. * Data is cleared if saved with File object selected with a file upload control
  505. *
  506. * @returns {Promise} Promise that is resolve with base64 data
  507. */
  508. (0, _createClass2.default)(ParseFile, [{
  509. key: "getData",
  510. value: function () {
  511. var _getData = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
  512. var _this = this;
  513. var options, controller, result;
  514. return _regeneratorRuntime().wrap(function (_context4) {
  515. while (1) {
  516. switch (_context4.prev = _context4.next) {
  517. case 0:
  518. if (!this._data) {
  519. _context4.next = 2;
  520. break;
  521. }
  522. return _context4.abrupt("return", this._data);
  523. case 2:
  524. if (this._url) {
  525. _context4.next = 4;
  526. break;
  527. }
  528. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  529. case 4:
  530. options = {
  531. requestTask: function (task) {
  532. return _this._requestTask = task;
  533. }
  534. };
  535. controller = _CoreManager.default.getFileController();
  536. _context4.next = 8;
  537. return controller.download(this._url, options);
  538. case 8:
  539. result = _context4.sent;
  540. this._data = result.base64;
  541. return _context4.abrupt("return", this._data);
  542. case 11:
  543. case "end":
  544. return _context4.stop();
  545. }
  546. }
  547. }, _callee, this);
  548. }));
  549. function getData() {
  550. return _getData.apply(this, arguments);
  551. }
  552. return getData;
  553. }()
  554. /**
  555. * Gets the name of the file. Before save is called, this is the filename
  556. * given by the user. After save is called, that name gets prefixed with a
  557. * unique identifier.
  558. *
  559. * @returns {string}
  560. */
  561. }, {
  562. key: "name",
  563. value: function ()
  564. /*: string*/
  565. {
  566. return this._name;
  567. }
  568. /**
  569. * Gets the url of the file. It is only available after you save the file or
  570. * after you get the file from a Parse.Object.
  571. *
  572. * @param {object} options An object to specify url options
  573. * @returns {string}
  574. */
  575. }, {
  576. key: "url",
  577. value: function (options
  578. /*:: ?: { forceSecure?: boolean }*/
  579. )
  580. /*: ?string*/
  581. {
  582. options = options || {};
  583. if (!this._url) {
  584. return;
  585. }
  586. if (options.forceSecure) {
  587. return this._url.replace(/^http:\/\//i, 'https://');
  588. } else {
  589. return this._url;
  590. }
  591. }
  592. /**
  593. * Gets the metadata of the file.
  594. *
  595. * @returns {object}
  596. */
  597. }, {
  598. key: "metadata",
  599. value: function ()
  600. /*: Object*/
  601. {
  602. return this._metadata;
  603. }
  604. /**
  605. * Gets the tags of the file.
  606. *
  607. * @returns {object}
  608. */
  609. }, {
  610. key: "tags",
  611. value: function ()
  612. /*: Object*/
  613. {
  614. return this._tags;
  615. }
  616. /**
  617. * Saves the file to the Parse cloud.
  618. *
  619. * @param {object} options
  620. * * Valid options are:<ul>
  621. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  622. * be used for this request.
  623. * <li>sessionToken: A valid session token, used for making a request on
  624. * behalf of a specific user.
  625. * <li>progress: In Browser only, callback for upload progress. For example:
  626. * <pre>
  627. * let parseFile = new Parse.File(name, file);
  628. * parseFile.save({
  629. * progress: (progressValue, loaded, total, { type }) => {
  630. * if (type === "upload" && progressValue !== null) {
  631. * // Update the UI using progressValue
  632. * }
  633. * }
  634. * });
  635. * </pre>
  636. * </ul>
  637. * @returns {Promise} Promise that is resolved when the save finishes.
  638. */
  639. }, {
  640. key: "save",
  641. value: function (options
  642. /*:: ?: FullOptions*/
  643. ) {
  644. var _this2 = this;
  645. options = options || {};
  646. options.requestTask = function (task) {
  647. return _this2._requestTask = task;
  648. };
  649. options.metadata = this._metadata;
  650. options.tags = this._tags;
  651. var controller = _CoreManager.default.getFileController();
  652. if (!this._previousSave) {
  653. if (this._source.format === 'file') {
  654. this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
  655. _this2._name = res.name;
  656. _this2._url = res.url;
  657. _this2._data = null;
  658. _this2._requestTask = null;
  659. return _this2;
  660. });
  661. } else if (this._source.format === 'uri') {
  662. this._previousSave = controller.download(this._source.uri, options).then(function (result) {
  663. if (!(result && result.base64)) {
  664. return {};
  665. }
  666. var newSource = {
  667. format: 'base64',
  668. base64: result.base64,
  669. type: result.contentType
  670. };
  671. _this2._data = result.base64;
  672. _this2._requestTask = null;
  673. return controller.saveBase64(_this2._name, newSource, options);
  674. }).then(function (res) {
  675. _this2._name = res.name;
  676. _this2._url = res.url;
  677. _this2._requestTask = null;
  678. return _this2;
  679. });
  680. } else {
  681. this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
  682. _this2._name = res.name;
  683. _this2._url = res.url;
  684. _this2._requestTask = null;
  685. return _this2;
  686. });
  687. }
  688. }
  689. if (this._previousSave) {
  690. return this._previousSave;
  691. }
  692. }
  693. /**
  694. * Aborts the request if it has already been sent.
  695. */
  696. }, {
  697. key: "cancel",
  698. value: function () {
  699. if (this._requestTask && typeof this._requestTask.abort === 'function') {
  700. this._requestTask.abort();
  701. }
  702. this._requestTask = null;
  703. }
  704. /**
  705. * Deletes the file from the Parse cloud.
  706. * In Cloud Code and Node only with Master Key.
  707. *
  708. * @param {object} options
  709. * * Valid options are:<ul>
  710. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  711. * be used for this request.
  712. * <pre>
  713. * @returns {Promise} Promise that is resolved when the delete finishes.
  714. */
  715. }, {
  716. key: "destroy",
  717. value: function () {
  718. var _this3 = this;
  719. var options
  720. /*:: ?: FullOptions*/
  721. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  722. if (!this._name) {
  723. throw new ParseError(ParseError.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
  724. }
  725. var destroyOptions = {
  726. useMasterKey: true
  727. };
  728. if (options.hasOwnProperty('useMasterKey')) {
  729. destroyOptions.useMasterKey = options.useMasterKey;
  730. }
  731. var controller = _CoreManager.default.getFileController();
  732. return controller.deleteFile(this._name, destroyOptions).then(function () {
  733. _this3._data = null;
  734. _this3._requestTask = null;
  735. return _this3;
  736. });
  737. }
  738. }, {
  739. key: "toJSON",
  740. value: function ()
  741. /*: { name: ?string, url: ?string }*/
  742. {
  743. return {
  744. __type: 'File',
  745. name: this._name,
  746. url: this._url
  747. };
  748. }
  749. }, {
  750. key: "equals",
  751. value: function (other
  752. /*: mixed*/
  753. )
  754. /*: boolean*/
  755. {
  756. if (this === other) {
  757. return true;
  758. } // Unsaved Files are never equal, since they will be saved to different URLs
  759. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  760. }
  761. /**
  762. * Sets metadata to be saved with file object. Overwrites existing metadata
  763. *
  764. * @param {object} metadata Key value pairs to be stored with file object
  765. */
  766. }, {
  767. key: "setMetadata",
  768. value: function (metadata
  769. /*: any*/
  770. ) {
  771. var _this4 = this;
  772. if (metadata && (0, _typeof2.default)(metadata) === 'object') {
  773. var _context5;
  774. (0, _forEach.default)(_context5 = (0, _keys.default)(metadata)).call(_context5, function (key) {
  775. _this4.addMetadata(key, metadata[key]);
  776. });
  777. }
  778. }
  779. /**
  780. * Sets metadata to be saved with file object. Adds to existing metadata.
  781. *
  782. * @param {string} key key to store the metadata
  783. * @param {*} value metadata
  784. */
  785. }, {
  786. key: "addMetadata",
  787. value: function (key
  788. /*: string*/
  789. , value
  790. /*: any*/
  791. ) {
  792. if (typeof key === 'string') {
  793. this._metadata[key] = value;
  794. }
  795. }
  796. /**
  797. * Sets tags to be saved with file object. Overwrites existing tags
  798. *
  799. * @param {object} tags Key value pairs to be stored with file object
  800. */
  801. }, {
  802. key: "setTags",
  803. value: function (tags
  804. /*: any*/
  805. ) {
  806. var _this5 = this;
  807. if (tags && (0, _typeof2.default)(tags) === 'object') {
  808. var _context6;
  809. (0, _forEach.default)(_context6 = (0, _keys.default)(tags)).call(_context6, function (key) {
  810. _this5.addTag(key, tags[key]);
  811. });
  812. }
  813. }
  814. /**
  815. * Sets tags to be saved with file object. Adds to existing tags.
  816. *
  817. * @param {string} key key to store tags
  818. * @param {*} value tag
  819. */
  820. }, {
  821. key: "addTag",
  822. value: function (key
  823. /*: string*/
  824. , value
  825. /*: string*/
  826. ) {
  827. if (typeof key === 'string') {
  828. this._tags[key] = value;
  829. }
  830. }
  831. }], [{
  832. key: "fromJSON",
  833. value: function (obj)
  834. /*: ParseFile*/
  835. {
  836. if (obj.__type !== 'File') {
  837. throw new TypeError('JSON object does not represent a ParseFile');
  838. }
  839. var file = new ParseFile(obj.name);
  840. file._url = obj.url;
  841. return file;
  842. }
  843. }, {
  844. key: "encodeBase64",
  845. value: function (bytes
  846. /*: Array<number>*/
  847. )
  848. /*: string*/
  849. {
  850. var chunks = [];
  851. chunks.length = Math.ceil(bytes.length / 3);
  852. for (var i = 0; i < chunks.length; i++) {
  853. var b1 = bytes[i * 3];
  854. var b2 = bytes[i * 3 + 1] || 0;
  855. var b3 = bytes[i * 3 + 2] || 0;
  856. var has2 = i * 3 + 1 < bytes.length;
  857. var has3 = i * 3 + 2 < bytes.length;
  858. chunks[i] = [b64Digit(b1 >> 2 & 0x3f), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0f), has2 ? b64Digit(b2 << 2 & 0x3c | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3f) : '='].join('');
  859. }
  860. return chunks.join('');
  861. }
  862. }]);
  863. return ParseFile;
  864. }();
  865. var DefaultController = {
  866. saveFile: function () {
  867. var _saveFile = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(name
  868. /*: string*/
  869. , source
  870. /*: FileSource*/
  871. , options
  872. /*:: ?: FullOptions*/
  873. ) {
  874. var base64Data, _base64Data$split, _base64Data$split2, first, second, data, newSource;
  875. return _regeneratorRuntime().wrap(function _callee2$(_context7) {
  876. while (1) {
  877. switch (_context7.prev = _context7.next) {
  878. case 0:
  879. if (!(source.format !== 'file')) {
  880. _context7.next = 2;
  881. break;
  882. }
  883. throw new Error('saveFile can only be used with File-type sources.');
  884. case 2:
  885. _context7.next = 4;
  886. return new _promise.default(function (res, rej) {
  887. // eslint-disable-next-line no-undef
  888. var reader = new FileReader();
  889. reader.onload = function () {
  890. return res(reader.result);
  891. };
  892. reader.onerror = function (error) {
  893. return rej(error);
  894. };
  895. reader.readAsDataURL(source.file);
  896. });
  897. case 4:
  898. base64Data = _context7.sent; // we only want the data after the comma
  899. // For example: "data:application/pdf;base64,JVBERi0xLjQKJ..." we would only want "JVBERi0xLjQKJ..."
  900. _base64Data$split = base64Data.split(','), _base64Data$split2 = (0, _slicedToArray2.default)(_base64Data$split, 2), first = _base64Data$split2[0], second = _base64Data$split2[1]; // in the event there is no 'data:application/pdf;base64,' at the beginning of the base64 string
  901. // use the entire string instead
  902. data = second ? second : first;
  903. newSource = {
  904. format: 'base64',
  905. base64: data,
  906. type: source.type || (source.file ? source.file.type : null)
  907. };
  908. _context7.next = 10;
  909. return DefaultController.saveBase64(name, newSource, options);
  910. case 10:
  911. return _context7.abrupt("return", _context7.sent);
  912. case 11:
  913. case "end":
  914. return _context7.stop();
  915. }
  916. }
  917. }, _callee2);
  918. }));
  919. function saveFile(_x, _x2, _x3) {
  920. return _saveFile.apply(this, arguments);
  921. }
  922. return saveFile;
  923. }(),
  924. saveBase64: function saveBase64(name
  925. /*: string*/
  926. , source
  927. /*: FileSource*/
  928. , options
  929. /*:: ?: FullOptions*/
  930. ) {
  931. if (source.format !== 'base64') {
  932. throw new Error('saveBase64 can only be used with Base64-type sources.');
  933. }
  934. var data
  935. /*: { base64: any, _ContentType?: any, fileData: Object }*/
  936. = {
  937. base64: source.base64,
  938. fileData: {
  939. metadata: _objectSpread({}, options.metadata),
  940. tags: _objectSpread({}, options.tags)
  941. }
  942. };
  943. delete options.metadata;
  944. delete options.tags;
  945. if (source.type) {
  946. data._ContentType = source.type;
  947. }
  948. var path = 'files/' + name;
  949. return _CoreManager.default.getRESTController().request('POST', path, data, options);
  950. },
  951. download: function download(uri, options) {
  952. if (XHR) {
  953. return this.downloadAjax(uri, options);
  954. } else {
  955. return _promise.default.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  956. }
  957. },
  958. downloadAjax: function downloadAjax(uri, options) {
  959. return new _promise.default(function (resolve, reject) {
  960. var xhr = new XHR();
  961. xhr.open('GET', uri, true);
  962. xhr.responseType = 'arraybuffer';
  963. xhr.onerror = function (e) {
  964. reject(e);
  965. };
  966. xhr.onreadystatechange = function () {
  967. if (xhr.readyState !== xhr.DONE) {
  968. return;
  969. }
  970. if (!this.response) {
  971. return resolve({});
  972. }
  973. var bytes = new Uint8Array(this.response);
  974. resolve({
  975. base64: ParseFile.encodeBase64(bytes),
  976. contentType: xhr.getResponseHeader('content-type')
  977. });
  978. };
  979. options.requestTask(xhr);
  980. xhr.send();
  981. });
  982. },
  983. deleteFile: function deleteFile(name
  984. /*: string*/
  985. , options
  986. /*:: ?: FullOptions*/
  987. ) {
  988. var headers = {
  989. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID')
  990. };
  991. if (options.useMasterKey) {
  992. headers['X-Parse-Master-Key'] = _CoreManager.default.get('MASTER_KEY');
  993. }
  994. var url = _CoreManager.default.get('SERVER_URL');
  995. if (url[url.length - 1] !== '/') {
  996. url += '/';
  997. }
  998. url += 'files/' + name;
  999. return _CoreManager.default.getRESTController().ajax('DELETE', url, '', headers).catch(function (response) {
  1000. // TODO: return JSON object in server
  1001. if (!response || response === 'SyntaxError: Unexpected end of JSON input') {
  1002. return _promise.default.resolve();
  1003. } else {
  1004. return _CoreManager.default.getRESTController().handleError(response);
  1005. }
  1006. });
  1007. },
  1008. _setXHR: function _setXHR(xhr
  1009. /*: any*/
  1010. ) {
  1011. XHR = xhr;
  1012. },
  1013. _getXHR: function _getXHR() {
  1014. return XHR;
  1015. }
  1016. };
  1017. _CoreManager.default.setFileController(DefaultController);
  1018. var _default = ParseFile;
  1019. exports.default = _default;
  1020. exports.b64Digit = b64Digit;