UNPKG

webview-module-api

Version:

Standard module APIs of the <web-view> component within windmill.

718 lines (659 loc) 40 kB
/* __webviewModuleApi (0.3.8), build at 2019-06-05 18:17. */ var __webviewModuleApi = (function () { 'use strict'; (typeof window === 'undefined') && (window = {ctrl: {}, lib: {}});!window.ctrl && (window.ctrl = {});!window.lib && (window.lib = {});!function(a,b){function c(a,b){a=a.toString().split("."),b=b.toString().split(".");for(var c=0;c<a.length||c<b.length;c++){var d=parseInt(a[c],10),e=parseInt(b[c],10);if(window.isNaN(d)&&(d=0),window.isNaN(e)&&(e=0),e>d){ return -1; }if(d>e){ return 1 }}return 0}var d=a.Promise,e=a.document,f=a.navigator.userAgent,g=/Windows\sPhone\s(?:OS\s)?[\d\.]+/i.test(f)||/Windows\sNT\s[\d\.]+/i.test(f),h=g&&a.WindVane_Win_Private&&a.WindVane_Win_Private.call,i=/iPhone|iPad|iPod/i.test(f),j=/Android/i.test(f),k=f.match(/WindVane[\/\s](\d+[._]\d+[._]\d+)/),l=Object.prototype.hasOwnProperty,m=b.windvane=a.WindVane||(a.WindVane={version:"3.0.4"}),n=Math.floor(65536*Math.random()),o=1,p=[],q=3,r="hybrid",s="wv_hybrid",t="iframe_",u="param_",v=6e5,w=6e4;k=k?(k[1]||"0.0.0").replace(/\_/g,"."):"0.0.0";var x={isAvailable:1===c(k,"0"),isNewBridgeAvailable:1===c(k,j?"8.3.0":"8.2.0"),call2:function(a,b,c,d,e){var f=a.indexOf(".");return x.call(a.substr(0,f),a.substr(f+1),b,c,d,e)},call:function(b,c,e,f,g,h){var i,j;if("number"==typeof arguments[arguments.length-1]&&(h=arguments[arguments.length-1]),"function"!=typeof f&&(f=null),"function"!=typeof g&&(g=null),!d||f||g||(j=new d(function(a,b){f=a,g=b;})),x.isNewBridgeAvailable&&a.__windvane__&&a.__windvane__.call){ return a.__windvane__.call(b+"."+c,e,f,g,h),j; }i=y.getSid();var k={success:f,failure:g};return h>0&&(k.timeout=setTimeout(function(){x.onFailure(i,{ret:"HY_TIMEOUT"});},h)),y.registerCall(i,k),y.registerGC(i,h),x.isAvailable?y.callMethod(b,c,e,i):x.onFailure(i,{ret:"HY_NOT_IN_WINDVANE"}),j},fireEvent:function(a,b,c){var d=e.createEvent("HTMLEvents");d.initEvent(a,!1,!0),d.param=y.parseData(b),e.dispatchEvent(d);},getParam:function(a){return y.getParam(a)},setData:function(a,b){},find:function(a,b){b||y.unregisterCall(a,!1);},onSuccess:function(a,b,c){y.onComplete(a,b,"success",c);},onFailure:function(a,b){y.onComplete(a,b,"failure");}};x.isNewBridgeAvailable&&a.__windvane__&&a.__windvane__.callSync&&(x.callSync=function(b,c){if(i){ return a.__windvane__.callSync(b,c); }if(j){var d={name:b};c&&(d.params=JSON.stringify(c));var e=a.__windvane__.callSync(d);if(e){ try{return JSON.parse(e)}catch(f){} }}});var y={params:{},calls:{},getSid:function(){return (n+o++)%65536+""},buildParam:function(a){return a&&"object"==typeof a?JSON.stringify(a):a||""},getParam:function(a){return this.params[u+a]||""},setParam:function(a,b){this.params[u+a]=b;},parseData:function(a){var b;if(a&&"string"==typeof a){ try{b=JSON.parse(a);}catch(c){b={ret:"HY_RESULT_PARSE_ERROR",originValue:a};} }else { b=a||{}; }return b},registerCall:function(a,b){this.calls[a]=b;},unregisterCall:function(a,b){var c=this.calls[a]||{},d=c.timeout;return d&&clearTimeout(d),b||delete this.calls[a],c},useIframe:function(a,b){var c=t+a,d=p.pop();d||(d=e.createElement("iframe"),d.setAttribute("frameborder","0"),d.style.cssText="width:0;height:0;border:0;display:none;"),d.setAttribute("id",c),d.setAttribute("src",b),d.parentNode||setTimeout(function(){e.body.appendChild(d);},5);},retrieveIframe:function(a){var b=t+a,c=e.querySelector("#"+b);if(c){ if(p.length>=q){ try{e.body.removeChild(c);}catch(d){} }else { p.indexOf(c)<0&&p.push(c); } }},callMethod:function(b,c,d,e){var f=y.buildParam(d);if(g){ h?a.WindVane_Win_Private.call(b,c,e,f):this.onComplete(e,{ret:"HY_NO_HANDLER_ON_WP"},"failure"); }else if(i){this.setParam(e,f);var k=r+"://"+b+":"+e+"/"+c+"?"+encodeURIComponent(f);this.useIframe(e,k);}else if(j){this.setParam(e,d);var k=r+"://"+b+":"+e+"/"+c+"?"+f,l=s+":";window.prompt(k,l);}else { this.onComplete(e,{ret:"HY_NOT_SUPPORT_DEVICE"},"failure"); }},registerGC:function(a,b){var c=this,d=Math.max(b||0,v),e=Math.max(b||0,w);setTimeout(function(){c.unregisterCall(a);},d),i&&setTimeout(function(){c.params[u+a]&&delete c.params[u+a];},e);},onComplete:function(a,b,c,d){var e=this.unregisterCall(a,d),f=e.success,g=e.failure;b=this.parseData(b);var h=b.ret;"string"==typeof h&&(b=b.value||b,b.ret||(b.ret=[h])),"success"===c?f&&f(b):"failure"===c&&g&&g(b),i&&(this.retrieveIframe(a),this.params[u+a]&&delete this.params[u+a]);}};for(var z in x){ l.call(m,z)||(m[z]=x[z]); }}(window,window.lib||(window.lib={}));var windvane_common = window.lib['windvane']; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var index_min = createCommonjsModule(function (module, exports) { /** * windmill.renderer.min.js v0.4.2. */ console.log("Start windmill renderer.min (0.4.2) framework. Build at 2018-09-20 19:21"),function(e,t){module.exports=t();}(commonjsGlobal,function(){"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{writable:!0,enumerable:!1,configurable:!0,value:function(e,t){var n=arguments;if(null==e){ throw new TypeError("Cannot convert undefined or null to object"); }for(var i=Object(e),o=1;o<arguments.length;o++){var r=n[o];if(null!=r){ for(var a in r){ Object.prototype.hasOwnProperty.call(r,a)&&(i[a]=r[a]); } }}return i}});var t,r=(t=1e5,function(){var e=String(t);return t+=1,e});function d(t,n,e){void 0===e&&(e=!0);var i="undefined"!=typeof commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:new Function("return this")();try{Object.defineProperty(i,t,{value:n,configurable:!0,enumerable:!0,writable:!e});}catch(e){i[t]=n;}}function s(e){return Object.prototype.toString.call(e).slice(8,-1)}function l(e){return "Object"===s(e)}function o(){ var arguments$1 = arguments; for(var e=[],t=arguments.length;t--;){ e[t]=arguments$1[t]; }}var n=function(){},u={},a=["Android","iOS"];function i(e,t){if("object"==typeof process&&process&&process.env,!0===u.debugMode){ return !0 }}function p(e,t){i()&&n("debug",e);}function g(e,t){i()&&n("warn",e);}function c(e,t){i()&&n("error",e);}function f(e){c(e);}n=function(e,t){var n,i="["+((n=e).charAt(0).toUpperCase()+n.slice(1))+"][wml-r] "+t;return u.isWeex&&-1<a.indexOf(u.platform)?console.log(i):console.error(i)};var h={network:["request","uploadFile"],miniApp:["setAppShareInfo","hideLauncherLoading","setWebViewTop","setWebViewBackgroundImage"],mtop:["request"],storage:["length","setItem","getItem","removeItem"],memoryStorage:["setItem","getItem"],tabBar:["show","hide"],navigator:["push","pop","openMessagePage","reloadPage","getBackStack","popToHome","navigateTo","redirectTo","switchTab"],user:["login","logout","info"],modal:["alert","confirm","toast","showLoading","hideLoading"],navigatorBar:["show","hide","setTitle","setRightItem","setStyle","setDrawer","setActionSheet","hasIndexBadge","scaleIndexBadge","resetIndexBadge","getHeight","openDrawer","isDrawerOpened","closeDrawer","setLeftItem","showMenu","hideMenu","getStatusBarHeight","setNavigationBar"],clipboard:["writeText","readText"],picker:["pick","pickDate","pickTime","chooseCity"],webSocket:["webSocket","send","close","onOpen","onMessage","onClose","onError"],calendar:["addEvent","checkEvent","removeEvent"],connection:["getType","getDownlinkMax","onChange"],screen:["setAlwaysOn","setBrightness","getScreenBrightness"],broadcast:["createChannel","postMessage","onMessage","close"],share:["doShare"],cookie:["read","write","getAllObjects"],audio:["load","play","pause","stop","setVolume","canPlayType"],wopc:["authLogin","checkAuthSession","doAuth","getSessionKey","setSessionKey"],WopcMtopPlugin:["request"],device:["onShake","vibrate"],keyboard:["hideKeyboard"],contact:["choosePhoneContact"],location:["getLocation"],alipay:["tradePay"],userTrack:["commit","commitut","commitEvent","customAdvance","pageAppear","pageDisappear","skipPage","updatePageUtparam","updateNextPageUtparam"],"nuvajs-exec":["exec"],aluWVJSBridge:["userIsLogin","refreshAlipayCookie"],TBDeviceInfo:["getUtdid"],actionSheet:["showActionSheet"],image:["chooseImage","previewImage","compressImage","getImageInfo","saveImage"],media:["startVoice","stopVoice"],audioRecord:["startRecord","stopRecord","cancelRecord"],audioPlayer:["playVoice","pauseVoice","stopVoice"],file:["saveFile","getFileInfo","getFileList","removeFile"],video:["chooseVideo","getVideoInfo"],phone:["makePhoneCall"],compass:["startCompass","stopCompass","onCompassChange"],tbsecurity:["secureToken"]};var e=function(){};e.prototype.$on=function(e,t){return void 0===t&&(t=o),p('$on "'+e+'"'),!e&&f("invalid event name "+e+" for windmill.$on."),t===o&&f("bind event "+e+" with no callback through windmill.$on."),this.bridge.onReceiveMessage({data:{type:e},origin:this.label,type:"Event"},t)},e.prototype.$once=function(e,t){return void 0===t&&(t=o),p('$once "'+e+'"'),!e&&f("invalid event name "+e+" for windmill.$once."),t===o&&f("bind event "+e+" with no callback through windmill.$once."),this.bridge.onReceiveMessage({data:{type:e,once:!0},origin:this.label,type:"Event"},t)},e.prototype.$off=function(e,t){return p('$off "'+e+'"'),!e&&f("invalid event name "+e+" for windmill.$off."),this.bridge.unbindEventListener("Event."+e,t)},e.prototype.$cycle=function(e,t){return void 0===t&&(t=o),p('$cycle "'+e+'"'),e&&/^app:|^page(:|@)/.test(e)||f("invalid lifecycle name "+e+" for windmill.$cycle."),t===o&&f("hook lifecycle "+e+" with no callback function through windmill.$cycle."),"AppWorker"!==this.label&&/^app:/.test(e)&&f("Shouldn't bind lifecycle hook for app in a page client."),this.bridge.onReceiveMessage({type:"Lifecycle",origin:this.label,data:{type:e}},t)},e.prototype.$decycle=function(e,t){return p('$decycle "'+e+'"'),e&&/^app:|^page(:|@)/.test(e)||f("invalid lifecycle name "+e+" for windmill.$decycle."),this.bridge.unbindEventListener("Lifecycle."+e,t)},e.prototype.$emit=function(e,t,n){return void 0===t&&(t={}),p('$emit("'+e+'")'),!e&&f("invalid event name "+e+" for windmill.$emit."),n&&n!==this.label?this.bridge.postMessage({data:{type:e,data:t},origin:this.label,target:n,type:"Event"}):this.bridge.emitEvent(""+e,t)},e.prototype.$callAsync=function(n,i){var o=this;return void 0===i&&(i={}),p('$callAsync "'+n+'"'),n||f("invalid method name "+n+" for windmill.$callAsync."),new Promise(function(e,t){o.bridge.dispatchMessage({type:"ModuleCall",origin:o.label,target:"AppWorker",data:{method:n,params:i}},e,t,!1);})},e.prototype.$call=function(e,t,n,i){return void 0===t&&(t={}),void 0===n&&(n=o),void 0===i&&(i=o),p('$call "'+e+'", params: '+JSON.stringify(t)),e||f("invalid method name "+e+" for windmill.$call."),this.bridge.dispatchMessage({type:"ModuleCall",origin:this.label,target:"AppWorker",data:{method:e,params:t}},n,i,!0)},e.prototype.$registerModules=function(e){!function(i,o){if(void 0===o&&(o=!1),l(i)){var e=function(t){var e=i[t];h[t]?o||g('The "'+t+'" module has already been registered.It would be overridden.'):h[t]=[];var n=h[t];Array.isArray(e)?e.forEach(function(e){-1===n.indexOf(e)?n.push(e):o||g('The "'+e+'" of the "'+t+'" module has already been registered.');}):c('Invalid parameter type! The method list of the "'+t+'" module should be an Array.');};for(var t in i){ e(t); }}else { c("Invalid parameter type! The module definition is not a plain object."); }}(e,!0);},e.prototype.$getAvailableModules=function(){return function(e){var t={};try{t=JSON.parse(JSON.stringify(e));}catch(e){}return t}(h)};var m="[[EVENT_MAP]]";function v(e,t){var n=e[m];return Array.isArray(n[t])||(n[t]=[]),n[t]}var y,b=function(){p("Create new EventEmitter."),Object.defineProperty(this,m,{configurable:!1,enumerable:!1,writable:!1,value:{}});};function w(t){var n;try{n=JSON.stringify(t);}catch(e){n=t;}f("failed to postMessage: "+n);}function k(e,t,n,i,o,r){var a=t+"."+n;return e.WindVane?e.WindVane.call(t,n,i,o,r):f("should have WindVane in global context"+(a?" to call "+a:"")+".")}b.prototype.on=function(e,t){return p('EventEmitter: on("'+e+'")'),v(this,e).push({listener:t,once:!1,callCount:0}),this},b.prototype.once=function(e,t){return p('EventEmitter: once("'+e+'")'),v(this,e).push({listener:t,once:!0,callCount:0}),this},b.prototype.off=function(e,t){p('EventEmitter: off("'+e+'"'+(t?", listener":"")+")");var n=this[m];if(t){var i=n[e];if(Array.isArray(i)){var o=i.findIndex(function(e){return e.listener===t});-1!==o&&i.splice(o,1);}}else { delete n[e]; }return this};var M=!(b.prototype.emit=function(t){ var arguments$1 = arguments; for(var n=[],e=arguments.length-1;0<e--;){ n[e]=arguments$1[e+1]; }p('EventEmitter: emit("'+t+'", '+JSON.stringify(n)+")");var i=this[m],o=i[t];return Array.isArray(o)&&(i[t]=o.filter(function(e){try{e.listener.apply(null,n),e.callCount+=1;}catch(e){return c('Failed to emit "'+t+'" event.'),c(e.toString()),!0}return !e.once})),this});var A=function(){this._messages=[];};A.prototype.postMessage=function(e){p("cache message in lazyMsgModule. "+JSON.stringify(e)),this._messages.push(e);},A.prototype.replaceWith=function(e){S=!1,this._messageModule=e,this._flush();},A.prototype._flush=function(){var t=this;this._messages.forEach(function(e){return t._messageModule.postMessage(e)});};var S,$,E=new A;function I(e,t){var n,i=e?(n=e).requireModule("@weex/windmill")||n.requireModule("windmill"):function(){if(!y){var t="undefined"!=typeof window?window:commonjsGlobal;y={postMessage:function(e){return k(t,"Windmill","postMessage",e,function(){},w)},onmessage:function(e){if(!M){ return M=!0,k(t,"Windmill","onMessage",{},e,w) }}};}return y}();if(!i){ return f("can't find message module ("+(e?"windmill module":"message module in webview")+")."),S=!0,E; }if("function"==typeof t){p('Set the "onmessage" method to the bridge through callback.');try{i.onmessage(t);}catch(e){c('Failed to set the "onmessage" method to the bridge through callback.'),c(e.toString());}}return S&&E.replaceWith(i),i}function _(e){var t=e.match(/([^@]+)(@\S+)/);return t&&t[1]||e}var O=function(e,t){var a=this;void 0===t&&(t={}),p("Create a new RendererBridge."),$=t.isWeex,this._emitter=new b,p("Register onmessage api for "+($?"Weex windmill module":"webview")+"."),$&&(this._weex=e),this._onMessage=function(e){if(p("Receive message from the worker. (message: "+JSON.stringify(e)+")"),!l(e)&&(c("The parameter of onmessage should be a plain object! Not "+s(e)),"string"==typeof e)){ try{e=JSON.parse(e);}catch(e){return void c("Failed to parse the message string. "+e.toString())} }var t=e.type,n=e.data;void 0===n&&(n={});var i=e.origin,o=e.callbackId;switch(t){case"Callback":a._emitter.emit("callback@AppWorker:"+o,n);break;case"Event":var r=_(n.type);a._emitter.emit(t+"."+r,Object.assign({origin:i},n,{type:r}));break;case"Lifecycle":a._emitter.emit(t+"."+n.lifecycle,n.options);break;case"SetData":a._emitter.emit("Event.setdata",n);break;default:f('Unknown message type received from worker: "'+t+'"');}},I(e,this._onMessage);};O.prototype.dispatchMessage=function(t,n,i,e){p("Dispatch message to worker. (message: "+JSON.stringify(t)+")"),t.callbackId=this._genCallbackId(function(e){return e.status&&"SUCCESS"===e.status?n(e):(e.status,c("call API "+t.data.method+" from renderer failed: "+e.status+", "+e.error),i(e))},{keepAlive:e});try{t.keepAlive=!0,this.postMessage(t);}catch(e){i(e);}},O.prototype.postMessage=function(e){try{p("Call postMessage to worker. (message: "+JSON.stringify(e)+")"),I(this._weex,this._onMessage).postMessage(e);}catch(e){f(e.message||e.toString()||"postMessage failed.");}},O.prototype._genCallbackId=function(e,t){var n=t.keepAlive,i=t.callbackId,o=i||r();return this._emitter[n?"on":"once"]("callback@AppWorker:"+o,e),o},O.prototype.onReceiveMessage=function(e,t){var n=e.type,i=e.data;void 0===i&&(i={});var o=i.type;"Event"===n&&(o=_(o),i.type=o);var r=i.once?"once":"on";this._emitter[r](n+"."+o,t);},O.prototype.unbindEventListener=function(e,t){this._emitter.off(_(e),t);},O.prototype.emitEvent=function(e,t){void 0===t&&(t={});var n=_(e);this._emitter.emit("Event."+n,{type:n,data:t});};var x=function(n){function e(e,t){void 0===t&&(t={}),n.call(this),this._name=t.pageName||"",this.label=t.clientId||"",e&&l(e.config)&&(this._name=e.config.pageName||"",this.label=e.config.clientId||"",e.config.availableModules?(this.$registerModules(e.config.availableModules),this._gotAvailableModulesFromWeex=!0):g("No available modules in weex options.")),p("Create a new RendererRuntime. ("+this.label+", "+this._name+")"),this.bridge=new O(e,t),this._init();}return n&&(e.__proto__=n),((e.prototype=Object.create(n&&n.prototype)).constructor=e).prototype._init=function(){var t=this;this.bridge.onReceiveMessage({origin:"AppWorker",target:this.label,type:"Event",data:{type:"registerModules"}},function(e){e&&"registerModules"===e.type&&(p("Register available modules in renderer. ("+Object.keys(e.data)+")"),t.$registerModules(e.data));});},e.prototype.ready=function(){this.bridge.dispatchMessage({origin:this.label,target:"AppWorker",type:"Event",data:{type:"[[RendererRuntimeReady]]",data:{label:this.label,handshake:!this._gotAvailableModulesFromWeex}}},o,o);},e.prototype.$getCurrentActivePageId=function(){return this.label},e}(e),C=["$on","$once","$off","$emit","$cycle","$decycle","$call","$callAsync","$navTo","$getAvailableModules","$getCurrentActivePageId"];return function(e,t){var n=!(!e||!e.requireModule);!function(e){if(!e||!e.platform){ return console.error("set logger environment failed."); }Object.assign(u,e);}({platform:n&&e.config.env.platform,debugMode:n&&e.config.env.debugMode,isWeex:n}),p("Setup Windmill renderer framework."),e&&!e.requireModule&&(t=e,e=void 0),t||(t={}),p("Instantiate renderer in "+(((t=Object.assign({},t)).isWeex=n)?"Weex container":"WindVane container")+".");var i,o,r,s,l=new x(e,t),c=(i=l,o={},C.forEach(function(n){"function"==typeof i[n]&&(o[n]=function(){ var arguments$1 = arguments; for(var e=[],t=arguments.length;t--;){ e[t]=arguments$1[t]; }return i[n].apply(i,e)});}),o);return p("Prepare runtime APIs: "+JSON.stringify(C)),t.exposeModuleGetter&&d("__WINDMILL_MODULE_GETTER__",(r=function(){return c},s=function(){ var arguments$1 = arguments; for(var e,t=[],n=arguments.length;n--;){ t[n]=arguments$1[n]; }return (e=r()).$call.apply(e,t)},function(i){if(!i){ return p("Require a universal module proxy."),{call:s}; }var e=h[i];if(Array.isArray(e)){p('Require the "'+i+'" module.');var t={};return e.forEach(function(n){t[n]=function(){ var arguments$1 = arguments; for(var e=[],t=arguments.length;t--;){ e[t]=arguments$1[t]; }return s.apply(void 0,[i+"."+n].concat(e))};}),t}g('Require unknown module "'+i+"\".It may not exist or haven't been registered.");})),l.ready(),c}}); }); // 挂载到全局环境上的 windmill runtime api var RUNTIME_API = '__WINDMILL_WORKER_RUNTIME_APIS__'; // webview 组件和小程序之间通信的事件名 var WEBVIEW_MESSAGE = '__WEBVIEW_MESSAGE_EVENT_NAME__'; // storage 对于自动 JSON 序列化添加的标记 var STORAGE_JSON_FLAG = '[[JSON]]'; var STORAGE_JSON_FLAG_REGEXP = /^\[\[JSON\]\].*/; /** * Get current runtime context object */ function getContextObject() { return typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : (new Function('return this'))(); // tslint:disable-line } // windmill worker framework 环境里获取模块的全局变量 var getterMethod = '__WINDMILL_MODULE_GETTER__'; function moduleGetter(name) { var context = getContextObject(); // 兼容小程序 worker framework 环境 if (context && typeof context[getterMethod] === 'function') { return context[getterMethod](name); } // 兼容 rax 和三方 dsl 的业务代码环境 if (context && typeof context.require === 'function') { return context.require(("@core/" + name)); } else { console.error("Can't find available \"require\" function."); } // 兼容小程序 vue worker 环境 if (context && context && typeof context.requireModule === 'function') { return context.requireModule(name); } // 兼容 weex 页面环境 if (context && context.weex && typeof context.weex.requireModule === 'function') { return context.weex.requireModule(("@windmill/" + name)); } } /** * Event Emitter * Partially implement the events module of Node.js. * https://nodejs.org/api/events.html#events_class_eventemitter */ var eventMapKey = '[[EVENT_MAP]]'; function initListeners(emitter, eventName) { var events = emitter[eventMapKey]; if (!Array.isArray(events[eventName])) { events[eventName] = []; } return events[eventName]; } var EventEmitter = function EventEmitter() { Object.defineProperty(this, eventMapKey, { configurable: false, enumerable: false, writable: false, value: {} }); }; EventEmitter.prototype.on = function on (eventName, listener) { var listeners = initListeners(this, eventName); listeners.push({ listener: listener, once: false, callCount: 0 }); return this; }; EventEmitter.prototype.once = function once (eventName, listener) { var listeners = initListeners(this, eventName); listeners.push({ listener: listener, once: true, callCount: 0 }); return this; }; EventEmitter.prototype.off = function off (eventName, listener) { var events = this[eventMapKey]; if (listener) { var listeners = events[eventName]; if (Array.isArray(listeners)) { var index = listeners.findIndex(function (x) { return x.listener === listener; }); if (index !== -1) { listeners.splice(index, 1); } } } else { delete events[eventName]; } return this; }; EventEmitter.prototype.emit = function emit (eventName) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var events = this[eventMapKey]; var listeners = events[eventName]; if (Array.isArray(listeners)) { // invoke event listeners events[eventName] = listeners.filter(function (desc) { try { desc.listener.apply(null, args); desc.callCount += 1; } catch (e) { return true; } return !desc.once; }); } return this; }; function hasOwn(object, key) { return Object.prototype.hasOwnProperty.call(object, key); } function getType(value) { return Object.prototype.toString.call(value).slice(8, -1); } function isPlainObject(value) { return getType(value) === 'Object'; } function isFunction(value) { return typeof value === 'function'; } function getEnv() { return typeof __windmill_environment__ === 'object' ? __windmill_environment__ : typeof wmlEnv === 'object' ? wmlEnv : typeof windmillEnv === 'object' ? windmillEnv : {}; } var currentRuntime; function getRuntime() { if (!currentRuntime) { var context = getContextObject(); currentRuntime = context[RUNTIME_API]; } return currentRuntime; } function setRuntime(runtime) { if (runtime) { currentRuntime = runtime; // TODO: expose runtime api in current context // const context = getContextObject() // context[RUNTIME_API] = runtime } } // 获取当前显示的页面的 client id function getCurrentPageId() { return getRuntime().$getCurrentActivePageId(); } /** * 拦截并预处理模块的参数 */ var preprocessorMap = {}; function preprocess(api, options) { var processor = preprocessorMap[api]; if (isFunction(processor) && isPlainObject(options)) { return processor(options); } else { return options; } } /** * 注册模块参数的预处理器,用于注入特殊的处理逻辑 */ function registerPreprocessor(my, map) { if (isPlainObject(my) && isPlainObject(map)) { for (var api in map) { if (hasOwn(my, api) && typeof map[api] === 'function') { preprocessorMap[api] = map[api]; } } } } var renderEventEmitter = new EventEmitter(); /** * Set a global API to current context */ function setGlobalAPI(name, value, readonly) { if ( readonly === void 0 ) readonly = true; var context = getContextObject(); try { Object.defineProperty(context, name, { value: value, configurable: true, enumerable: true, writable: !readonly }); } catch (e) { context[name] = value; } } var ignoreMethods = ['success', 'fail', 'complete']; function omitMethod(rawOptions) { var options = {}; for (var key in rawOptions) { if (ignoreMethods.indexOf(key) === -1) { options[key] = rawOptions[key]; } } return options; } // 获取某个模块中的方法 function getMethod(methodPath, sync) { // 使用 worker framework 提供的 runtime api (可以绕过白名单) var runtime = getRuntime(); if (runtime) { if (sync && typeof runtime.$callSync === 'function') { return function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return runtime.$callSync.apply(runtime, [ methodPath ].concat( args )); }; } else if (!sync && typeof runtime.$call === 'function') { return function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return runtime.$call.apply(runtime, [ methodPath ].concat( args )); }; } } // 使用默认的 moduleGetter 获取模块接口 var ref = methodPath.split(/\s*\.\s*/i); var module = ref[0]; var method = ref[1]; if (module && method) { var mod = moduleGetter(module); if (mod && typeof mod[method] === 'function') { return mod[method]; } } return function () { }; } // 用于安全执行内部的回调函数 function saveCall(method, args) { if (typeof method === 'function') { try { return method.apply(null, args); } catch (error) { console.error(("Failed to execute internal method: " + (error.toString()))); } } } /** * 可以注入错误处理函数,处理执行用户传递的回调函数时的错误 */ var errorHandler = function (methodPath, error) { console.error(("Failed to execute callback of \"" + methodPath + "\": " + (error.toString()))); }; // 执行用户传递的回调函数,捕获错误并输出 function invokeCallback(methodPath, callback, args) { if (typeof callback === 'function') { try { return callback.apply(null, args); } catch (error) { errorHandler(methodPath, error); } } } var modifier = {}; /** * 真实调用原生模块(异步) * @param methodPath 模块调用的字符串,形如 "modal.toast" * @param rawOptions 三方 API 对外透出的 options * @param options 传递给原生模块的 options * @param onSuccess * @param onFail */ function callModule(methodPath, rawOptions, options, onSuccess, onFail) { if ( rawOptions === void 0 ) rawOptions = {}; if ( options === void 0 ) options = rawOptions; if ( onSuccess === void 0 ) onSuccess = function (x) { return x; }; if ( onFail === void 0 ) onFail = function (x) { return x; }; var method = getMethod(methodPath); var isComplete = false; return method(omitMethod(options), function (result) { var formattedResult = saveCall(onSuccess, [result]); invokeCallback(methodPath, rawOptions.success, [formattedResult]); if (!isComplete) { invokeCallback(methodPath, rawOptions.complete, [formattedResult]); isComplete = true; } }, function (error) { var formattedError = saveCall(onFail, [error]); invokeCallback(methodPath, rawOptions.fail, [formattedError]); if (!isComplete) { invokeCallback(methodPath, rawOptions.complete, [formattedError]); isComplete = true; } }, modifier); } function showActionSheet(options) { callModule('actionSheet.showActionSheet', options); } function tradePay(options) { if ( options === void 0 ) options = {}; options = preprocess('tradePay', options); callModule('alipay.tradePay', options); } function getNetworkType(options) { options = preprocess('getNetworkType', options); callModule('connection.getType', options, {}, function (res) { var type = res.type || ''; return { networkType: type.toUpperCase() }; }); } function chooseImage(options) { callModule('image.chooseImage', options); } function previewImage(options) { callModule('image.previewImage', options); } function getLocation(options) { var type = options.type; callModule('location.getLocation', options, options, function (res) { var result = { longitude: res.coords.longitude, latitude: res.coords.latitude, accuracy: res.coords.accuracy }; if (type > 0 && res.address) { result.country = res.address.country; result.province = res.address.province; result.city = res.address.city; result.cityAdcode = res.address.cityCode; result.district = res.address.area; result.districtAdcode = res.address.areaCode; // 修复线上接口返回值参数问题 @清屿 var env = getEnv(); if (env && env.platform === 'iOS' && env.appVersion === '8.8.0') { result.cityAdcode = res.address.areaCode; } } return result; }); } function alert(options) { if ( options === void 0 ) options = {}; callModule('modal.alert', options, { title: options.title, message: options.content, okTitle: options.buttonText }); } function showLoading(options) { callModule('modal.showLoading', options); } function hideLoading(options) { callModule('modal.hideLoading', options); } function isAbsolute(pathname) { return pathname.charAt(0) === '/'; } // About 1.5x faster than the two-arg version of Array#splice() function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; } list.pop(); } // This implementation is based heavily on node's url.parse function resolvePathname(to) { var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var toParts = to && to.split('/') || []; var fromParts = from && from.split('/') || []; var isToAbs = to && isAbsolute(to); var isFromAbs = from && isAbsolute(from); var mustEndAbs = isToAbs || isFromAbs; if (to && isAbsolute(to)) { // to is absolute fromParts = toParts; } else if (toParts.length) { // to is relative, drop the filename fromParts.pop(); fromParts = fromParts.concat(toParts); } if (!fromParts.length) { return '/'; } var hasTrailingSlash = void 0; if (fromParts.length) { var last = fromParts[fromParts.length - 1]; hasTrailingSlash = last === '.' || last === '..' || last === ''; } else { hasTrailingSlash = false; } var up = 0; for (var i = fromParts.length; i >= 0; i--) { var part = fromParts[i]; if (part === '.') { spliceOne(fromParts, i); } else if (part === '..') { spliceOne(fromParts, i); up++; } else if (up) { spliceOne(fromParts, i); up--; } } if (!mustEndAbs) { for (; up--; up) { fromParts.unshift('..'); } }if (mustEndAbs && fromParts[0] !== '' && (!fromParts[0] || !isAbsolute(fromParts[0]))) { fromParts.unshift(''); } var result = fromParts.join('/'); if (hasTrailingSlash && result.substr(-1) !== '/') { result += '/'; } return result; } /// <reference path="../../types/resolve-pathname.d.ts" /> function formatPath(url) { if ( url === void 0 ) url = ''; // process absolute path return url[0] === '/' ? url.slice(1) : url; } function navigateTo(options, basePath) { if ( options === void 0 ) options = {}; if ( basePath === void 0 ) basePath = ''; options = preprocess('navigateTo', options); var url = resolvePathname(options.url, basePath) || ''; callModule('navigator.push', options, { url: formatPath(url) }); } function navigateBack(options) { callModule('navigator.pop', preprocess('navigateBack', options)); } function redirectTo(options) { if ( options === void 0 ) options = {}; options = preprocess('redirectTo', options); callModule('navigator.redirectTo', options, { url: formatPath(options.url) }); } function switchTab(options) { if ( options === void 0 ) options = {}; options = preprocess('switchTab', options); callModule('navigator.switchTab', options, { url: formatPath(options.url) }); } function httpRequest(options) { if ( options === void 0 ) options = {}; options = preprocess('httpRequest', options); var method = options.method || 'GET'; // GET 请求不支持 body 方式传递参数,需要使用 url 传参。 if (method === 'GET' && isPlainObject(options.data)) { var query = []; Object.keys(options.data).forEach(function (key) { var data = options.data[key]; var value = typeof data === 'object' ? JSON.stringify(data) : data; query.push((key + "=" + (encodeURIComponent(value)))); }); var queryString = query.join('&'); if (options.url.indexOf('?') >= 0) { options.url += queryString; } else { options.url += ('?' + queryString); } } callModule('network.request', options, { method: method, url: options.url, headers: options.headers || { 'Content-Type': 'application/x-www-form-urlencoded' }, dataType: options.dataType || 'json', body: options.data, }, function (res) { return { data: res.data, status: res.status, headers: res.headers }; }); } function proccessSetStorageValue(options) { return STORAGE_JSON_FLAG + JSON.stringify(options.data); } function setStorage(options) { if ( options === void 0 ) options = {}; callModule('storage.setItem', options, { key: options.key, value: proccessSetStorageValue(options) }); } function proccessGetStorageRes(res) { var data; if (STORAGE_JSON_FLAG_REGEXP.test(res.value)) { data = JSON.parse(res.value.substr(STORAGE_JSON_FLAG.length)); } else { data = res.value; } return { data: data }; } function getStorage(options) { if ( options === void 0 ) options = {}; callModule('storage.getItem', options, options, proccessGetStorageRes); } function removeStorage(options) { if ( options === void 0 ) options = {}; callModule('storage.removeItem', options); } function clearStorage(options) { callModule('storage.clearStorage', options); } function getStorageInfo(options) { callModule('storage.getStorageInfo', options); } /** * 获取系统环境信息 * * https://docs.alipay.com/mini/api/system-info * https://lark.alipay.com/taobaoapp/design/app_worker#%E6%B3%A8%E5%85%A5%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F */ function getSystemInfoSync() { var env = getEnv(); return { model: env.model, pixelRatio: env.pixelRatio, windowWidth: env.screenWidth, windowHeight: env.screenHeight, language: env.language, version: env.appVersion, storage: null, currentBattery: null, system: env.systemVersion, platform: env.platform, screenWidth: env.screenWidth, screenHeight: env.screenHeight, brand: env.brand, fontSizeSetting: 14, app: env.appName, SDKVersion: env.version, frameworkType: env.frameworkType, frameworkVersion: env.frameworkVersion, userAgent: env.userAgent, screenDensity: env.screenDensity // 屏幕像素密度(number),Only Android }; } function getSystemInfo(params) { if ( params === void 0 ) params = {}; try { if (typeof params.success === 'function') { params.success.call(this, getSystemInfoSync()); } } catch (err) { if (typeof params.fail === 'function') { params.fail.call(this, err); } } finally { if (typeof params.complete === 'function') { params.complete.call(this); } } } var SDKVersion = getEnv().version || ''; function sendMtop(options) { callModule('sendMtop.request', preprocess('sendMtop', options)); } /** * 在 <web-view> 标签打开的页面环境里可用的接口 */ // 从 webview 页面里向 worker 发送消息 function postMessage(message) { var runtime = getRuntime(); if (runtime) { var clientId = getCurrentPageId(); runtime.$emit((WEBVIEW_MESSAGE + "@" + clientId), message, 'AppWorker'); } } // 在 webview 页面接收 worker 发来的消息 function onMessage(onMessageHandler) { var runtime = getRuntime(); if (runtime) { var clientId = getCurrentPageId(); runtime.$on((WEBVIEW_MESSAGE + "@" + clientId), function (res) { onMessageHandler(res); }); } } var webviewAPIs = /*#__PURE__*/Object.freeze({ postMessage: postMessage, onMessage: onMessage, showActionSheet: showActionSheet, tradePay: tradePay, getNetworkType: getNetworkType, chooseImage: chooseImage, previewImage: previewImage, getLocation: getLocation, alert: alert, showLoading: showLoading, hideLoading: hideLoading, navigateTo: navigateTo, navigateBack: navigateBack, switchTab: switchTab, redirectTo: redirectTo, httpRequest: httpRequest, setStorage: setStorage, getStorage: getStorage, removeStorage: removeStorage, clearStorage: clearStorage, getStorageInfo: getStorageInfo, getSystemInfoSync: getSystemInfoSync, getSystemInfo: getSystemInfo, SDKVersion: SDKVersion, sendMtop: sendMtop }); /// <reference path="./types/windmill-renderer.d.ts" /> var runtime = index_min({}, { isWeex: false, exposeModuleGetter: true }); // expose runtime api setRuntime(runtime); function getAvailableAPIs(options) { var my = Object.assign({}, webviewAPIs, { canIUse: function (x) { return x in webviewAPIs; } }); if (options && options.preprocessor) { registerPreprocessor(my, options.preprocessor); } // 监听从 worker 发到 webview 页面的消息 runtime.$on(WEBVIEW_MESSAGE, function (message) { if ( message === void 0 ) message = {}; if (typeof my.onMessage === 'function') { my.onMessage(message.data); } }); return { my: my }; } var apis = getAvailableAPIs(); for (var key in apis) { setGlobalAPI(key, apis[key]); } return getAvailableAPIs; }());