No Description

cordova.js 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. // Platform: browser
  2. // d07d9d0989196f1b90fe962ca68f5ceb355c69ec
  3. /*
  4. Licensed to the Apache Software Foundation (ASF) under one
  5. or more contributor license agreements. See the NOTICE file
  6. distributed with this work for additional information
  7. regarding copyright ownership. The ASF licenses this file
  8. to you under the Apache License, Version 2.0 (the
  9. "License"); you may not use this file except in compliance
  10. with the License. You may obtain a copy of the License at
  11. http://www.apache.org/licenses/LICENSE-2.0
  12. Unless required by applicable law or agreed to in writing,
  13. software distributed under the License is distributed on an
  14. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. KIND, either express or implied. See the License for the
  16. specific language governing permissions and limitations
  17. under the License.
  18. */
  19. ;(function() {
  20. var PLATFORM_VERSION_BUILD_LABEL = '6.0.0';
  21. // file: src/scripts/require.js
  22. var require;
  23. var define;
  24. (function () {
  25. var modules = {};
  26. // Stack of moduleIds currently being built.
  27. var requireStack = [];
  28. // Map of module ID -> index into requireStack of modules currently being built.
  29. var inProgressModules = {};
  30. var SEPARATOR = '.';
  31. function build (module) {
  32. var factory = module.factory;
  33. var localRequire = function (id) {
  34. var resultantId = id;
  35. // Its a relative path, so lop off the last portion and add the id (minus "./")
  36. if (id.charAt(0) === '.') {
  37. resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2);
  38. }
  39. return require(resultantId);
  40. };
  41. module.exports = {};
  42. delete module.factory;
  43. factory(localRequire, module.exports, module);
  44. return module.exports;
  45. }
  46. require = function (id) {
  47. if (!modules[id]) {
  48. throw 'module ' + id + ' not found';
  49. } else if (id in inProgressModules) {
  50. var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;
  51. throw 'Cycle in require graph: ' + cycle;
  52. }
  53. if (modules[id].factory) {
  54. try {
  55. inProgressModules[id] = requireStack.length;
  56. requireStack.push(id);
  57. return build(modules[id]);
  58. } finally {
  59. delete inProgressModules[id];
  60. requireStack.pop();
  61. }
  62. }
  63. return modules[id].exports;
  64. };
  65. define = function (id, factory) {
  66. if (modules[id]) {
  67. throw 'module ' + id + ' already defined';
  68. }
  69. modules[id] = {
  70. id: id,
  71. factory: factory
  72. };
  73. };
  74. define.remove = function (id) {
  75. delete modules[id];
  76. };
  77. define.moduleMap = modules;
  78. })();
  79. // Export for use in node
  80. if (typeof module === 'object' && typeof require === 'function') {
  81. module.exports.require = require;
  82. module.exports.define = define;
  83. }
  84. // file: src/cordova.js
  85. define("cordova", function(require, exports, module) {
  86. // Workaround for Windows 10 in hosted environment case
  87. // http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object
  88. if (window.cordova && !(window.cordova instanceof HTMLElement)) { // eslint-disable-line no-undef
  89. throw new Error('cordova already defined');
  90. }
  91. var channel = require('cordova/channel');
  92. var platform = require('cordova/platform');
  93. /**
  94. * Intercept calls to addEventListener + removeEventListener and handle deviceready,
  95. * resume, and pause events.
  96. */
  97. var m_document_addEventListener = document.addEventListener;
  98. var m_document_removeEventListener = document.removeEventListener;
  99. var m_window_addEventListener = window.addEventListener;
  100. var m_window_removeEventListener = window.removeEventListener;
  101. /**
  102. * Houses custom event handlers to intercept on document + window event listeners.
  103. */
  104. var documentEventHandlers = {};
  105. var windowEventHandlers = {};
  106. document.addEventListener = function (evt, handler, capture) {
  107. var e = evt.toLowerCase();
  108. if (typeof documentEventHandlers[e] !== 'undefined') {
  109. documentEventHandlers[e].subscribe(handler);
  110. } else {
  111. m_document_addEventListener.call(document, evt, handler, capture);
  112. }
  113. };
  114. window.addEventListener = function (evt, handler, capture) {
  115. var e = evt.toLowerCase();
  116. if (typeof windowEventHandlers[e] !== 'undefined') {
  117. windowEventHandlers[e].subscribe(handler);
  118. } else {
  119. m_window_addEventListener.call(window, evt, handler, capture);
  120. }
  121. };
  122. document.removeEventListener = function (evt, handler, capture) {
  123. var e = evt.toLowerCase();
  124. // If unsubscribing from an event that is handled by a plugin
  125. if (typeof documentEventHandlers[e] !== 'undefined') {
  126. documentEventHandlers[e].unsubscribe(handler);
  127. } else {
  128. m_document_removeEventListener.call(document, evt, handler, capture);
  129. }
  130. };
  131. window.removeEventListener = function (evt, handler, capture) {
  132. var e = evt.toLowerCase();
  133. // If unsubscribing from an event that is handled by a plugin
  134. if (typeof windowEventHandlers[e] !== 'undefined') {
  135. windowEventHandlers[e].unsubscribe(handler);
  136. } else {
  137. m_window_removeEventListener.call(window, evt, handler, capture);
  138. }
  139. };
  140. function createEvent (type, data) {
  141. var event = document.createEvent('Events');
  142. event.initEvent(type, false, false);
  143. if (data) {
  144. for (var i in data) {
  145. if (data.hasOwnProperty(i)) {
  146. event[i] = data[i];
  147. }
  148. }
  149. }
  150. return event;
  151. }
  152. /* eslint-disable no-undef */
  153. var cordova = {
  154. define: define,
  155. require: require,
  156. version: PLATFORM_VERSION_BUILD_LABEL,
  157. platformVersion: PLATFORM_VERSION_BUILD_LABEL,
  158. platformId: platform.id,
  159. /* eslint-enable no-undef */
  160. /**
  161. * Methods to add/remove your own addEventListener hijacking on document + window.
  162. */
  163. addWindowEventHandler: function (event) {
  164. return (windowEventHandlers[event] = channel.create(event));
  165. },
  166. addStickyDocumentEventHandler: function (event) {
  167. return (documentEventHandlers[event] = channel.createSticky(event));
  168. },
  169. addDocumentEventHandler: function (event) {
  170. return (documentEventHandlers[event] = channel.create(event));
  171. },
  172. removeWindowEventHandler: function (event) {
  173. delete windowEventHandlers[event];
  174. },
  175. removeDocumentEventHandler: function (event) {
  176. delete documentEventHandlers[event];
  177. },
  178. /**
  179. * Retrieve original event handlers that were replaced by Cordova
  180. *
  181. * @return object
  182. */
  183. getOriginalHandlers: function () {
  184. return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},
  185. 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};
  186. },
  187. /**
  188. * Method to fire event from native code
  189. * bNoDetach is required for events which cause an exception which needs to be caught in native code
  190. */
  191. fireDocumentEvent: function (type, data, bNoDetach) {
  192. var evt = createEvent(type, data);
  193. if (typeof documentEventHandlers[type] !== 'undefined') {
  194. if (bNoDetach) {
  195. documentEventHandlers[type].fire(evt);
  196. } else {
  197. setTimeout(function () {
  198. // Fire deviceready on listeners that were registered before cordova.js was loaded.
  199. if (type === 'deviceready') {
  200. document.dispatchEvent(evt);
  201. }
  202. documentEventHandlers[type].fire(evt);
  203. }, 0);
  204. }
  205. } else {
  206. document.dispatchEvent(evt);
  207. }
  208. },
  209. fireWindowEvent: function (type, data) {
  210. var evt = createEvent(type, data);
  211. if (typeof windowEventHandlers[type] !== 'undefined') {
  212. setTimeout(function () {
  213. windowEventHandlers[type].fire(evt);
  214. }, 0);
  215. } else {
  216. window.dispatchEvent(evt);
  217. }
  218. },
  219. /**
  220. * Plugin callback mechanism.
  221. */
  222. // Randomize the starting callbackId to avoid collisions after refreshing or navigating.
  223. // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.
  224. callbackId: Math.floor(Math.random() * 2000000000),
  225. callbacks: {},
  226. callbackStatus: {
  227. NO_RESULT: 0,
  228. OK: 1,
  229. CLASS_NOT_FOUND_EXCEPTION: 2,
  230. ILLEGAL_ACCESS_EXCEPTION: 3,
  231. INSTANTIATION_EXCEPTION: 4,
  232. MALFORMED_URL_EXCEPTION: 5,
  233. IO_EXCEPTION: 6,
  234. INVALID_ACTION: 7,
  235. JSON_EXCEPTION: 8,
  236. ERROR: 9
  237. },
  238. /**
  239. * Called by native code when returning successful result from an action.
  240. */
  241. callbackSuccess: function (callbackId, args) {
  242. cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
  243. },
  244. /**
  245. * Called by native code when returning error result from an action.
  246. */
  247. callbackError: function (callbackId, args) {
  248. // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
  249. // Derive success from status.
  250. cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
  251. },
  252. /**
  253. * Called by native code when returning the result from an action.
  254. */
  255. callbackFromNative: function (callbackId, isSuccess, status, args, keepCallback) {
  256. try {
  257. var callback = cordova.callbacks[callbackId];
  258. if (callback) {
  259. if (isSuccess && status === cordova.callbackStatus.OK) {
  260. callback.success && callback.success.apply(null, args);
  261. } else if (!isSuccess) {
  262. callback.fail && callback.fail.apply(null, args);
  263. }
  264. /*
  265. else
  266. Note, this case is intentionally not caught.
  267. this can happen if isSuccess is true, but callbackStatus is NO_RESULT
  268. which is used to remove a callback from the list without calling the callbacks
  269. typically keepCallback is false in this case
  270. */
  271. // Clear callback if not expecting any more results
  272. if (!keepCallback) {
  273. delete cordova.callbacks[callbackId];
  274. }
  275. }
  276. } catch (err) {
  277. var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;
  278. console && console.log && console.log(msg);
  279. console && console.log && err.stack && console.log(err.stack);
  280. cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });
  281. throw err;
  282. }
  283. },
  284. addConstructor: function (func) {
  285. channel.onCordovaReady.subscribe(function () {
  286. try {
  287. func();
  288. } catch (e) {
  289. console.log('Failed to run constructor: ' + e);
  290. }
  291. });
  292. }
  293. };
  294. module.exports = cordova;
  295. });
  296. // file: src/common/argscheck.js
  297. define("cordova/argscheck", function(require, exports, module) {
  298. var utils = require('cordova/utils');
  299. var moduleExports = module.exports;
  300. var typeMap = {
  301. 'A': 'Array',
  302. 'D': 'Date',
  303. 'N': 'Number',
  304. 'S': 'String',
  305. 'F': 'Function',
  306. 'O': 'Object'
  307. };
  308. function extractParamName (callee, argIndex) {
  309. return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];
  310. }
  311. function checkArgs (spec, functionName, args, opt_callee) {
  312. if (!moduleExports.enableChecks) {
  313. return;
  314. }
  315. var errMsg = null;
  316. var typeName;
  317. for (var i = 0; i < spec.length; ++i) {
  318. var c = spec.charAt(i);
  319. var cUpper = c.toUpperCase();
  320. var arg = args[i];
  321. // Asterix means allow anything.
  322. if (c === '*') {
  323. continue;
  324. }
  325. typeName = utils.typeName(arg);
  326. if ((arg === null || arg === undefined) && c === cUpper) {
  327. continue;
  328. }
  329. if (typeName !== typeMap[cUpper]) {
  330. errMsg = 'Expected ' + typeMap[cUpper];
  331. break;
  332. }
  333. }
  334. if (errMsg) {
  335. errMsg += ', but got ' + typeName + '.';
  336. errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;
  337. // Don't log when running unit tests.
  338. if (typeof jasmine === 'undefined') {
  339. console.error(errMsg);
  340. }
  341. throw TypeError(errMsg);
  342. }
  343. }
  344. function getValue (value, defaultValue) {
  345. return value === undefined ? defaultValue : value;
  346. }
  347. moduleExports.checkArgs = checkArgs;
  348. moduleExports.getValue = getValue;
  349. moduleExports.enableChecks = true;
  350. });
  351. // file: src/common/base64.js
  352. define("cordova/base64", function(require, exports, module) {
  353. var base64 = exports;
  354. base64.fromArrayBuffer = function (arrayBuffer) {
  355. var array = new Uint8Array(arrayBuffer);
  356. return uint8ToBase64(array);
  357. };
  358. base64.toArrayBuffer = function (str) {
  359. var decodedStr = typeof atob !== 'undefined' ? atob(str) : Buffer.from(str, 'base64').toString('binary'); // eslint-disable-line no-undef
  360. var arrayBuffer = new ArrayBuffer(decodedStr.length);
  361. var array = new Uint8Array(arrayBuffer);
  362. for (var i = 0, len = decodedStr.length; i < len; i++) {
  363. array[i] = decodedStr.charCodeAt(i);
  364. }
  365. return arrayBuffer;
  366. };
  367. // ------------------------------------------------------------------------------
  368. /* This code is based on the performance tests at http://jsperf.com/b64tests
  369. * This 12-bit-at-a-time algorithm was the best performing version on all
  370. * platforms tested.
  371. */
  372. var b64_6bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  373. var b64_12bit;
  374. var b64_12bitTable = function () {
  375. b64_12bit = [];
  376. for (var i = 0; i < 64; i++) {
  377. for (var j = 0; j < 64; j++) {
  378. b64_12bit[i * 64 + j] = b64_6bit[i] + b64_6bit[j];
  379. }
  380. }
  381. b64_12bitTable = function () { return b64_12bit; };
  382. return b64_12bit;
  383. };
  384. function uint8ToBase64 (rawData) {
  385. var numBytes = rawData.byteLength;
  386. var output = '';
  387. var segment;
  388. var table = b64_12bitTable();
  389. for (var i = 0; i < numBytes - 2; i += 3) {
  390. segment = (rawData[i] << 16) + (rawData[i + 1] << 8) + rawData[i + 2];
  391. output += table[segment >> 12];
  392. output += table[segment & 0xfff];
  393. }
  394. if (numBytes - i === 2) {
  395. segment = (rawData[i] << 16) + (rawData[i + 1] << 8);
  396. output += table[segment >> 12];
  397. output += b64_6bit[(segment & 0xfff) >> 6];
  398. output += '=';
  399. } else if (numBytes - i === 1) {
  400. segment = (rawData[i] << 16);
  401. output += table[segment >> 12];
  402. output += '==';
  403. }
  404. return output;
  405. }
  406. });
  407. // file: src/common/builder.js
  408. define("cordova/builder", function(require, exports, module) {
  409. var utils = require('cordova/utils');
  410. function each (objects, func, context) {
  411. for (var prop in objects) {
  412. if (objects.hasOwnProperty(prop)) {
  413. func.apply(context, [objects[prop], prop]);
  414. }
  415. }
  416. }
  417. function clobber (obj, key, value) {
  418. exports.replaceHookForTesting(obj, key);
  419. var needsProperty = false;
  420. try {
  421. obj[key] = value;
  422. } catch (e) {
  423. needsProperty = true;
  424. }
  425. // Getters can only be overridden by getters.
  426. if (needsProperty || obj[key] !== value) {
  427. utils.defineGetter(obj, key, function () {
  428. return value;
  429. });
  430. }
  431. }
  432. function assignOrWrapInDeprecateGetter (obj, key, value, message) {
  433. if (message) {
  434. utils.defineGetter(obj, key, function () {
  435. console.log(message);
  436. delete obj[key];
  437. clobber(obj, key, value);
  438. return value;
  439. });
  440. } else {
  441. clobber(obj, key, value);
  442. }
  443. }
  444. function include (parent, objects, clobber, merge) {
  445. each(objects, function (obj, key) {
  446. try {
  447. var result = obj.path ? require(obj.path) : {};
  448. if (clobber) {
  449. // Clobber if it doesn't exist.
  450. if (typeof parent[key] === 'undefined') {
  451. assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
  452. } else if (typeof obj.path !== 'undefined') {
  453. // If merging, merge properties onto parent, otherwise, clobber.
  454. if (merge) {
  455. recursiveMerge(parent[key], result);
  456. } else {
  457. assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
  458. }
  459. }
  460. result = parent[key];
  461. } else {
  462. // Overwrite if not currently defined.
  463. if (typeof parent[key] === 'undefined') {
  464. assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
  465. } else {
  466. // Set result to what already exists, so we can build children into it if they exist.
  467. result = parent[key];
  468. }
  469. }
  470. if (obj.children) {
  471. include(result, obj.children, clobber, merge);
  472. }
  473. } catch (e) {
  474. utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');
  475. }
  476. });
  477. }
  478. /**
  479. * Merge properties from one object onto another recursively. Properties from
  480. * the src object will overwrite existing target property.
  481. *
  482. * @param target Object to merge properties into.
  483. * @param src Object to merge properties from.
  484. */
  485. function recursiveMerge (target, src) {
  486. for (var prop in src) {
  487. if (src.hasOwnProperty(prop)) {
  488. if (target.prototype && target.prototype.constructor === target) {
  489. // If the target object is a constructor override off prototype.
  490. clobber(target.prototype, prop, src[prop]);
  491. } else {
  492. if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
  493. recursiveMerge(target[prop], src[prop]);
  494. } else {
  495. clobber(target, prop, src[prop]);
  496. }
  497. }
  498. }
  499. }
  500. }
  501. exports.buildIntoButDoNotClobber = function (objects, target) {
  502. include(target, objects, false, false);
  503. };
  504. exports.buildIntoAndClobber = function (objects, target) {
  505. include(target, objects, true, false);
  506. };
  507. exports.buildIntoAndMerge = function (objects, target) {
  508. include(target, objects, true, true);
  509. };
  510. exports.recursiveMerge = recursiveMerge;
  511. exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
  512. exports.replaceHookForTesting = function () {};
  513. });
  514. // file: src/common/channel.js
  515. define("cordova/channel", function(require, exports, module) {
  516. var utils = require('cordova/utils');
  517. var nextGuid = 1;
  518. /**
  519. * Custom pub-sub "channel" that can have functions subscribed to it
  520. * This object is used to define and control firing of events for
  521. * cordova initialization, as well as for custom events thereafter.
  522. *
  523. * The order of events during page load and Cordova startup is as follows:
  524. *
  525. * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.
  526. * onNativeReady* Internal event that indicates the Cordova native side is ready.
  527. * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.
  528. * onDeviceReady* User event fired to indicate that Cordova is ready
  529. * onResume User event fired to indicate a start/resume lifecycle event
  530. * onPause User event fired to indicate a pause lifecycle event
  531. *
  532. * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.
  533. * All listeners that subscribe after the event is fired will be executed right away.
  534. *
  535. * The only Cordova events that user code should register for are:
  536. * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript
  537. * pause App has moved to background
  538. * resume App has returned to foreground
  539. *
  540. * Listeners can be registered as:
  541. * document.addEventListener("deviceready", myDeviceReadyListener, false);
  542. * document.addEventListener("resume", myResumeListener, false);
  543. * document.addEventListener("pause", myPauseListener, false);
  544. *
  545. * The DOM lifecycle events should be used for saving and restoring state
  546. * window.onload
  547. * window.onunload
  548. *
  549. */
  550. /**
  551. * Channel
  552. * @constructor
  553. * @param type String the channel name
  554. */
  555. var Channel = function (type, sticky) {
  556. this.type = type;
  557. // Map of guid -> function.
  558. this.handlers = {};
  559. // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
  560. this.state = sticky ? 1 : 0;
  561. // Used in sticky mode to remember args passed to fire().
  562. this.fireArgs = null;
  563. // Used by onHasSubscribersChange to know if there are any listeners.
  564. this.numHandlers = 0;
  565. // Function that is called when the first listener is subscribed, or when
  566. // the last listener is unsubscribed.
  567. this.onHasSubscribersChange = null;
  568. };
  569. var channel = {
  570. /**
  571. * Calls the provided function only after all of the channels specified
  572. * have been fired. All channels must be sticky channels.
  573. */
  574. join: function (h, c) {
  575. var len = c.length;
  576. var i = len;
  577. var f = function () {
  578. if (!(--i)) h();
  579. };
  580. for (var j = 0; j < len; j++) {
  581. if (c[j].state === 0) {
  582. throw Error('Can only use join with sticky channels.');
  583. }
  584. c[j].subscribe(f);
  585. }
  586. if (!len) h();
  587. },
  588. /* eslint-disable no-return-assign */
  589. create: function (type) {
  590. return channel[type] = new Channel(type, false);
  591. },
  592. createSticky: function (type) {
  593. return channel[type] = new Channel(type, true);
  594. },
  595. /* eslint-enable no-return-assign */
  596. /**
  597. * cordova Channels that must fire before "deviceready" is fired.
  598. */
  599. deviceReadyChannelsArray: [],
  600. deviceReadyChannelsMap: {},
  601. /**
  602. * Indicate that a feature needs to be initialized before it is ready to be used.
  603. * This holds up Cordova's "deviceready" event until the feature has been initialized
  604. * and Cordova.initComplete(feature) is called.
  605. *
  606. * @param feature {String} The unique feature name
  607. */
  608. waitForInitialization: function (feature) {
  609. if (feature) {
  610. var c = channel[feature] || this.createSticky(feature);
  611. this.deviceReadyChannelsMap[feature] = c;
  612. this.deviceReadyChannelsArray.push(c);
  613. }
  614. },
  615. /**
  616. * Indicate that initialization code has completed and the feature is ready to be used.
  617. *
  618. * @param feature {String} The unique feature name
  619. */
  620. initializationComplete: function (feature) {
  621. var c = this.deviceReadyChannelsMap[feature];
  622. if (c) {
  623. c.fire();
  624. }
  625. }
  626. };
  627. function checkSubscriptionArgument (argument) {
  628. if (typeof argument !== 'function' && typeof argument.handleEvent !== 'function') {
  629. throw new Error(
  630. 'Must provide a function or an EventListener object ' +
  631. 'implementing the handleEvent interface.'
  632. );
  633. }
  634. }
  635. /**
  636. * Subscribes the given function to the channel. Any time that
  637. * Channel.fire is called so too will the function.
  638. * Optionally specify an execution context for the function
  639. * and a guid that can be used to stop subscribing to the channel.
  640. * Returns the guid.
  641. */
  642. Channel.prototype.subscribe = function (eventListenerOrFunction, eventListener) {
  643. checkSubscriptionArgument(eventListenerOrFunction);
  644. var handleEvent, guid;
  645. if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {
  646. // Received an EventListener object implementing the handleEvent interface
  647. handleEvent = eventListenerOrFunction.handleEvent;
  648. eventListener = eventListenerOrFunction;
  649. } else {
  650. // Received a function to handle event
  651. handleEvent = eventListenerOrFunction;
  652. }
  653. if (this.state === 2) {
  654. handleEvent.apply(eventListener || this, this.fireArgs);
  655. return;
  656. }
  657. guid = eventListenerOrFunction.observer_guid;
  658. if (typeof eventListener === 'object') {
  659. handleEvent = utils.close(eventListener, handleEvent);
  660. }
  661. if (!guid) {
  662. // First time any channel has seen this subscriber
  663. guid = '' + nextGuid++;
  664. }
  665. handleEvent.observer_guid = guid;
  666. eventListenerOrFunction.observer_guid = guid;
  667. // Don't add the same handler more than once.
  668. if (!this.handlers[guid]) {
  669. this.handlers[guid] = handleEvent;
  670. this.numHandlers++;
  671. if (this.numHandlers === 1) {
  672. this.onHasSubscribersChange && this.onHasSubscribersChange();
  673. }
  674. }
  675. };
  676. /**
  677. * Unsubscribes the function with the given guid from the channel.
  678. */
  679. Channel.prototype.unsubscribe = function (eventListenerOrFunction) {
  680. checkSubscriptionArgument(eventListenerOrFunction);
  681. var handleEvent, guid, handler;
  682. if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {
  683. // Received an EventListener object implementing the handleEvent interface
  684. handleEvent = eventListenerOrFunction.handleEvent;
  685. } else {
  686. // Received a function to handle event
  687. handleEvent = eventListenerOrFunction;
  688. }
  689. guid = handleEvent.observer_guid;
  690. handler = this.handlers[guid];
  691. if (handler) {
  692. delete this.handlers[guid];
  693. this.numHandlers--;
  694. if (this.numHandlers === 0) {
  695. this.onHasSubscribersChange && this.onHasSubscribersChange();
  696. }
  697. }
  698. };
  699. /**
  700. * Calls all functions subscribed to this channel.
  701. */
  702. Channel.prototype.fire = function (e) {
  703. var fail = false; // eslint-disable-line no-unused-vars
  704. var fireArgs = Array.prototype.slice.call(arguments);
  705. // Apply stickiness.
  706. if (this.state === 1) {
  707. this.state = 2;
  708. this.fireArgs = fireArgs;
  709. }
  710. if (this.numHandlers) {
  711. // Copy the values first so that it is safe to modify it from within
  712. // callbacks.
  713. var toCall = [];
  714. for (var item in this.handlers) {
  715. toCall.push(this.handlers[item]);
  716. }
  717. for (var i = 0; i < toCall.length; ++i) {
  718. toCall[i].apply(this, fireArgs);
  719. }
  720. if (this.state === 2 && this.numHandlers) {
  721. this.numHandlers = 0;
  722. this.handlers = {};
  723. this.onHasSubscribersChange && this.onHasSubscribersChange();
  724. }
  725. }
  726. };
  727. // defining them here so they are ready super fast!
  728. // DOM event that is received when the web page is loaded and parsed.
  729. channel.createSticky('onDOMContentLoaded');
  730. // Event to indicate the Cordova native side is ready.
  731. channel.createSticky('onNativeReady');
  732. // Event to indicate that all Cordova JavaScript objects have been created
  733. // and it's time to run plugin constructors.
  734. channel.createSticky('onCordovaReady');
  735. // Event to indicate that all automatically loaded JS plugins are loaded and ready.
  736. // FIXME remove this
  737. channel.createSticky('onPluginsReady');
  738. // Event to indicate that Cordova is ready
  739. channel.createSticky('onDeviceReady');
  740. // Event to indicate a resume lifecycle event
  741. channel.create('onResume');
  742. // Event to indicate a pause lifecycle event
  743. channel.create('onPause');
  744. // Channels that must fire before "deviceready" is fired.
  745. channel.waitForInitialization('onCordovaReady');
  746. channel.waitForInitialization('onDOMContentLoaded');
  747. module.exports = channel;
  748. });
  749. // file: /Users/erisu/git/apache/cordova/cordova-browser/cordova-js-src/confighelper.js
  750. define("cordova/confighelper", function(require, exports, module) {
  751. var config;
  752. function Config(xhr) {
  753. function loadPreferences(xhr) {
  754. var parser = new DOMParser();
  755. var doc = parser.parseFromString(xhr.responseText, "application/xml");
  756. var preferences = doc.getElementsByTagName("preference");
  757. return Array.prototype.slice.call(preferences);
  758. }
  759. this.xhr = xhr;
  760. this.preferences = loadPreferences(this.xhr);
  761. }
  762. function readConfig(success, error) {
  763. var xhr;
  764. if(typeof config != 'undefined') {
  765. success(config);
  766. }
  767. function fail(msg) {
  768. console.error(msg);
  769. if(error) {
  770. error(msg);
  771. }
  772. }
  773. var xhrStatusChangeHandler = function() {
  774. if (xhr.readyState == 4) {
  775. if (xhr.status == 200 || xhr.status == 304 || xhr.status === 0 /* file:// */) {
  776. config = new Config(xhr);
  777. success(config);
  778. }
  779. else {
  780. fail('[Browser][cordova.js][xhrStatusChangeHandler] Could not XHR config.xml: ' + xhr.statusText);
  781. }
  782. }
  783. };
  784. xhr = new XMLHttpRequest();
  785. xhr.addEventListener("load", xhrStatusChangeHandler);
  786. try {
  787. xhr.open("get", "config.xml", true);
  788. xhr.send();
  789. } catch(e) {
  790. fail('[Browser][cordova.js][readConfig] Could not XHR config.xml: ' + JSON.stringify(e));
  791. }
  792. }
  793. /**
  794. * Reads a preference value from config.xml.
  795. * Returns preference value or undefined if it does not exist.
  796. * @param {String} preferenceName Preference name to read */
  797. Config.prototype.getPreferenceValue = function getPreferenceValue(preferenceName) {
  798. var preferenceItem = this.preferences && this.preferences.filter(function(item) {
  799. return item.attributes.name && item.attributes.name.value === preferenceName;
  800. });
  801. if(preferenceItem && preferenceItem[0] && preferenceItem[0].attributes && preferenceItem[0].attributes.value) {
  802. return preferenceItem[0].attributes.value.value;
  803. }
  804. };
  805. exports.readConfig = readConfig;
  806. });
  807. // file: /Users/erisu/git/apache/cordova/cordova-browser/cordova-js-src/exec.js
  808. define("cordova/exec", function(require, exports, module) {
  809. /*jslint sloppy:true, plusplus:true*/
  810. /*global require, module, console */
  811. var cordova = require('cordova');
  812. var execProxy = require('cordova/exec/proxy');
  813. /**
  814. * Execute a cordova command. It is up to the native side whether this action
  815. * is synchronous or asynchronous. The native side can return:
  816. * Synchronous: PluginResult object as a JSON string
  817. * Asynchronous: Empty string ""
  818. * If async, the native side will cordova.callbackSuccess or cordova.callbackError,
  819. * depending upon the result of the action.
  820. *
  821. * @param {Function} success The success callback
  822. * @param {Function} fail The fail callback
  823. * @param {String} service The name of the service to use
  824. * @param {String} action Action to be run in cordova
  825. * @param {String[]} [args] Zero or more arguments to pass to the method
  826. */
  827. module.exports = function (success, fail, service, action, args) {
  828. var proxy = execProxy.get(service, action);
  829. args = args || [];
  830. if (proxy) {
  831. var callbackId = service + cordova.callbackId++;
  832. if (typeof success === "function" || typeof fail === "function") {
  833. cordova.callbacks[callbackId] = {success: success, fail: fail};
  834. }
  835. try {
  836. // callbackOptions param represents additional optional parameters command could pass back, like keepCallback or
  837. // custom callbackId, for example {callbackId: id, keepCallback: true, status: cordova.callbackStatus.JSON_EXCEPTION }
  838. var onSuccess = function (result, callbackOptions) {
  839. callbackOptions = callbackOptions || {};
  840. var callbackStatus;
  841. // covering both undefined and null.
  842. // strict null comparison was causing callbackStatus to be undefined
  843. // and then no callback was called because of the check in cordova.callbackFromNative
  844. // see CB-8996 Mobilespec app hang on windows
  845. if (callbackOptions.status !== undefined && callbackOptions.status !== null) {
  846. callbackStatus = callbackOptions.status;
  847. }
  848. else {
  849. callbackStatus = cordova.callbackStatus.OK;
  850. }
  851. cordova.callbackSuccess(callbackOptions.callbackId || callbackId,
  852. {
  853. status: callbackStatus,
  854. message: result,
  855. keepCallback: callbackOptions.keepCallback || false
  856. });
  857. };
  858. var onError = function (err, callbackOptions) {
  859. callbackOptions = callbackOptions || {};
  860. var callbackStatus;
  861. // covering both undefined and null.
  862. // strict null comparison was causing callbackStatus to be undefined
  863. // and then no callback was called because of the check in cordova.callbackFromNative
  864. // note: status can be 0
  865. if (callbackOptions.status !== undefined && callbackOptions.status !== null) {
  866. callbackStatus = callbackOptions.status;
  867. }
  868. else {
  869. callbackStatus = cordova.callbackStatus.OK;
  870. }
  871. cordova.callbackError(callbackOptions.callbackId || callbackId,
  872. {
  873. status: callbackStatus,
  874. message: err,
  875. keepCallback: callbackOptions.keepCallback || false
  876. });
  877. };
  878. proxy(onSuccess, onError, args);
  879. } catch (e) {
  880. console.log("Exception calling native with command :: " + service + " :: " + action + " ::exception=" + e);
  881. }
  882. } else {
  883. console.log("Error: exec proxy not found for :: " + service + " :: " + action);
  884. if(typeof fail === "function" ) {
  885. fail("Missing Command Error");
  886. }
  887. }
  888. };
  889. });
  890. // file: src/common/exec/proxy.js
  891. define("cordova/exec/proxy", function(require, exports, module) {
  892. // internal map of proxy function
  893. var CommandProxyMap = {};
  894. module.exports = {
  895. // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);
  896. add: function (id, proxyObj) {
  897. console.log('adding proxy for ' + id);
  898. CommandProxyMap[id] = proxyObj;
  899. return proxyObj;
  900. },
  901. // cordova.commandProxy.remove("Accelerometer");
  902. remove: function (id) {
  903. var proxy = CommandProxyMap[id];
  904. delete CommandProxyMap[id];
  905. CommandProxyMap[id] = null;
  906. return proxy;
  907. },
  908. get: function (service, action) {
  909. return (CommandProxyMap[service] ? CommandProxyMap[service][action] : null);
  910. }
  911. };
  912. });
  913. // file: src/common/init.js
  914. define("cordova/init", function(require, exports, module) {
  915. var channel = require('cordova/channel');
  916. var cordova = require('cordova');
  917. var modulemapper = require('cordova/modulemapper');
  918. var platform = require('cordova/platform');
  919. var pluginloader = require('cordova/pluginloader');
  920. var utils = require('cordova/utils');
  921. var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];
  922. function logUnfiredChannels (arr) {
  923. for (var i = 0; i < arr.length; ++i) {
  924. if (arr[i].state !== 2) {
  925. console.log('Channel not fired: ' + arr[i].type);
  926. }
  927. }
  928. }
  929. window.setTimeout(function () {
  930. if (channel.onDeviceReady.state !== 2) {
  931. console.log('deviceready has not fired after 5 seconds.');
  932. logUnfiredChannels(platformInitChannelsArray);
  933. logUnfiredChannels(channel.deviceReadyChannelsArray);
  934. }
  935. }, 5000);
  936. // Replace navigator before any modules are required(), to ensure it happens as soon as possible.
  937. // We replace it so that properties that can't be clobbered can instead be overridden.
  938. function replaceNavigator (origNavigator) {
  939. var CordovaNavigator = function () {};
  940. CordovaNavigator.prototype = origNavigator;
  941. var newNavigator = new CordovaNavigator();
  942. // This work-around really only applies to new APIs that are newer than Function.bind.
  943. // Without it, APIs such as getGamepads() break.
  944. if (CordovaNavigator.bind) {
  945. for (var key in origNavigator) {
  946. if (typeof origNavigator[key] === 'function') {
  947. newNavigator[key] = origNavigator[key].bind(origNavigator);
  948. } else {
  949. (function (k) {
  950. utils.defineGetterSetter(newNavigator, key, function () {
  951. return origNavigator[k];
  952. });
  953. })(key);
  954. }
  955. }
  956. }
  957. return newNavigator;
  958. }
  959. if (window.navigator) {
  960. window.navigator = replaceNavigator(window.navigator);
  961. }
  962. if (!window.console) {
  963. window.console = {
  964. log: function () {}
  965. };
  966. }
  967. if (!window.console.warn) {
  968. window.console.warn = function (msg) {
  969. this.log('warn: ' + msg);
  970. };
  971. }
  972. // Register pause, resume and deviceready channels as events on document.
  973. channel.onPause = cordova.addDocumentEventHandler('pause');
  974. channel.onResume = cordova.addDocumentEventHandler('resume');
  975. channel.onActivated = cordova.addDocumentEventHandler('activated');
  976. channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');
  977. // Listen for DOMContentLoaded and notify our channel subscribers.
  978. if (document.readyState === 'complete' || document.readyState === 'interactive') {
  979. channel.onDOMContentLoaded.fire();
  980. } else {
  981. document.addEventListener('DOMContentLoaded', function () {
  982. channel.onDOMContentLoaded.fire();
  983. }, false);
  984. }
  985. // _nativeReady is global variable that the native side can set
  986. // to signify that the native code is ready. It is a global since
  987. // it may be called before any cordova JS is ready.
  988. if (window._nativeReady) {
  989. channel.onNativeReady.fire();
  990. }
  991. modulemapper.clobbers('cordova', 'cordova');
  992. modulemapper.clobbers('cordova/exec', 'cordova.exec');
  993. modulemapper.clobbers('cordova/exec', 'Cordova.exec');
  994. // Call the platform-specific initialization.
  995. platform.bootstrap && platform.bootstrap();
  996. // Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.
  997. // The delay allows the attached modules to be defined before the plugin loader looks for them.
  998. setTimeout(function () {
  999. pluginloader.load(function () {
  1000. channel.onPluginsReady.fire();
  1001. });
  1002. }, 0);
  1003. /**
  1004. * Create all cordova objects once native side is ready.
  1005. */
  1006. channel.join(function () {
  1007. modulemapper.mapModules(window);
  1008. platform.initialize && platform.initialize();
  1009. // Fire event to notify that all objects are created
  1010. channel.onCordovaReady.fire();
  1011. // Fire onDeviceReady event once page has fully loaded, all
  1012. // constructors have run and cordova info has been received from native
  1013. // side.
  1014. channel.join(function () {
  1015. require('cordova').fireDocumentEvent('deviceready');
  1016. }, channel.deviceReadyChannelsArray);
  1017. }, platformInitChannelsArray);
  1018. });
  1019. // file: src/common/modulemapper.js
  1020. define("cordova/modulemapper", function(require, exports, module) {
  1021. var builder = require('cordova/builder');
  1022. var moduleMap = define.moduleMap; // eslint-disable-line no-undef
  1023. var symbolList;
  1024. var deprecationMap;
  1025. exports.reset = function () {
  1026. symbolList = [];
  1027. deprecationMap = {};
  1028. };
  1029. function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {
  1030. if (!(moduleName in moduleMap)) {
  1031. throw new Error('Module ' + moduleName + ' does not exist.');
  1032. }
  1033. symbolList.push(strategy, moduleName, symbolPath);
  1034. if (opt_deprecationMessage) {
  1035. deprecationMap[symbolPath] = opt_deprecationMessage;
  1036. }
  1037. }
  1038. // Note: Android 2.3 does have Function.bind().
  1039. exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {
  1040. addEntry('c', moduleName, symbolPath, opt_deprecationMessage);
  1041. };
  1042. exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {
  1043. addEntry('m', moduleName, symbolPath, opt_deprecationMessage);
  1044. };
  1045. exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {
  1046. addEntry('d', moduleName, symbolPath, opt_deprecationMessage);
  1047. };
  1048. exports.runs = function (moduleName) {
  1049. addEntry('r', moduleName, null);
  1050. };
  1051. function prepareNamespace (symbolPath, context) {
  1052. if (!symbolPath) {
  1053. return context;
  1054. }
  1055. var parts = symbolPath.split('.');
  1056. var cur = context;
  1057. for (var i = 0, part; part = parts[i]; ++i) { // eslint-disable-line no-cond-assign
  1058. cur = cur[part] = cur[part] || {};
  1059. }
  1060. return cur;
  1061. }
  1062. exports.mapModules = function (context) {
  1063. var origSymbols = {};
  1064. context.CDV_origSymbols = origSymbols;
  1065. for (var i = 0, len = symbolList.length; i < len; i += 3) {
  1066. var strategy = symbolList[i];
  1067. var moduleName = symbolList[i + 1];
  1068. var module = require(moduleName);
  1069. // <runs/>
  1070. if (strategy === 'r') {
  1071. continue;
  1072. }
  1073. var symbolPath = symbolList[i + 2];
  1074. var lastDot = symbolPath.lastIndexOf('.');
  1075. var namespace = symbolPath.substr(0, lastDot);
  1076. var lastName = symbolPath.substr(lastDot + 1);
  1077. var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;
  1078. var parentObj = prepareNamespace(namespace, context);
  1079. var target = parentObj[lastName];
  1080. if (strategy === 'm' && target) {
  1081. builder.recursiveMerge(target, module);
  1082. } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {
  1083. if (!(symbolPath in origSymbols)) {
  1084. origSymbols[symbolPath] = target;
  1085. }
  1086. builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);
  1087. }
  1088. }
  1089. };
  1090. exports.getOriginalSymbol = function (context, symbolPath) {
  1091. var origSymbols = context.CDV_origSymbols;
  1092. if (origSymbols && (symbolPath in origSymbols)) {
  1093. return origSymbols[symbolPath];
  1094. }
  1095. var parts = symbolPath.split('.');
  1096. var obj = context;
  1097. for (var i = 0; i < parts.length; ++i) {
  1098. obj = obj && obj[parts[i]];
  1099. }
  1100. return obj;
  1101. };
  1102. exports.reset();
  1103. });
  1104. // file: /Users/erisu/git/apache/cordova/cordova-browser/cordova-js-src/platform.js
  1105. define("cordova/platform", function(require, exports, module) {
  1106. module.exports = {
  1107. id: 'browser',
  1108. cordovaVersion: '4.2.0', // cordova-js
  1109. bootstrap: function() {
  1110. var modulemapper = require('cordova/modulemapper');
  1111. var channel = require('cordova/channel');
  1112. modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy');
  1113. channel.onNativeReady.fire();
  1114. document.addEventListener("visibilitychange", function(){
  1115. if(document.hidden) {
  1116. channel.onPause.fire();
  1117. }
  1118. else {
  1119. channel.onResume.fire();
  1120. }
  1121. });
  1122. // End of bootstrap
  1123. }
  1124. };
  1125. });
  1126. // file: src/common/pluginloader.js
  1127. define("cordova/pluginloader", function(require, exports, module) {
  1128. var modulemapper = require('cordova/modulemapper');
  1129. // Helper function to inject a <script> tag.
  1130. // Exported for testing.
  1131. exports.injectScript = function (url, onload, onerror) {
  1132. var script = document.createElement('script');
  1133. // onload fires even when script fails loads with an error.
  1134. script.onload = onload;
  1135. // onerror fires for malformed URLs.
  1136. script.onerror = onerror;
  1137. script.src = url;
  1138. document.head.appendChild(script);
  1139. };
  1140. function injectIfNecessary (id, url, onload, onerror) {
  1141. onerror = onerror || onload;
  1142. if (id in define.moduleMap) { // eslint-disable-line no-undef
  1143. onload();
  1144. } else {
  1145. exports.injectScript(url, function () {
  1146. if (id in define.moduleMap) { // eslint-disable-line no-undef
  1147. onload();
  1148. } else {
  1149. onerror();
  1150. }
  1151. }, onerror);
  1152. }
  1153. }
  1154. function onScriptLoadingComplete (moduleList, finishPluginLoading) {
  1155. // Loop through all the plugins and then through their clobbers and merges.
  1156. for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign
  1157. if (module.clobbers && module.clobbers.length) {
  1158. for (var j = 0; j < module.clobbers.length; j++) {
  1159. modulemapper.clobbers(module.id, module.clobbers[j]);
  1160. }
  1161. }
  1162. if (module.merges && module.merges.length) {
  1163. for (var k = 0; k < module.merges.length; k++) {
  1164. modulemapper.merges(module.id, module.merges[k]);
  1165. }
  1166. }
  1167. // Finally, if runs is truthy we want to simply require() the module.
  1168. if (module.runs) {
  1169. modulemapper.runs(module.id);
  1170. }
  1171. }
  1172. finishPluginLoading();
  1173. }
  1174. // Handler for the cordova_plugins.js content.
  1175. // See plugman's plugin_loader.js for the details of this object.
  1176. // This function is only called if the really is a plugins array that isn't empty.
  1177. // Otherwise the onerror response handler will just call finishPluginLoading().
  1178. function handlePluginsObject (path, moduleList, finishPluginLoading) {
  1179. // Now inject the scripts.
  1180. var scriptCounter = moduleList.length;
  1181. if (!scriptCounter) {
  1182. finishPluginLoading();
  1183. return;
  1184. }
  1185. function scriptLoadedCallback () {
  1186. if (!--scriptCounter) {
  1187. onScriptLoadingComplete(moduleList, finishPluginLoading);
  1188. }
  1189. }
  1190. for (var i = 0; i < moduleList.length; i++) {
  1191. injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback);
  1192. }
  1193. }
  1194. function findCordovaPath () {
  1195. var path = null;
  1196. var scripts = document.getElementsByTagName('script');
  1197. var term = '/cordova.js';
  1198. for (var n = scripts.length - 1; n > -1; n--) {
  1199. var src = scripts[n].src.replace(/\?.*$/, ''); // Strip any query param (CB-6007).
  1200. if (src.indexOf(term) === (src.length - term.length)) {
  1201. path = src.substring(0, src.length - term.length) + '/';
  1202. break;
  1203. }
  1204. }
  1205. return path;
  1206. }
  1207. // Tries to load all plugins' js-modules.
  1208. // This is an async process, but onDeviceReady is blocked on onPluginsReady.
  1209. // onPluginsReady is fired when there are no plugins to load, or they are all done.
  1210. exports.load = function (callback) {
  1211. var pathPrefix = findCordovaPath();
  1212. if (pathPrefix === null) {
  1213. console.log('Could not find cordova.js script tag. Plugin loading may fail.');
  1214. pathPrefix = '';
  1215. }
  1216. injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function () {
  1217. var moduleList = require('cordova/plugin_list');
  1218. handlePluginsObject(pathPrefix, moduleList, callback);
  1219. }, callback);
  1220. };
  1221. });
  1222. // file: src/common/urlutil.js
  1223. define("cordova/urlutil", function(require, exports, module) {
  1224. /**
  1225. * For already absolute URLs, returns what is passed in.
  1226. * For relative URLs, converts them to absolute ones.
  1227. */
  1228. exports.makeAbsolute = function makeAbsolute (url) {
  1229. var anchorEl = document.createElement('a');
  1230. anchorEl.href = url;
  1231. return anchorEl.href;
  1232. };
  1233. });
  1234. // file: src/common/utils.js
  1235. define("cordova/utils", function(require, exports, module) {
  1236. var utils = exports;
  1237. /**
  1238. * Defines a property getter / setter for obj[key].
  1239. */
  1240. utils.defineGetterSetter = function (obj, key, getFunc, opt_setFunc) {
  1241. if (Object.defineProperty) {
  1242. var desc = {
  1243. get: getFunc,
  1244. configurable: true
  1245. };
  1246. if (opt_setFunc) {
  1247. desc.set = opt_setFunc;
  1248. }
  1249. Object.defineProperty(obj, key, desc);
  1250. } else {
  1251. obj.__defineGetter__(key, getFunc);
  1252. if (opt_setFunc) {
  1253. obj.__defineSetter__(key, opt_setFunc);
  1254. }
  1255. }
  1256. };
  1257. /**
  1258. * Defines a property getter for obj[key].
  1259. */
  1260. utils.defineGetter = utils.defineGetterSetter;
  1261. utils.arrayIndexOf = function (a, item) {
  1262. if (a.indexOf) {
  1263. return a.indexOf(item);
  1264. }
  1265. var len = a.length;
  1266. for (var i = 0; i < len; ++i) {
  1267. if (a[i] === item) {
  1268. return i;
  1269. }
  1270. }
  1271. return -1;
  1272. };
  1273. /**
  1274. * Returns whether the item was found in the array.
  1275. */
  1276. utils.arrayRemove = function (a, item) {
  1277. var index = utils.arrayIndexOf(a, item);
  1278. if (index !== -1) {
  1279. a.splice(index, 1);
  1280. }
  1281. return index !== -1;
  1282. };
  1283. utils.typeName = function (val) {
  1284. return Object.prototype.toString.call(val).slice(8, -1);
  1285. };
  1286. /**
  1287. * Returns an indication of whether the argument is an array or not
  1288. */
  1289. utils.isArray = Array.isArray ||
  1290. function (a) { return utils.typeName(a) === 'Array'; };
  1291. /**
  1292. * Returns an indication of whether the argument is a Date or not
  1293. */
  1294. utils.isDate = function (d) {
  1295. return (d instanceof Date);
  1296. };
  1297. /**
  1298. * Does a deep clone of the object.
  1299. */
  1300. utils.clone = function (obj) {
  1301. if (!obj || typeof obj === 'function' || utils.isDate(obj) || typeof obj !== 'object') {
  1302. return obj;
  1303. }
  1304. var retVal, i;
  1305. if (utils.isArray(obj)) {
  1306. retVal = [];
  1307. for (i = 0; i < obj.length; ++i) {
  1308. retVal.push(utils.clone(obj[i]));
  1309. }
  1310. return retVal;
  1311. }
  1312. retVal = {};
  1313. for (i in obj) {
  1314. // https://issues.apache.org/jira/browse/CB-11522 'unknown' type may be returned in
  1315. // custom protocol activation case on Windows Phone 8.1 causing "No such interface supported" exception
  1316. // on cloning.
  1317. if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') { // eslint-disable-line valid-typeof
  1318. retVal[i] = utils.clone(obj[i]);
  1319. }
  1320. }
  1321. return retVal;
  1322. };
  1323. /**
  1324. * Returns a wrapped version of the function
  1325. */
  1326. utils.close = function (context, func, params) {
  1327. return function () {
  1328. var args = params || arguments;
  1329. return func.apply(context, args);
  1330. };
  1331. };
  1332. // ------------------------------------------------------------------------------
  1333. function UUIDcreatePart (length) {
  1334. var uuidpart = '';
  1335. for (var i = 0; i < length; i++) {
  1336. var uuidchar = parseInt((Math.random() * 256), 10).toString(16);
  1337. if (uuidchar.length === 1) {
  1338. uuidchar = '0' + uuidchar;
  1339. }
  1340. uuidpart += uuidchar;
  1341. }
  1342. return uuidpart;
  1343. }
  1344. /**
  1345. * Create a UUID
  1346. */
  1347. utils.createUUID = function () {
  1348. return UUIDcreatePart(4) + '-' +
  1349. UUIDcreatePart(2) + '-' +
  1350. UUIDcreatePart(2) + '-' +
  1351. UUIDcreatePart(2) + '-' +
  1352. UUIDcreatePart(6);
  1353. };
  1354. /**
  1355. * Extends a child object from a parent object using classical inheritance
  1356. * pattern.
  1357. */
  1358. utils.extend = (function () {
  1359. // proxy used to establish prototype chain
  1360. var F = function () {};
  1361. // extend Child from Parent
  1362. return function (Child, Parent) {
  1363. F.prototype = Parent.prototype;
  1364. Child.prototype = new F();
  1365. Child.__super__ = Parent.prototype;
  1366. Child.prototype.constructor = Child;
  1367. };
  1368. }());
  1369. /**
  1370. * Alerts a message in any available way: alert or console.log.
  1371. */
  1372. utils.alert = function (msg) {
  1373. if (window.alert) {
  1374. window.alert(msg);
  1375. } else if (console && console.log) {
  1376. console.log(msg);
  1377. }
  1378. };
  1379. });
  1380. window.cordova = require('cordova');
  1381. // file: src/scripts/bootstrap.js
  1382. require('cordova/init');
  1383. })();