UNPKG

16.9 kBJavaScriptView Raw
1import { fromEvent, Observable } from 'rxjs';
2export var ERR_CORDOVA_NOT_AVAILABLE = { error: 'cordova_not_available' };
3export var ERR_PLUGIN_NOT_INSTALLED = { error: 'plugin_not_installed' };
4export function getPromise(callback) {
5 var tryNativePromise = function () {
6 if (Promise) {
7 return new Promise(function (resolve, reject) {
8 callback(resolve, reject);
9 });
10 }
11 else {
12 console.error('No Promise support or polyfill found. To enable Ionic Native support, please add the es6-promise polyfill before this script, or run with a library like Angular or on a recent browser.');
13 }
14 };
15 if (typeof window !== 'undefined' && window.angular) {
16 var doc = window.document;
17 var injector = window.angular.element(doc.querySelector('[ng-app]') || doc.body).injector();
18 if (injector) {
19 var $q = injector.get('$q');
20 return $q(function (resolve, reject) {
21 callback(resolve, reject);
22 });
23 }
24 console.warn("Angular 1 was detected but $q couldn't be retrieved. This is usually when the app is not bootstrapped on the html or body tag. Falling back to native promises which won't trigger an automatic digest when promises resolve.");
25 }
26 return tryNativePromise();
27}
28export function wrapPromise(pluginObj, methodName, args, opts) {
29 if (opts === void 0) { opts = {}; }
30 var pluginResult, rej;
31 var p = getPromise(function (resolve, reject) {
32 if (opts.destruct) {
33 pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, function () {
34 var args = [];
35 for (var _i = 0; _i < arguments.length; _i++) {
36 args[_i] = arguments[_i];
37 }
38 return resolve(args);
39 }, function () {
40 var args = [];
41 for (var _i = 0; _i < arguments.length; _i++) {
42 args[_i] = arguments[_i];
43 }
44 return reject(args);
45 });
46 }
47 else {
48 pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, resolve, reject);
49 }
50 rej = reject;
51 });
52 // Angular throws an error on unhandled rejection, but in this case we have already printed
53 // a warning that Cordova is undefined or the plugin is uninstalled, so there is no reason
54 // to error
55 if (pluginResult && pluginResult.error) {
56 p.catch(function () { });
57 typeof rej === 'function' && rej(pluginResult.error);
58 }
59 return p;
60}
61function wrapOtherPromise(pluginObj, methodName, args, opts) {
62 if (opts === void 0) { opts = {}; }
63 return getPromise(function (resolve, reject) {
64 var pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts);
65 if (pluginResult) {
66 if (pluginResult.error) {
67 reject(pluginResult.error);
68 }
69 else if (pluginResult.then) {
70 pluginResult.then(resolve).catch(reject);
71 }
72 }
73 else {
74 reject({ error: 'unexpected_error' });
75 }
76 });
77}
78function wrapObservable(pluginObj, methodName, args, opts) {
79 if (opts === void 0) { opts = {}; }
80 return new Observable(function (observer) {
81 var pluginResult;
82 if (opts.destruct) {
83 pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, function () {
84 var args = [];
85 for (var _i = 0; _i < arguments.length; _i++) {
86 args[_i] = arguments[_i];
87 }
88 return observer.next(args);
89 }, function () {
90 var args = [];
91 for (var _i = 0; _i < arguments.length; _i++) {
92 args[_i] = arguments[_i];
93 }
94 return observer.error(args);
95 });
96 }
97 else {
98 pluginResult = callCordovaPlugin(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer));
99 }
100 if (pluginResult && pluginResult.error) {
101 observer.error(pluginResult.error);
102 observer.complete();
103 }
104 return function () {
105 try {
106 if (opts.clearFunction) {
107 if (opts.clearWithArgs) {
108 return callCordovaPlugin(pluginObj, opts.clearFunction, args, opts, observer.next.bind(observer), observer.error.bind(observer));
109 }
110 return callCordovaPlugin(pluginObj, opts.clearFunction, []);
111 }
112 }
113 catch (e) {
114 console.warn('Unable to clear the previous observable watch for', pluginObj.constructor.getPluginName(), methodName);
115 console.warn(e);
116 }
117 };
118 });
119}
120/**
121 * Wrap the event with an observable
122 * @private
123 * @param event event name
124 * @param element The element to attach the event listener to
125 * @returns {Observable}
126 */
127function wrapEventObservable(event, element) {
128 element =
129 typeof window !== 'undefined' && element
130 ? get(window, element)
131 : element || (typeof window !== 'undefined' ? window : {});
132 return fromEvent(element, event);
133}
134export function checkAvailability(plugin, methodName, pluginName) {
135 var pluginRef, pluginInstance, pluginPackage;
136 if (typeof plugin === 'string') {
137 pluginRef = plugin;
138 }
139 else {
140 pluginRef = plugin.constructor.getPluginRef();
141 pluginName = plugin.constructor.getPluginName();
142 pluginPackage = plugin.constructor.getPluginInstallName();
143 }
144 pluginInstance = getPlugin(pluginRef);
145 if (!pluginInstance || (!!methodName && typeof pluginInstance[methodName] === 'undefined')) {
146 if (typeof window === 'undefined' || !window.cordova) {
147 cordovaWarn(pluginName, methodName);
148 return ERR_CORDOVA_NOT_AVAILABLE;
149 }
150 pluginWarn(pluginName, pluginPackage, methodName);
151 return ERR_PLUGIN_NOT_INSTALLED;
152 }
153 return true;
154}
155/**
156 * Checks if _objectInstance exists and has the method/property
157 * @private
158 */
159export function instanceAvailability(pluginObj, methodName) {
160 return pluginObj._objectInstance && (!methodName || typeof pluginObj._objectInstance[methodName] !== 'undefined');
161}
162export function setIndex(args, opts, resolve, reject) {
163 if (opts === void 0) { opts = {}; }
164 // ignore resolve and reject in case sync
165 if (opts.sync) {
166 return args;
167 }
168 // If the plugin method expects myMethod(success, err, options)
169 if (opts.callbackOrder === 'reverse') {
170 // Get those arguments in the order [resolve, reject, ...restOfArgs]
171 args.unshift(reject);
172 args.unshift(resolve);
173 }
174 else if (opts.callbackStyle === 'node') {
175 args.push(function (err, result) {
176 if (err) {
177 reject(err);
178 }
179 else {
180 resolve(result);
181 }
182 });
183 }
184 else if (opts.callbackStyle === 'object' && opts.successName && opts.errorName) {
185 var obj = {};
186 obj[opts.successName] = resolve;
187 obj[opts.errorName] = reject;
188 args.push(obj);
189 }
190 else if (typeof opts.successIndex !== 'undefined' || typeof opts.errorIndex !== 'undefined') {
191 var setSuccessIndex = function () {
192 // If we've specified a success/error index
193 if (opts.successIndex > args.length) {
194 args[opts.successIndex] = resolve;
195 }
196 else {
197 args.splice(opts.successIndex, 0, resolve);
198 }
199 };
200 var setErrorIndex = function () {
201 // We don't want that the reject cb gets spliced into the position of an optional argument that has not been
202 // defined and thus causing non expected behavior.
203 if (opts.errorIndex > args.length) {
204 args[opts.errorIndex] = reject; // insert the reject fn at the correct specific index
205 }
206 else {
207 args.splice(opts.errorIndex, 0, reject); // otherwise just splice it into the array
208 }
209 };
210 if (opts.successIndex > opts.errorIndex) {
211 setErrorIndex();
212 setSuccessIndex();
213 }
214 else {
215 setSuccessIndex();
216 setErrorIndex();
217 }
218 }
219 else {
220 // Otherwise, let's tack them on to the end of the argument list
221 // which is 90% of cases
222 args.push(resolve);
223 args.push(reject);
224 }
225 return args;
226}
227export function callCordovaPlugin(pluginObj, methodName, args, opts, resolve, reject) {
228 if (opts === void 0) { opts = {}; }
229 // Try to figure out where the success/error callbacks need to be bound
230 // to our promise resolve/reject handlers.
231 args = setIndex(args, opts, resolve, reject);
232 var availabilityCheck = checkAvailability(pluginObj, methodName);
233 if (availabilityCheck === true) {
234 var pluginInstance = getPlugin(pluginObj.constructor.getPluginRef());
235 return pluginInstance[methodName].apply(pluginInstance, args);
236 }
237 else {
238 return availabilityCheck;
239 }
240}
241export function callInstance(pluginObj, methodName, args, opts, resolve, reject) {
242 if (opts === void 0) { opts = {}; }
243 args = setIndex(args, opts, resolve, reject);
244 if (instanceAvailability(pluginObj, methodName)) {
245 return pluginObj._objectInstance[methodName].apply(pluginObj._objectInstance, args);
246 }
247}
248export function getPlugin(pluginRef) {
249 if (typeof window !== 'undefined') {
250 return get(window, pluginRef);
251 }
252 return null;
253}
254export function get(element, path) {
255 var paths = path.split('.');
256 var obj = element;
257 for (var i = 0; i < paths.length; i++) {
258 if (!obj) {
259 return null;
260 }
261 obj = obj[paths[i]];
262 }
263 return obj;
264}
265export function pluginWarn(pluginName, plugin, method) {
266 if (method) {
267 console.warn('Native: tried calling ' + pluginName + '.' + method + ', but the ' + pluginName + ' plugin is not installed.');
268 }
269 else {
270 console.warn("Native: tried accessing the " + pluginName + " plugin but it's not installed.");
271 }
272 if (plugin) {
273 console.warn("Install the " + pluginName + " plugin: 'ionic cordova plugin add " + plugin + "'");
274 }
275}
276/**
277 * @private
278 * @param pluginName
279 * @param method
280 */
281export function cordovaWarn(pluginName, method) {
282 if (typeof process === 'undefined') {
283 if (method) {
284 console.warn('Native: tried calling ' +
285 pluginName +
286 '.' +
287 method +
288 ', but Cordova is not available. Make sure to include cordova.js or run in a device/simulator');
289 }
290 else {
291 console.warn('Native: tried accessing the ' +
292 pluginName +
293 ' plugin but Cordova is not available. Make sure to include cordova.js or run in a device/simulator');
294 }
295 }
296}
297/**
298 * @private
299 */
300export var wrap = function (pluginObj, methodName, opts) {
301 if (opts === void 0) { opts = {}; }
302 return function () {
303 var args = [];
304 for (var _i = 0; _i < arguments.length; _i++) {
305 args[_i] = arguments[_i];
306 }
307 if (opts.sync) {
308 // Sync doesn't wrap the plugin with a promise or observable, it returns the result as-is
309 return callCordovaPlugin(pluginObj, methodName, args, opts);
310 }
311 else if (opts.observable) {
312 return wrapObservable(pluginObj, methodName, args, opts);
313 }
314 else if (opts.eventObservable && opts.event) {
315 return wrapEventObservable(opts.event, opts.element);
316 }
317 else if (opts.otherPromise) {
318 return wrapOtherPromise(pluginObj, methodName, args, opts);
319 }
320 else {
321 return wrapPromise(pluginObj, methodName, args, opts);
322 }
323 };
324};
325/**
326 * @private
327 */
328export function wrapInstance(pluginObj, methodName, opts) {
329 if (opts === void 0) { opts = {}; }
330 return function () {
331 var args = [];
332 for (var _i = 0; _i < arguments.length; _i++) {
333 args[_i] = arguments[_i];
334 }
335 if (opts.sync) {
336 return callInstance(pluginObj, methodName, args, opts);
337 }
338 else if (opts.observable) {
339 return new Observable(function (observer) {
340 var pluginResult;
341 if (opts.destruct) {
342 pluginResult = callInstance(pluginObj, methodName, args, opts, function () {
343 var args = [];
344 for (var _i = 0; _i < arguments.length; _i++) {
345 args[_i] = arguments[_i];
346 }
347 return observer.next(args);
348 }, function () {
349 var args = [];
350 for (var _i = 0; _i < arguments.length; _i++) {
351 args[_i] = arguments[_i];
352 }
353 return observer.error(args);
354 });
355 }
356 else {
357 pluginResult = callInstance(pluginObj, methodName, args, opts, observer.next.bind(observer), observer.error.bind(observer));
358 }
359 if (pluginResult && pluginResult.error) {
360 observer.error(pluginResult.error);
361 }
362 return function () {
363 try {
364 if (opts.clearWithArgs) {
365 return callInstance(pluginObj, opts.clearFunction, args, opts, observer.next.bind(observer), observer.error.bind(observer));
366 }
367 return callInstance(pluginObj, opts.clearFunction, []);
368 }
369 catch (e) {
370 console.warn('Unable to clear the previous observable watch for', pluginObj.constructor.getPluginName(), methodName);
371 console.warn(e);
372 }
373 };
374 });
375 }
376 else if (opts.otherPromise) {
377 return getPromise(function (resolve, reject) {
378 var result;
379 if (opts.destruct) {
380 result = callInstance(pluginObj, methodName, args, opts, function () {
381 var args = [];
382 for (var _i = 0; _i < arguments.length; _i++) {
383 args[_i] = arguments[_i];
384 }
385 return resolve(args);
386 }, function () {
387 var args = [];
388 for (var _i = 0; _i < arguments.length; _i++) {
389 args[_i] = arguments[_i];
390 }
391 return reject(args);
392 });
393 }
394 else {
395 result = callInstance(pluginObj, methodName, args, opts, resolve, reject);
396 }
397 if (result && result.then) {
398 result.then(resolve, reject);
399 }
400 else {
401 reject();
402 }
403 });
404 }
405 else {
406 var pluginResult_1, rej_1;
407 var p = getPromise(function (resolve, reject) {
408 if (opts.destruct) {
409 pluginResult_1 = callInstance(pluginObj, methodName, args, opts, function () {
410 var args = [];
411 for (var _i = 0; _i < arguments.length; _i++) {
412 args[_i] = arguments[_i];
413 }
414 return resolve(args);
415 }, function () {
416 var args = [];
417 for (var _i = 0; _i < arguments.length; _i++) {
418 args[_i] = arguments[_i];
419 }
420 return reject(args);
421 });
422 }
423 else {
424 pluginResult_1 = callInstance(pluginObj, methodName, args, opts, resolve, reject);
425 }
426 rej_1 = reject;
427 });
428 // Angular throws an error on unhandled rejection, but in this case we have already printed
429 // a warning that Cordova is undefined or the plugin is uninstalled, so there is no reason
430 // to error
431 if (pluginResult_1 && pluginResult_1.error) {
432 p.catch(function () { });
433 typeof rej_1 === 'function' && rej_1(pluginResult_1.error);
434 }
435 return p;
436 }
437 };
438}
439//# sourceMappingURL=common.js.map
\No newline at end of file