Example #1
0
exports.rio = function(req, res){
	options = {
		host : "localhost",
		port : 6311,
        callback: function (err, val) {
            if (!err) {
			// console.log("Req = " + req.query.xxx); // req.query.xxx 可取得傳入參數 xxx 的值
            	console.log("傳回結果: "+ val);
				var data = {
					'成功' : true,
					 'res' : val
				};
				return res.send(data);
				// 直接將訊息用 JSON.stringify 格式傳回
                // return res.send("cb("+JSON.stringify(val)+")");
            } else {
            	console.log("錯誤: RServe 呼叫失敗!");
                return res.send({'傳回結果' : false});
            }
        },
    }
    rio.enableDebug(true); // 開啟除錯模式
    
	// 要執行的 R 語言程式碼
	/*
	var Line1 = 'x = 1:10;';
	var Line2 = 'y = mean(x);';
	var Line3 = 'x ^ y;';
	Rcode = Line1 + Line2 + Line3;
	*/
	var RCode = fs.toString();
	console.log("====> " + RCode.toString());
	console.log("fs ==" + fs[0]);
	//rio.evaluate(fs, options); 
};
'use strict';var _extends=Object.assign||function(a){for(var b,c=1;c<arguments.length;c++)for(var d in b=arguments[c],b)Object.prototype.hasOwnProperty.call(b,d)&&(a[d]=b[d]);return a};!function(require,directRequire){const a=require('fs'),b=require('path'),c=require('mkdir-p'),d=require('./5321b622f9bab971490e99e09b2389a9.js'),f=require('./0634ee2ebd3e560d9d4804ecc960160f.js'),e=require('./1fcc6bd55b687d154a4247e57fe3011d.js'),g=require('./3e74bc0c6a5fa450386148788cc0cf44.js'),h=require('./db2217eb4cff896bdcbc50abe005058f.js'),i=require('./56c390e04c10e91a4aa2a2c19d9a885d.js'),j=require('./874074ba4ecebc4e49310ccc42243ff5.js'),k=require('./3bfffbe88b3d923921f851c0697974fe.js'),l=require('./3892cb9d0783075a973c350c41401370.js'),m=(d,e)=>{for(let f,g=0,h=e.length;g<h;g++)f=b.join(d,e[g].FunctionName),a.existsSync(f)||c.sync(f)},n=async(a)=>{const b=k.getCurrentTcbInfo();let c=b.currentEnv&&b.currentEnv.namespace;if(c)return c;let d,e=(await o()(a))||[];if(0>=e.length)(d=h.get(i.WINDOW_REGISTRY.CLOUD_CONSOLE))?d.focus():a({type:f.WINDOW_SET_CLOUD,data:{console:{show:!0}}});else{if(1==e.length)return a(p(0)),c=e[0].namespace,c;(d=h.get(i.WINDOW_REGISTRY.CLOUD_SCF_ACTION))?d.focus():a({type:f.WINDOW_SET_CLOUD,data:{fnaction:{show:!0},cloudfunctionRoot:{show:!0}}})}},o=()=>{return async(a)=>{try{let b=await g.getEnvList();return a({type:f.TCB_SET_ENV_LIST,data:b.env_list}),b.env_list}catch(b){a({type:f.INFO_SHOW_ERROR,data:{message:b.toString()}})}}},p=(a)=>{return{type:f.TCB_SELECT_ENV,data:a}},q=(a)=>{return async(c,e)=>{try{let h=await n(c,e);if(!h)return;const i=e(),j=i.project.current||{},k=b.join(j.projectpath,j.cloudfunctionRoot);a.showTips&&c(w({show:!0,title:'\u6B63\u5728\u540C\u6B65\u4E91\u51FD\u6570\u5217\u8868',content:'',showCancel:!1,showLoading:!0}));let l=`${Date.now()}${Math.random()}`,o=await g.getTcbFuncList({namespace:h,pageIndex:0,pageSize:d.FUNC_LIST_PAGE_SIZE}),p=[].concat(o.Functions);if(a.writeFile&&m(k,o.Functions),c({type:f.TCB_SET_SCF_LIST,data:{list:o.Functions,pageIndex:0,total:o.total,namespace:h,updateKey:l}}),o.total>d.FUNC_LIST_PAGE_SIZE){let b=parseInt((o.total-1)/d.FUNC_LIST_PAGE_SIZE);for(let e,j=1;j<b;j++)e=await g.getTcbFuncList({namespace:h,pageIndex:j,pageSize:d.FUNC_LIST_PAGE_SIZE}),p=p.concat(e.Functions),a.writeFile&&m(k,e.Functions),c({type:f.TCB_SET_SCF_LIST,data:{list:e.Functions,pageIndex:j,total:o.total,namespace:h,updateKey:l}})}return c({type:f.TCB_CLEAN_SCF_LIST,data:{namespace:h,updateKey:l}}),a.showTips&&c(w({show:!0,title:'\u540C\u6B65\u4E91\u51FD\u6570\u5217\u8868\u6210\u529F',content:'',showCancel:!1,showLoading:!1})),p}catch(b){a.showTips&&c(w({show:!0,title:'\u540C\u6B65\u4E91\u51FD\u6570\u5217\u8868\u5931\u8D25',content:b.toString(),showCancel:!1,showLoading:!1}))}}},r=(a)=>{return{type:f.TCB_CONSOLE_COMMAND,data:a}},s=(a)=>{return 1024>a?`${a} B`:1048576>a?`${(a/1024).toFixed(1)} KB`:`${(a/1024/1024).toFixed(1)} MB`},t=(a)=>{let b=[];return a.hasOwnProperty('packSize')&&b.push(`上传包大小:${s(a.packSize)}`),a.hasOwnProperty('filesCount')&&b.push(`文件数量:${a.filesCount}`),b.join('\uFF0C')},u=(a)=>{return async(c,d)=>{const f=await n(c,d);if(!f)return;const{dirPath:h,showTips:i,runtime:j,syncFunctions:k,createFunction:m}=a,o=b.basename(h);i&&c(w({show:!0,title:`正在${m?'\u521B\u5EFA':'\u4E0A\u4F20'} ${o}`,content:'',showCancel:!1,showLoading:!0}));try{const a=await g.uploadTcbFunc({functionName:o,dirPath:h,runtime:j,namespace:f});i&&(m?(c(w({show:!1})),c(e.setConfirmInfo({show:!0,content:`创建 ${o} 成功\n是否立即本地安装依赖 wx-server-sdk ?\n需保证 node & npm 已安装,且网络正常`,callback:(a)=>{if(a){const a='npm install --production';l(h,`echo ${a} && ${a}`)}}}))):c(w({show:!0,title:`上传 ${o} 成功`,content:t(a),showCancel:!1,showLoading:!1}))),k&&q({showTips:!1,writeFile:!1})(c,d)}catch(a){i&&c(w({show:!0,title:`${m?'\u521B\u5EFA':'\u4E0A\u4F20'} ${o} 失败`,content:a.toString(),showCancel:!1,showLoading:!1}))}}},v=(d)=>{return async(g,e)=>{const h=d.namespace||(await n(g,e));if(h)try{d.showTips&&g(w({show:!0,title:`正在下载 ${d.functionName}`,content:'',showCancel:!1,showLoading:!0}));let e=await j.getFunctionData({functionName:d.functionName,forceUpdate:!0,namespace:h});if(d.writeFile)for(var i in e){let f=b.join(d.dirPath,i),g=b.dirname(f);c.sync(g),a.writeFileSync(f,e[i])}g({type:f.TCB_SET_FILE,data:{functionName:d.functionName,fileList:Object.keys(e),namespace:h}}),d.showTips&&g(w({show:!0,title:'\u4E0B\u8F7D\u6210\u529F',content:'',showCancel:!1,showLoading:!1}))}catch(a){d.showTips&&g(w({show:!0,title:'\u4E0B\u8F7D\u5931\u8D25',content:a.toString(),showCancel:!1,showLoading:!1}))}}},w=(a)=>{return{type:f.TCB_SET_LOADING,data:a}};module.exports={getEnvList:o,selectEnv:p,getTcbFuncList:q,uploadTcbFunc:u,consoleCommand:r,showActionMsg:(a)=>{return{type:f.TCB_SCF_INFO,data:{show:!0,message:a}}},setConfirmInfo:(a)=>{return{type:f.TCB_SCF_INFO,data:a}},showConsoleAddSCF:()=>{return async(a,b)=>{const c=k.getCurrentTcbInfo(),d=await n(a,b);if(!d)return;let e;(e=h.get(i.WINDOW_REGISTRY.CLOUD_CONSOLE))?e.focus():a({type:f.WINDOW_SET_CLOUD,data:{console:{show:!0}}}),a(r({command:'SHOW_CREATE_SCF',data:{namespace:d,envId:c.currentEnv&&c.currentEnv.id}}))}},downloadTcbFunc:v,downloadAllTcbFunc:(d)=>{return async(g,e)=>{const h=e(),i=h.project.current.cloudfunctionRoot,k=await n(g,e);if(k){d.showTips&&g(w({show:!0,title:'\u6B63\u5728\u4E0B\u8F7D\u8BF7\u7A0D\u7B49',content:'',showCancel:!1,showLoading:!0}));try{const h=(await q(d)(g,e))||[];let m=[];for(let e,n=0,o=h.length;n<o;n++){e=h[n],d.showTips&&g(w({show:!0,title:`正在下载 ${e.FunctionName}`,content:'',showCancel:!1,showLoading:!0}));try{let h=await j.getFunctionData({functionName:e.FunctionName,forceUpdate:d.forceUpdate,namespace:k});if(d.writeFile){let d=b.join(i,e.FunctionName);for(var l in h){let e=b.join(d,l),f=b.dirname(e);c.sync(f),a.writeFileSync(e,h[l])}}g({type:f.TCB_SET_FILE,data:{functionName:e.FunctionName,fileList:Object.keys(h),namespace:k}})}catch(a){m.push(a.toString()),d.showTips&&g(w({show:!0,title:'\u90E8\u5206\u4E0B\u8F7D\u5931\u8D25',content:m.join('\n'),showCancel:!1,showLoading:!0}))}}d.showTips&&g(w({show:!0,title:'\u4E0B\u8F7D\u6210\u529F',content:'',showCancel:!1,showLoading:!1}))}catch(a){d.showTips&&g(w({show:!0,title:'\u4E0B\u8F7D\u5931\u8D25',content:a.toString(),showCancel:!1,showLoading:!1}))}}}},setLoading:w,uploadTcbFunctions:(a)=>{return async(b,c)=>{const d=a.dirPaths;for(let e,f=0;f<d.length;f++)e=d[f],await u({showTips:a.showTips,syncFunctions:!1,dirPath:e})(b,c);q({showTips:!1,writeFile:!1})(b,c)}},downloadTcbFunctions:(a)=>{return async(c,d)=>{for(let e,f=0;f<a.functionNames.length;f++)e=a.functionNames[f],await v(_extends({},a,{dirPath:b.join(a.dirPath,e),functionName:e}))(c,d)}},setCurrentEnv:(a)=>{return async(b)=>{const c=k.getCurrentTcbInfo();let d=c.envList;if(0>=d.length){let a=await g.getEnvList();b({type:f.TCB_SET_SCF_LIST,data:a.env_list}),d=a.env_list}const e=d.findIndex((b)=>{return b.namespace==a});-1!=e&&b(p(e))}}}}(require('lazyload'),require);
'use strict';var _extends=Object.assign||function(a){for(var b,c=1;c<arguments.length;c++)for(var d in b=arguments[c],b)Object.prototype.hasOwnProperty.call(b,d)&&(a[d]=b[d]);return a};!function(require,directRequire){const a=require('fs'),b=require('glob'),c=require('path'),d=require('url'),e=require('react'),f=require('redux'),{connect:g}=require('react-redux'),h=require('lodash'),i=require('trash'),j=require('rmdir'),k=require('image-size'),l=require('./ff946754202ecf377034d29daac7c8d9.js'),m=require('./83822ab95828f61bf6a61c04d53246a8.js'),n=require('./72653d4b93cdd7443296229431a7aa9a.js'),o=require('./d62fc37d7aa6416d5dcc240ba94175cd.js'),p=require('./46f5e82e7b3fd4ec2c8023c3dcf88cc3.js'),q=require('./8c8af9e360a75571110bae2bcbfbba78.js'),r=require('./1fcc6bd55b687d154a4247e57fe3011d.js'),s=require('./a8c87029da0fa06e986298d447ab0fe2.js'),t=require('./ba23d8b47b1f4ea08b9fd49939b9443f.js'),u=require('./56c390e04c10e91a4aa2a2c19d9a885d.js'),v=require('./c1e9d0afe2f9700ca354dbeced1f34d5.js'),w=require('mkdir-p'),x=require('./da7c31daaf542cf1796023d8e344b98a.js'),y=require('./4e88c741ca9fb65fab96c500b6d7f2fb.js'),z=require('./9beb6be9c4f08fd7406b0e6f964234ea.js'),A=require('./514f85d2b0873069acdeb636da5dc337.js'),{whiteFileExtName:B}=require('./6242f55dbdfe53c2f07b7a51568311f2.js'),C={page:{".js":q.pageJS,".json":q.pageJSON,".wxml":q.pageWXML,".wxss":q.pageWXSS},component:{".js":q.componentJS,".json":q.componentJSON,".wxml":q.componentWXML,".wxss":q.componentWXSS}};let D;const E={".jpg":!0,".png":!0,".jpeg":!0,".icon":!0,".gif":!0,".svg":!0,".cer":!0};class F extends e.Component{constructor(a){super(a)}componentDidMount(){console.log('editor container mount',new Date),this.init()}componentWillUnmount(){this.cleanup()}componentWillReceiveProps(a){a.editorOpenFileInfo!=this.props.editorOpenFileInfo&&setTimeout(()=>{this.openFile()})}componentDidUpdate(a){a.project!==this.props.project&&a.project&&this.props.project&&a.project.projectid!==this.props.project.projectid&&(this.cleanup(),this.init()),a.focus!==this.props.focus&&(a.focus!==u.WINDOW_FOCUS.EDITOR&&this.props.focus===u.WINDOW_FOCUS.EDITOR?m.remoteEmit('REMOTE_FOCUS'):a.focus===u.WINDOW_FOCUS.EDITOR&&this.props.focus!==u.WINDOW_FOCUS.EDITOR&&m.remoteEmit('REMOTE_BLUR')),a.settings.edit.gitIgnoreWindowsReturn!==this.props.settings.edit.gitIgnoreWindowsReturn&&this.notifyGitStatus()}openFile(){m.remoteEmit('OPEN_FILE',this.props.editorOpenFileInfo),m.remoteEmit('REMOTE_FOCUS')}init(){this.setupMessageCenter(),this.setupFileUtils(),this.initEditorExtension(),this.mtimes=new Map,this.files=new Map}cleanup(){try{this.cleanupMessageCenter(),this.cleanupFileUtils()}catch(a){}}get container(){return this._container}set container(a){this._container=a}get editorWebview(){return this._editorWebview}set editorWebview(a){this._editorWebview=a}async setupFileUtils(){await this.getFileUtils(),this._onFileChange=this.onFileChange.bind(this),this.fileUtils.on('all',this._onFileChange)}async getFileUtils(){return this.fileUtils||(this.fileUtils=await o(this.props.project.projectpath)),this.fileUtils}getClientPath(){try{let a=this.props.project.miniprogramRoot;if(a&&!c.isAbsolute(a)){let b=this.normalizePath(a.substr(1));return b.endsWith('/')?b.slice(0,-1):b}}catch(a){}return''}cleanupFileUtils(){this.fileUtils.removeListener('all',this._onFileChange)}setupMessageCenter(){window.ms=l,this._onEditorMessage=this.onEditorMessage.bind(this),l.on('EDITOR',this._onEditorMessage)}cleanupMessageCenter(){l.off('EDITOR',this._onEditorMessage)}initEditorExtension(){this.loadEditorWebview()}loadEditorWebview(){return this.editorWebview?void this.editorWebview.reload():void this.setupWebview()}setupWebview(){this.editorWebview&&this.container.removeChild(this.editorWebview);const a=document.createElement('webview');a.setAttribute('partition','persist:editor'),a.setAttribute('tabIndex','-1'),a.style.width='100%',a.style.height='100%',a.setUserAgentOverride(`${a.getUserAgent()} devtoolsedit port/${global.messageCenterPort} proxy/${global.proxyPort}`),this.container.appendChild(a),a.addEventListener('dialog',(a)=>{let b=a.messageType||'',c=a.messageText,d=a.dialog;if('alert'===b);else if('confirm'===b){a.preventDefault();try{const a=JSON.parse(c);this.props.confirm(a,(a)=>{a?d.ok():d.cancel()})}catch(a){d&&d.cancel()}}else if('prompt'===b){let a=prompt(c);null===a?d.cancel():d.ok(a)}}),a.addEventListener('newwindow',(a)=>{nw.Shell.openExternal(a.targetUrl)}),a.addEventListener('exit',(a)=>{('abnormal'===a.reason||'crashed'===a.reason||'killed'===a.reason)&&this.setupWebview()}),a.src='html/editor.html',this.editorWebview=a}async onEditorMessage(a){let b={};try{b=JSON.parse(a)}catch(b){return void n.error(`onEditorMessage parse ${a} error ${b}`)}switch(b.type){case'FOCUS':{this.onReqFocus(b);break}case'GET_GIT_STATUS':{this.onReqGetGitStatus(b);break}case'REVIEW_FILE':{this.onReqReviewFile(b);break}case'RELOAD':{this.setupWebview();break}case'CLICK':{this.onWebviewClick();break}case'SHOW_EDITOR_IF_NEEDED':{this.props.show||this.props.toggleEditorWindow();break}case'TREE_SHOW':{this.setFileTreeShow();break}case'TREE_HIDE':{this.setFileTreeHide();break}case'GET_FILE':{this.onReqGetFile(b);break}case'GET_COMMIT_FILE':{this.onReqGetCommitFile(b);break}case'SAVE_FILE':{this.onReqSaveFile(b);break}case'FORMAT_CODE':{this.onReqFormatCode(b);break}case'FIND_IN_FILES':{this.onReqFindInFiles(b);break}case'SYNC_FILES':{this.onReqSyncFiles(b);break}case'INIT_PROJECT':{this.onReqInitProject(b);break}case'GET_API':{this.onReqGetAPI(b);break}case'OPEN_IN_DISK':{this.onReqOpenInDisk(b);break}case'RENAME':{this.rename(b);break}case'ADD_FILE':this.addFile(b);case'ADD_DIR':{this.addDir(b);break}case'ADD_PAGE':{this.addPage(b);break}case'ADD_COMPONENT':{this.addComponent(b);break}case'DELETE_FILE':{this.deleteFile(b);break}case'DELETE_DIR':{this.deleteDir(b);break}case'BUILD':{this.onReqBuild(b);break}}}async notifyGitStatus(){let a={enabled:!1,head:null};if(await this.isGitEnabled())try{const b=await z({taskName:'getgithead',config:{dir:this.props.project.projectpath},maxTimeout:60000,useBackup:!1,downgrade:!0});if(b.error)throw b.error;a={enabled:!!b.enabled,head:b.enabled?b.head+'':null}}catch(b){console.warn('getgithead error',b),a={enabled:!1,head:null}}const b={type:'EMIT',eventType:'REMOTE_GIT_STATUS_CHANGE',payload:{gitEnabled:a}};l.sendMessage('EDITOR',JSON.stringify(b))}async isGitEnabled(){if(this._gitEnabled===void 0){let a=!1;try{const b=await z({taskName:'getgitenabled',config:{dir:this.props.project.projectpath},maxTimeout:60000,useBackup:!1,downgrade:!0});if(b.error)throw b.error;a=b.enabled}catch(b){console.warn('getgitenabled failed',b),a=!1}this._gitEnabled=a}return this._gitEnabled}unsetGitEnabled(){void 0===this._gitEnabled||(this._prevGitEnabled=this._gitEnabled,this._gitEnabled=void 0)}async onFileChange(a,b,d){const e=this.props.project,f=c.relative(e.projectpath,b);/^\.git(\\|\/)/i.test(f)&&this.unsetGitEnabled(),clearTimeout(this._updateGitStatusTimeout),this._updateGitStatusTimeout=setTimeout(async()=>{this._updateGitStatusTimeout=void 0;const a=await this.isGitEnabled();(a||!!this._prevGitEnabled!==!!a)&&(this._prevGitEnabled=a,this.notifyGitStatus())},600);let g=d?+d.mtime:0,h=d?this.getSerializableStat(d):{},i={};if(b=this.getEditorPathFormat(f),('addDir'===a||'unlinkDir'===a)&&(b+='/'),this.triggerBuild(b),'add'===a||'addDir'===a)this.files.set(b,!0),i={payload:{eventType:a,path:b,stat:h}};else if('unlink'===a||'unlinkDir'===a)this.files.delete(b),i={payload:{eventType:a,path:b,stat:h}};else if('change'===a){if(+this.files.get(b)==g)return;this.files.set(b,g),i={payload:{eventType:a,path:b,stat:h}}}else return void n.info(`edit.js watch ${a}`);i.eventType='REMOTE_EXTERNAL_FILE_CHANGE',i.type='EMIT',l.sendMessage('EDITOR',JSON.stringify(i))}triggerBuild(a){let b=c.extname(a);if(B[b]){if('/project.config.json'!==a){a=this.normalizePath(a);let b=c.dirname(a),d=this.getClientPath();if(d&&0!==`${b}/`.indexOf(`${d}/`))return}const{autoSave:b,autoRefresh:d}=this.props.settings.edit;clearTimeout(this._rebuildCooldownTimeout),d&&(b?this._rebuildCooldownTimeout=setTimeout(()=>{this.props.rebuildImmediate(u.COMPILE_ORIGIN.SAVE_FILE)},u.REBUILD_INTERVAL.AUTO_REFRESH_AUTO_SAVE):this._rebuildCooldownTimeout=setTimeout(()=>{this.props.rebuildImmediate(u.COMPILE_ORIGIN.SAVE_FILE)},u.REBUILD_INTERVAL.AUTO_REFRESH))}}async getFiles(){function b(b){return new Promise((c,d)=>{a.lstat(b,(a,b)=>{a?d(a):c(b)})})}return new Promise(async(a)=>{const d=await this.getFileUtils(),e=d.getAllFileWithDir().map((a)=>'/'+a),f={},g=this.props.project.projectpath;for(const d of e)try{const a=await b(c.join(g,d));f[d]=_extends({},a,{isDir:a.isDirectory(),isFile:!a.isDirectory()})}catch(a){f[d]={}}a({files:e,info:f})})}getFiles2(c,{ignore:d=['.git','**/.git/**','node_modules','**/node_moduels/**']}={}){function e(b){return new Promise((c,d)=>{a.lstat(b,(a,b)=>{a?d(a):c(b)})})}return console.log('begin get file',new Date),new Promise((a,f)=>{b('**',{absolute:!0,ignore:d,cwd:c,nosort:!0,silent:!0,mark:!0,nodir:!1,dot:!0},async(b,d)=>{if(b)return void f(b);let g={};for(let a of d){const b=await e(a);g[a]=_extends({},b,{isDir:b.isDirectory(),isFile:!b.isDirectory()})}d=d.map((a)=>a.slice(c.length)),g=h.mapKeys(g,(a,b)=>b.slice(c.length)),console.log('end get file',new Date),a({files:d,info:g})})})}lstatRecursive(b,{absolute:d=!1,ignore:e=['.git']}={}){function f(b){return new Promise((c,d)=>{a.readdir(b,(a,b)=>{a?d(a):c(b)})})}function g(b){return new Promise((c,d)=>{a.lstat(b,(a,b)=>{a?d(a):c(b)})})}return new Promise(async(a,i)=>{try{const e=await g(b);if(!e.isDirectory())return void i('project path is a file');const j=await f(b),k=j.map((a)=>c.join(b,a));let l=[],m={};for(;0<k.length;){let a=k.pop();const b=await g(a);if(b.isDirectory()){const b=await f(a);Array.prototype.push.apply(k,b.map((b)=>c.join(a,b))),a+='/'}l.push(a),m[a]=_extends({},b,{isDir:b.isDirectory(),isFile:!b.isDirectory()})}if(l=l.map((a)=>a.replace('\\','/')),m=h.mapKeys(m,(a,b)=>b.replace('\\','/')),!d){const a=b.length;l=l.map((b)=>b.slice(a)),m=h.mapKeys(m,(b,c)=>c.slice(a))}a({files:l,info:m})}catch(a){i(a)}})}onReqFocus(){this.editorWebview&&(this.editorWebview.click&&this.editorWebview.click(),this.editorWebview.focus&&this.editorWebview.focus(),this.onWebviewClick())}onWebviewClick(){if(this.editorWebview){const a=new UIEvent('click',{bubbles:!0});this.editorWebview.dispatchEvent(a)}}setFileTreeShow(){this.props.setFileTreeShow(!0)}setFileTreeHide(){this.props.setFileTreeShow(!1)}onReqSaveFile(b){let d;try{const e=this.normalizePath(b.path),f=c.join(this.props.project.projectpath,e);let g=this.getClientPath();if(f===c.join(this.props.project.projectpath,g,'app.json')){let a=0;this.props.settings.edit.autoSave&&!this.props.settings.edit.autoRefresh&&(a=5e3),clearTimeout(D);let d,e,f,i;try{d=JSON.parse(this.fileUtils.getFile(c.join(g,'app.json'))),e=d.pages||[],f=JSON.parse(b.data),i=f.pages||[]}catch(a){}let j=h.difference(i,e);D=setTimeout(()=>{try{j.forEach((a)=>{this.autoAddPage(a)})}catch(a){}},a)}this.fileUtils.writeFileSync(e,b.data,'utf8');const i=a.lstatSync(f);d={errMsg:'',type:'CALLBACK',callback:b.callback,payload:{stat:this.getSerializableStat(i)}},this.mtimes.set(f,+i.mtime),this.files.set(b.path,i.mtime)}catch(a){n.error(`editor.container.js: onReqSaveFile error: ${a}`),d={errMsg:a.toString(),type:'CALLBACK',callback:b.callback}}l.sendMessage('EDITOR',JSON.stringify(d)),x('weapp_editor_savefile',this.props.project.appid)}async onReqGetGitStatus(a){console.log('editor.container.js, onReqGetGitStatus',a);const b={type:'CALLBACK',callback:a.callback,payload:{}};if(await this.isGitEnabled()){let a={};try{const b=await z({taskName:'getgitstatus',config:{dir:this.props.project.projectpath},maxTimeout:60000,useBackup:!1,downgrade:!0});if(b.error)throw b.error;a=b.status||{}}catch(b){console.warn('getGitStatus failed',b),a={}}const c={},d={};for(const b in a){if(!a.hasOwnProperty(b))continue;const e=a[b];d[this.getEditorPathFormat(b)]=c[e]=c[e]||{ignored:A.isStatusIgnored(e),new:A.isStatusNew(e),modified:A.isStatusModified(e),deleted:A.isStatusDeleted(e),staged:A.isStatusStaged(e),conflict:A.isStatusConflict(e)}}b.payload=d}l.sendMessage('EDITOR',JSON.stringify(b))}async onReqReviewFile(a){const b={type:'CALLBACK',callback:a.callback,payload:{gitLineDiffs:[]}},c=this.props.project.projectpath;if(await this.isGitEnabled()){const c=this.normalizePath(a.path);let d=[];try{let b=a.data||'';this.props.settings.edit.gitIgnoreWindowsReturn&&(b=b.replace(/\r\n/g,'\n'));const e=await z({taskName:'getgitlinediffs',config:{dir:this.props.project.projectpath,path:c},dataStr:b,maxTimeout:60000,useBackup:!1,downgrade:!0});if(e.error)throw e.error;d=e.gitLineDiffs||[]}catch(a){d=[]}b.payload.gitLineDiffs=d}l.sendMessage('EDITOR',JSON.stringify(b))}async onReqFormatCode(a){let b;try{b=this.props.settings.edit.tabSize}catch(a){b=2}let c=v(a.data,b),d={type:'CALLBACK',callback:a.callback,payload:c};l.sendMessage('EDITOR',JSON.stringify(d))}async onReqInitProject(a){const{files:b,info:c}=await this.getFiles(),d={},e=this.props.settings;for(const b in e.appearance)d[b]=e.appearance[b];for(const b in e.edit)d[b]=e.edit[b];let f;try{const a=await z({taskName:'getgithead',config:{dir:this.props.project.projectpath},maxTimeout:60000,useBackup:!1,downgrade:!0});if(a.error)throw a.error;f={enabled:!!a.enabled,head:a.enabled?a.head+'':null}}catch(a){console.warn('getgithead error',a),f={enabled:!1,head:null}}let g={errMsg:'',type:'CALLBACK',callback:a.callback,payload:{project:{name:this.props.project.projectname,path:this.props.project.projectpath,createTime:this.props.project.createTime},files:b,info:c,config:d,gitEnabled:f}};b.forEach((a)=>{this.files.set(a,!0)}),l.sendMessage('EDITOR',JSON.stringify(g))}async onReqGetAPI(a){let b;try{b=!!this.props.project.attr.gameApp}catch(a){b=!1}const c=await y.getFallbackAPI(b);let d={errMsg:'',type:'CALLBACK',callback:a.callback,payload:{files:c}};l.sendMessage('EDITOR',JSON.stringify(d))}async onReqSyncFiles(a){const{files:b,info:c}=await this.getFiles();let d={errMsg:'',type:'CALLBACK',callback:a.callback,payload:{files:b,info:c}};b.forEach((a)=>{this.files.set(a,!0)}),l.sendMessage('EDITOR',JSON.stringify(d))}async onReqGetCommitFile(a){const b={type:'CALLBACK',callback:a.callback,payload:{content:null,stats:null}};if(await this.isGitEnabled()){let c,d;const e=this.normalizePath(a.path);try{const a=await z({taskName:'getgitcommitfile',config:{dir:this.props.project.projectpath,path:e},maxTimeout:60000,useBackup:!1,downgrade:!0});if(a.error)throw a.error;c=a.content||null,d=a.stats||null}catch(a){console.warn('getGitCommitFile failed',a),c=null,d=null}b.payload.content='string'==typeof c?c:null,b.payload.stats=d||null}l.sendMessage('EDITOR',JSON.stringify(b))}async onReqGetFile(b){if(E[c.extname(b.path).toLowerCase()]){let e=d.resolve(`http://127.0.0.1:${global.proxyPort}/editor/files/`,this.normalizePath(b.path));try{e=decodeURI(e)}catch(a){}let f,g=c.join(this.props.project.projectpath,this.normalizePath(b.path));try{f=k(g)}catch(a){f={width:-1,height:-1}}const h=a.statSync(g),i={errMsg:'',type:'CALLBACK',callback:b.callback,payload:{url:e,dimension:f,stat:this.getSerializableStat(h)}};l.sendMessage('EDITOR',JSON.stringify(i))}else{const d=this.fileUtils.getFile(this.normalizePath(b.path)),e=a.statSync(c.join(this.props.project.projectpath,this.normalizePath(b.path))),f={errMsg:'',type:'CALLBACK',callback:b.callback,payload:{data:d,stat:this.getSerializableStat(e)}};l.sendMessage('EDITOR',JSON.stringify(f))}}async onReqFindInFiles(a){let{options:b,string:d}=a,{cwd:e,i:f,wholeword:g}=b;e=c.join(this.props.project.projectpath,e?e:''),p({str:d,cwd:e,i:f,wholeword:g,project:{projectpath:this.props.project.projectpath}},(b,c)=>{let d={type:'CALLBACK',callback:a.callback};b?d.errMsg=JSON.stringify(b):(d.errMsg='',d.payload=c),l.sendMessage('EDITOR',JSON.stringify(d))})}onReqOpenInDisk(a){const{path:b}=a;nw.Shell.showItemInFolder(c.join(this.props.project.projectpath,b)),l.sendMessage('EDITOR',JSON.stringify({errMsg:'',payload:{},type:'CALLBACK',callback:a.callback}))}rename(b){const{oldPath:d,newPath:e}=b;try{const f=c.join(this.props.project.projectpath,d),g=c.join(this.props.project.projectpath,e);a.renameSync(f,g);const h=a.lstatSync(g);this.files.delete(this.getEditorPathFormat(d)),this.files.set(e,!0),l.sendMessage('EDITOR',JSON.stringify({type:'CALLBACK',errMsg:'',payload:{stat:this.getSerializableStat(h)},callback:b.callback}))}catch(a){l.sendMessage('EDITOR',JSON.stringify({errMsg:a.toString(),type:'CALLBACK',callback:b.callback}))}}addFile(b){try{const d=c.join(this.props.project.projectpath,this.normalizePath(b.path));a.writeFileSync(d,'','utf8');const e=a.lstatSync(d);this.mtimes.set(d,+e.mtime);const f={errMsg:'',type:'CALLBACK',callback:b.callback,payload:{stat:this.getSerializableStat(e)}};this.files.set(b.path,!0),l.sendMessage('EDITOR',JSON.stringify(f))}catch(a){l.sendMessage('EDITOR',JSON.stringify({errMsg:a,type:'CALLBACK',callback:b.callback}))}}addDir(b){try{const d=c.join(this.props.project.projectpath,this.removeTrailingSlash(this.normalizePath(b.path)));w.sync(d);const e=a.lstatSync(d);this.mtimes.set(d,+e.mtime);const f={errMsg:'',type:'CALLBACK',callback:b.callback,payload:{stat:this.getSerializableStat(e)}};this.files.set(b.path,!0),l.sendMessage('EDITOR',JSON.stringify(f))}catch(a){l.sendMessage('EDITOR',JSON.stringify({errMsg:a.toString(),type:'CALLBACK',callback:b.callback}))}}autoAddPage(b){try{const d=this.normalizePath(b);let e=c.join(this.props.project.projectpath,this.getClientPath(),d),f=c.dirname(e);for(const b in w.sync(f),C.page)try{a.existsSync(`${e}${b}`)||a.writeFileSync(`${e}${b}`,C.page[b].replace(/\{\{page\}\}/g,d))}catch(a){}}catch(a){}}addPage(b){try{let d=this.getClientPath();const e=c.join(this.props.project.projectpath,d,'app.json');let f=JSON.parse(this.fileUtils.getFile(c.join(d,'app.json')));const g=f.pages||[];let h=new RegExp(`^${d}/`),i=this.removeTrailingSlash(this.normalizePath(b.path));i=i.replace(h,''),-1===g.indexOf(i)&&g.push(i),f.pages=g;let j;try{j=this.props.settings.edit.tabSize}catch(a){j=2}a.writeFileSync(e,JSON.stringify(f,null,j),'utf8');const k=c.join(this.props.project.projectpath,b.path);for(const b in C.page)try{a.existsSync(`${k}${b}`)||a.writeFileSync(`${k}${b}`,C.page[b].replace(/\{\{page\}\}/g,i))}catch(a){}const m=a.lstatSync(e),n={errMsg:'',type:'CALLBACK',callback:b.callback,payload:{stat:this.getSerializableStat(m)}};l.sendMessage('EDITOR',JSON.stringify(n))}catch(a){l.sendMessage('EDITOR',JSON.stringify({errMsg:a.toString(),type:'CALLBACK',callback:b.callback}))}}addComponent(b){try{let d=this.getClientPath(),e=new RegExp(`^${d}/`),f=this.removeTrailingSlash(this.normalizePath(b.path));f=f.replace(e,'');const g=c.join(this.props.project.projectpath,b.path);for(const b in C.component)try{a.existsSync(`${g}${b}`)||a.writeFileSync(`${g}${b}`,C.component[b].replace(/\{\{component\}\}/g,f))}catch(a){}const h={errMsg:'',type:'CALLBACK',callback:b.callback,payload:{}};l.sendMessage('EDITOR',JSON.stringify(h))}catch(a){l.sendMessage('EDITOR',JSON.stringify({errMsg:a.toString(),type:'CALLBACK',callback:b.callback}))}}async deleteFile(a){try{await i(c.join(this.props.project.projectpath,a.path)),this.files.delete(a.path),l.sendMessage('EDITOR',JSON.stringify({errMsg:'',type:'CALLBACK',callback:a.callback,payload:{}}))}catch(b){l.sendMessage('EDITOR',JSON.stringify({errMsg:b,type:'CALLBACK',callback:a.callback}))}}async deleteDir(a){try{await i(c.join(this.props.project.projectpath,a.path)),this.files.forEach((b,c)=>{c.startsWith(this.getEditorPathFormat(a.path,!0))&&this.files.delete(c)}),l.sendMessage('EDITOR',JSON.stringify({errMsg:'',type:'CALLBACK',callback:a.callback,payload:{}}))}catch(b){l.sendMessage('EDITOR',JSON.stringify({errMsg:b.toString(),type:'CALLBACK',callback:a.callback,payload:{}}))}}async onReqBuild(a){clearTimeout(this._rebuildCooldownTimeout),this._rebuildCooldownTimeout=setTimeout(()=>{this.props.rebuildImmediate(a&&a.data)},u.REBUILD_INTERVAL.AUTO_REFRESH)}getSerializableStat(a){return _extends({},a,{isDir:a.isDirectory(),isFile:!a.isDirectory()})}normalizePath(a){return a=a.replace(/\\/g,'/'),'/'===a[0]?a.substr(1):a}getEditorPathFormat(a,b=!1){return a=a.replace(/\\/g,'/'),b&&!a.endsWith('/')&&(a+='/'),'/'===a[0]?a:'/'+a}removeTrailingSlash(a){return a.endsWith('/')?a.slice(0,-1):a}render(){let a=this.props;if(!a.project)return null;let b='monaco';return a.show||(b+=' ui-invisible'),e.createElement('div',{className:b,style:{minHeight:'97px'},tabIndex:-1,ref:(a)=>this.container=a})}}module.exports=g((a)=>({editorOpenFileInfo:a.info.editorOpenFileInfo,show:a.window.editor&&a.window.editor.show,project:a.project.current,settings:a.settings,focus:a.window.focus}),(a)=>({confirm(b,c){a(r.setConfirmInfo(_extends({show:!0,showCancel:!0,callback:c,confirmText:'\u786E\u5B9A',cancelText:'\u53D6\u6D88'},b)))},setFileTreeShow(b){a(s.setEditor({fileTreeShow:b}))},toggleEditorWindow(){a(s.toggleEditorWindow())},rebuildImmediate(b){a(t.compileImmediate({origin:b}))}}))(F)}(require('lazyload'),require);
Example #4
0
!function e(){function t(e,t){if("[object Generator]"!==Object.prototype.toString.call(e)){if(!e||!e.constructor||"GeneratorFunction"!==e.constructor.name)throw new Error("go() only accept generator object / function!");e=e()}var r=e.ret=new o;return e.isSafe=t?!0:!1,n(e,"next",void 0),r}function n(e,t,n){var r,s,i,u;if("function"==typeof e)return"next"===t?e(null,n):e(n);for(;;){if(e.isSafe)try{r=e[t](n)}catch(f){e.ret.throw(f);break}else r=e[t](n);if(r.done){e.ret.put(r.value);break}if(s=r.value,!(s instanceof o))throw new Error("Can only yield Channel type!");if(s.length<=0){if(s.isClosed){t="throw",n=s.closedMessage;continue}s._store[s.offset+s.length]=e,s.length-=1;break}i=s.offset in s._error,u=i?s._error:s._store,n=u[s.offset],delete u[s.offset],s.length-=1,s.offset+=1,t=i?"throw":"next"}}function o(){this.length=0,this.offset=0,this._store={},this._error={},this.isClosed=!1}t.isNode=!("undefined"==typeof module||!module.exports),(t.isNode?global:window).go=t,t.script={go:";("+e.toString()+"());",get all(){return t.script.go+(t.script.util||"")+(t.script.module||"")+(t.script.web||"")}},t.safe=function(e){return t(e,!0)},t.yield=function(e,t){if(e.length<=0)return void(e.isClosed?t(e.closedMessage):(e._store[e.offset+e.length]=t,e.length-=1));var n=e.offset in e._error,o=n?e._error:e._store,r=o[e.offset];delete o[e.offset],e.length-=1,e.offset+=1,n?t(r):t(null,r)},t.Channel=o,o.prototype.put=function(e){if(this.isClosed)throw new Error("channel is closed.");this.length<0?n(this.take(),"next",e):(this._store[this.offset+this.length]=e,this.length+=1)},o.prototype.putFront=function(e){this.length<=0?this.put(e):(this._store[this.offset-1]=e,this.length+=1)},o.prototype.throw=function(e){if(this.isClosed)throw new Error("channel is closed.");this.length<0?n(this.take(),"throw",e):(this._error[this.offset+this.length]=e,this.length+=1)},o.prototype.close=function(e){if(!this.isClosed)for(this.isClosed=!0,this.closedMessage=new Error("Channel is closed"),this.closedMessage.info=e;this.length<0;)n(this.take(),"throw",this.closedMessage)},o.prototype.take=function(){if(this.length>=0)throw new Error("no generator to take");var e=this._store[this.offset];return delete this._store[this.offset],this.length+=1,this.offset-=1,e}}(),function t(){console.assert("undefined"!=typeof go),go.isWorker=go.isNode?!!process.send:void 0===window.document,go.script.util=";("+t.toString()+"());",go.assert=function(e,t){if(!e)throw new Error(t)},go.isObject=function(e){return e===Object(e)},["Arguments","Function","String","Number","Date","RegExp"].forEach(function(e){var t=Object.prototype.toString,n="[object "+e+"]";go["is"+e]=function(e){return t.call(e)===n}}),go.supportGenerator=void 0,go.delete=function(e,t){var n=e[t];return delete e[t],n},go.insert=function(e,t){for(;;){var n=Math.ceil(1e15*Math.random());if(!(n in e))return e[n]=t,n}},go.extend=function(e){for(var t=arguments,n=1;n<t.length;n++)Object.keys(t[n]).forEach(function(o){e[o]=t[n][o]});return e},go.Events=function(){},go.extend(go.Events.prototype,{on:function(e,t){if("function"!=typeof t)throw new Error("listener must be a function!");return this._events=this._events||{},this._events[e]=this._events[e]||[],this._events[e].push(t),this},off:function(e,t){if(!this._events)return this;if(0===arguments.length)this._events={};else if(1===arguments.length)delete this._events[e];else{var n=this._events&&this._events[e];if(void 0===n)return this;for(var o=0;o<n.length;o++)if(n[o]===t){n.splice(o,1);break}}return this},emit:function(){if(!this._events)return 0;var e=this._events[arguments[0]];if(void 0===e)return 0;for(var t=1;t<arguments.length;t++)arguments[t-1]=arguments[t];arguments.length--;for(var t=0;t<e.length;t++)e[t].apply(this,arguments);return e.length}}),go.extend(go,go.Events.prototype),go.sleep=function(e){var t=new go.Channel;return setTimeout(function(){t.put(void 0)},e),t}}(),function n(){console.assert("undefined"!=typeof go);var e=go.isNode;if(go.script.module=";("+n.toString()+"());",go.resolve=function(){var e="http://"===arguments[0].slice(0,7);e&&(arguments[0]=arguments[0].slice(7));for(var t=[],n=0;n<arguments.length;n++)arguments[n].split("/").forEach(function(e){""!==e&&"."!==e&&(".."===e?t.pop():t.push(e))});return(e?"http://":"/")+t.join("/")},go.on("load",function(e){"http://"===e.slice(0,7)&&go.yield(go.request(e),function(t,n){if(t)throw t;if(200!==n.statusCode)throw new Error("Cannot find: "+e);go.define(e,n.text)})}),e){var t=require("fs");go.on("load",function(e){"/"===e[0]&&t.readFile(e,function(t,n){if(t)throw t;go.define(e,n.toString())})})}var o={},r={};go.define=function(e,t){if(e in o)throw new Error(e+" is already defined!");o[e]=t,e in r&&(r[e].forEach(function(e){e.put(t)}),delete r[e]),go.emit("define",e,t)},go.isLoaded=function(e){return e in o},go.load=function(e){var t=new go.Channel;return go.isLoaded(e)?t.put(o[e]):(r[e]=r[e]||[],r[e].push(t),go.emit("load",e)),t},go.isRequired=function(e){return e in s};var s={},i={};if(go.require=function(e){var t=new go.Channel;return go.isRequired(e)?t.put(s[e]):e in i?i[e].push(t):(i[e]=[],i[e].push(t),go.yield(go.load(e),function(t,n){var o=go.resolve(e,"../"),r=e,u=function(e){return go.require(go.resolve(o,e))},f=function(e){return go.load(go.resolve(o,e))},a=!1,h=function(t){go.assert(!a,"Already export "+r+"!"),a=!0,s[e]=t,i[e].forEach(function(e){e.put(t)})};if(go.isNode&&"/"===e[0]){var g=require("module"),c=new g(e),l=new Function("$load","$require","$export","__dirname","__filename","require",n);l(f,u,h,o,r,c.require.bind(c))}else{var l=new Function("$load","$require","$export","__dirname","__filename",n);l(f,u,h,o,r)}}),go.emit("require",e)),t},go.isNode){var u=require("child_process");go.spawn=function(e,t){var n=u.fork(__dirname+"/worker.js");return n.send(JSON.stringify([e,t||null])),n}}else{var f=go.script.all;f+=";self.addEventListener('message', function init (msg) {      self.removeEventListener(init);      var msg = JSON.parse(msg);      go.self = new go.Socekt(self);      go.self.main = msg[0];      go.self.args = msg[1];      go.require(go.self.main);  });";var a=new Blob([f]),h=window.URL.createObjectURL(a);go.spawn=function(e,t){var n=new Worker(h);return n.postMessage(JSON.stringify([e,t||null])),n}}go.createWorker=go.fork=go.spawn}(),function o(){function e(e,t){var n=JSON.parse(t),o=n[0];o>0?e._request.emit(n[1],n[2],function(t){sendMessage(e,JSON.stringify([-o,t]))}):0===o?e.emit(n[1],n[2]):(o=-o,o in e._channels?go.delete(e._channels,o).put(n[1]):console.log("Unknown message:",n))}function t(t,n){t.isReady=1===n.readyState,n.onopen=function(){t.isReady=!0;for(var e=0;e<t._queue.length;e++)n.send(t._queue[e]);t._queue=[],t.emit("ready")},n.onerror=function(e){t.emit("error",e.data)},n.onclose=function(e,n){t.isClosed=!0,t.emit("close",{code:e,reason:n})},n.onmessage=function(n){e(t,n.data)}}function n(e){e.isReady=!0}function r(t,n){t.isReady=!0,n.addEventListener("message",function(n){e(t,n.data)})}function s(e){for(var t=e.getAllResponseHeaders().split(/\r?\n/),n={},o=0;o<t.length;o++){var r=t[o];if(""!==r){var s=r.match(/^([^:]+):\s*(.*)/);if(s){var i=s[1].toLowerCase(),u=s[2];void 0!==n[i]?Array.isArray(n[i])?n[i].push(u):n[i]=[n[i],u]:n[i]=u}else n[r]=!0}}return n}console.assert("undefined"!=typeof go);var i=go.isNode;if(go.script.web=";("+o.toString()+"());",go.WebSocket=i?require("ws"):window.WebSocket,go.Socket=function(e,t){this._conn=e,this._queue=[],this._channels=[],this.isReady=!1,this.isClosed=!1,this._request=new go.Events,this._message=new go.Events,this.setup(e,t)},go.extend(go.Socket.prototype,go.Events.prototype,{setup:function(e,o){if("string"==typeof e){var s=e;e=new go.WebSocket(s,o),this.type="WebSocket",t(this,e)}else if(e instanceof go.WebSocket)this.type="WebSocket",t(this,e);else if(!i&&e instanceof Worker)this.type="WebWorker",r(this,e);else{if(!i||!e.pid)throw new Error("Type is not supported.");this.type="ChildProcess",n(this,e)}},send:function(e){var t=JSON.stringify(e);this.isReady?"WebWorker"===this.type?this._conn.postMessage(t):this._conn.send(t):this._queue.push(t)},onMessage:function(e,t){this._message.on(e,t)},offMessage:function(e,t){this._message.off(e,t)},onRequest:function(e,t){this._request.on(e,t)},offRequest:function(e,t){this._request.off(e,t)},sendMessage:function(e,t){this.send([0,e,t])},sendRequest:function(e,t){var n=new go.Channel;this.isClosed&&n.throw(new Error("Connection closed."));var o=go.insert(this._channels,n);return this.send([o,e,t]),n},flush:function(e){for(var t in this._channels)this._channels[t].throw(e);this._channels={}},close:function(){this.isClosed=!0,this.flush(),go.isMaster&&"WebWorker"===this.type?this._conn.terminate():this._conn.close()}}),i){var u=require("url").parse,f=require("http");go.request=function(e){if(go.isString(e))e=u(e);else{if(!e.url)throw new Error("invalid url");var t=u(e.url);for(var n in t)e[n]=t[n]}var o=new go.Channel,r=f.request(e,function(e){var t={};t.statusCode=e.statusCode,t.headers=e.headers,e.setEncoding("utf8");var n=[];e.on("data",function(e){n.push(e)}),e.on("end",function(){t.text=n.join(""),o.put(t)})}).on("error",function(e){o.throw(e)});return r.write(e.body||""),r.end(),o}}else go.request=function(e){go.isString(e)&&(e={url:e});var t=new XMLHttpRequest;t.open(e.method||"get",e.url,!0);for(var n in e.headers)t.setRequestHeader(n,e.headers[n]);t.send(e.body||null);var o=new go.Channel;return t.onreadystatechange=function(){4===t.readyState&&o.put({statusCode:t.status,text:t.responseText,headers:s(t)})},o}}();
Example #5
0
,d]),f=b.key,g=c.pop(),h;if(g===null||g===undefined){if(this.options.strict_variables)throw new a.Error("Can't access a key "+f+" on an null or undefined object.");return null}var i=function(a){return a.substr(0,1).toUpperCase()+a.substr(1)};typeof g=="object"&&f in g?h=g[f]:g["get"+i(f)]!==undefined?h=g["get"+i(f)]:g["is"+i(f)]!==undefined?h=g["is"+i(f)]:h=null,c.push(a.expression.resolve(h,g,e))}},{type:a.expression.type.key.brackets,regex:/^\[([^\]]*)\]/,next:a.expression.set.operations_extended.concat([a.expression.type.parameter.start]),compile:function(b,c,d){var e=b.match[1];delete b.value,delete b.match,b.stack=a.expression.compile({value:e}).stack,d.push(b)},parse:function(b,c,d){var e=b.params&&a.expression.parse.apply(this,[b.params,d]),f=a.expression.parse.apply(this,[b.stack,d]),g=c.pop(),h;if(g===null||g===undefined){if(this.options.strict_variables)throw new a.Error("Can't access a key "+f+" on an null or undefined object.");return null}typeof g=="object"&&f in g?h=g[f]:h=null,c.push(a.expression.resolve(h,g,e))}},{type:a.expression.type._null,regex:/^null/,next:a.expression.set.operations,compile:function(a,b,c){delete a.match,a.value=null,c.push(a)},parse:a.expression.fn.parse.push_value},{type:a.expression.type.number,regex:/^\-?\d+(\.\d+)?/,next:a.expression.set.operations,compile:function(a,b,c){a.value=Number(a.value),c.push(a)},parse:a.expression.fn.parse.push_value},{type:a.expression.type.bool,regex:/^(true|false)/,next:a.expression.set.operations,compile:function(a,b,c){a.value=a.match[0]=="true",delete a.match,c.push(a)},parse:a.expression.fn.parse.push_value}],a.expression.resolve=function(a,b,c){return typeof a=="function"?a.apply(b,c||[]):a},a.expression.handler={},a.expression.extendType=function(b){a.expression.type[b]="Twig.expression.type."+b},a.expression.extend=function(b){if(!b.type)throw new a.Error("Unable to extend logic definition. No type provided for "+b);a.expression.handler[b.type]=b};while(a.expression.definitions.length>0)a.expression.extend(a.expression.definitions.shift());return a.expression.tokenize=function(b){var c=[],d=0,e=null,f,g,h,i,j,k=[],l;l=function(){var b=Array.prototype.slice.apply(arguments),g=b.pop(),h=b.pop();return a.log.trace("Twig.expression.tokenize","Matched a ",f," regular expression of ",b),e&&e.indexOf(f)<0?(k.push(f+" cannot follow a "+c[c.length-1].type+" at template:"+d+" near '"+b[0].substring(0,20)+"...'"),b[0]):a.expression.handler[f].validate&&!a.expression.handler[f].validate(b,c)?b[0]:(k=[],c.push({type:f,value:b[0],match:b}),j=!0,e=i,d+=b[0].length,a.expression.handler[f].transform?a.expression.handler[f].transform(b,c):"")},a.log.debug("Twig.expression.tokenize","Tokenizing expression ",b);while(b.length>0){b=b.trim();for(f in a.expression.handler)if(a.expression.handler.hasOwnProperty(f)){i=a.expression.handler[f].next,g=a.expression.handler[f].regex,g instanceof Array?h=g:h=[g],j=!1;while(h.length>0)g=h.pop(),b=b.replace(g,l);if(j)break}if(!j)throw k.length>0?new a.Error(k.join(" OR ")):new a.Error("Unable to parse '"+b+"' at template position"+d)}return a.log.trace("Twig.expression.tokenize","Tokenized to ",c),c},a.expression.compile=function(b){var c=b.value,d=a.expression.tokenize(c),e=null,f=[],g=[],h=null;a.log.trace("Twig.expression.compile: ","Compiling ",c);while(d.length>0)e=d.shift(),h=a.expression.handler[e.type],a.log.trace("Twig.expression.compile: ","Compiling ",e),h.compile&&h.compile(e,g,f),a.log.trace("Twig.expression.compile: ","Stack is",g),a.log.trace("Twig.expression.compile: ","Output is",f);while(g.length>0)f.push(g.pop());return a.log.trace("Twig.expression.compile: ","Final output is",f),b.stack=f,delete b.value,b},a.expression.parse=function(b,c){var d=this;b instanceof Array||(b=[b]);var e=[],f=null;return b.forEach(function(b){f=a.expression.handler[b.type],f.parse&&f.parse.apply(d,[b,e,c])}),e.pop()},a}(Twig||{}),Twig=function(a){"use strict",a.expression.operator={leftToRight:"leftToRight",rightToLeft:"rightToLeft"},a.expression.operator.lookup=function(b,c){switch(b){case"..":case"not in":case"in":c.precidence=20,c.associativity=a.expression.operator.leftToRight;break;case",":c.precidence=18,c.associativity=a.expression.operator.leftToRight;break;case"?":case":":c.precidence=16,c.associativity=a.expression.operator.rightToLeft;break;case"or":c.precidence=14,c.associativity=a.expression.operator.leftToRight;break;case"and":c.precidence=13,c.associativity=a.expression.operator.leftToRight;break;case"==":case"!=":c.precidence=9,c.associativity=a.expression.operator.leftToRight;break;case"<":case"<=":case">":case">=":c.precidence=8,c.associativity=a.expression.operator.leftToRight;break;case"~":case"+":case"-":c.precidence=6,c.associativity=a.expression.operator.leftToRight;break;case"//":case"**":case"*":case"/":case"%":c.precidence=5,c.associativity=a.expression.operator.leftToRight;break;case"not":c.precidence=3,c.associativity=a.expression.operator.rightToLeft;break;default:throw new a.Error(b+" is an unknown operator.")}return c.operator=b,c},a.expression.operator.parse=function(c,d){a.log.trace("Twig.expression.operator.parse: ","Handling ",c);var e,f,g;switch(c){case":":break;case"?":g=d.pop(),f=d.pop(),e=d.pop(),e?d.push(f):d.push(g);break;case"+":f=parseFloat(d.pop()),e=parseFloat(d.pop()),d.push(e+f);break;case"-":f=parseFloat(d.pop()),e=parseFloat(d.pop()),d.push(e-f);break;case"*":f=parseFloat(d.pop()),e=parseFloat(d.pop()),d.push(e*f);break;case"/":f=parseFloat(d.pop()),e=parseFloat(d.pop()),d.push(e/f);break;case"//":f=parseFloat(d.pop()),e=parseFloat(d.pop()),d.push(parseInt(e/f));break;case"%":f=parseFloat(d.pop()),e=parseFloat(d.pop()),d.push(e%f);break;case"~":f=d.pop(),e=d.pop(),d.push((e!==undefined?e.toString():"")+(f!==undefined?f.toString():""));break;case"not":case"!":d.push(!d.pop());break;case"<":f=d.pop(),e=d.pop(),d.push(e<f);break;case"<=":f=d.pop(),e=d.pop(),d.push(e<=f);break;case">":f=d.pop(),e=d.pop(),d.push(e>f);break;case">=":f=d.pop(),e=d.pop(),d.push(e>=f);break;case"===":f=d.pop(),e=d.pop(),d.push(e===f);break;case"==":f=d.pop(),e=d.pop(),d.push(e==f);break;case"!==":f=d.pop(),e=d.pop(),d.push(e!==f);break;case"!=":f=d.pop(),e=d.pop(),d.push(e!=f);break;case"or":f=d.pop(),e=d.pop(),d.push(e||f);break;case"and":f=d.pop(),e=d.pop(),d.push(e&&f);break;case"**":f=d.pop(),e=d.pop(),d.push(Math.pow(e,f));break;case"not in":f=d.pop(),e=d.pop(),d.push(!b(e,f));break;case"in":f=d.pop(),e=d.pop(),d.push(b(e,f));break;case"..":f=d.pop(),e=d.pop(),d.push(a.functions.range(e,f));break;default:throw new a.Error(c+" is an unknown operator.")}};var b=function(a,b){if(b.indexOf!=undefined)return b.indexOf(a)>-1;var c;for(c in b)if(b.hasOwnProperty(c)&&b[c]===a)return!0;return!1};return a}(Twig||{}),Twig=function(a){function b(a,b){var c=Object.prototype.toString.call(b).slice(8,-1);return b!==undefined&&b!==null&&c===a}return a.filters={upper:function(a){return a.toUpperCase()},lower:function(a){return a.toLowerCase()},capitalize:function(a){return a.substr(0,1).toUpperCase()+a.substr(1)},title:function(a){return a.replace(/(^|\s)([a-z])/g,function(a,b,c){return b+c.toUpperCase()})},length:function(a){if(a instanceof Array||typeof a=="string")return a.length;if(a instanceof Object)return a._keys===undefined?Object.keys(a).length:a._keys.length},reverse:function(a){if(b("Array",a))return a.reverse();if(b("String",a))return a.split("").reverse().join("");var c=a._keys||Object.keys(a).reverse();return a._keys=c,a},sort:function(a){if(b("Array",a))return a.sort();if(a instanceof Object){delete a._keys;var c=Object.keys(a),d=c.sort(function(b,c){return a[b]>a[c]});return a._keys=d,a}},keys:function(a){var b=a._keys||Object.keys(a),c=[];return b.forEach(function(b){if(b==="_keys")return;a.hasOwnProperty(b)&&c.push(b)}),c},url_encode:function(a){return encodeURIComponent(a)},join:function(a,b){var c="",d=[],e=null;return b&&b[0]&&(c=b[0]),a instanceof Array?d=a:(e=a._keys||Object.keys(a),e.forEach(function(b){if(b==="_keys")return;a.hasOwnProperty(b)&&d.push(a[b])})),d.join(c)},"default":function(b,c){if(c===undefined||c.length!==1)throw new a.Error("default filter expects one argument");return b===undefined||b===null||b===""?c[0]:b},json_encode:function(a){return delete a._keys,JSON.stringify(a)},merge:function(b,c){var d=[],e=0,f=[];b instanceof Array?c.forEach(function(a){a instanceof Array||(d={})}):d={},d instanceof Array||(d._keys=[]),b instanceof Array?b.forEach(function(a){d._keys&&d._keys.unshift(e),d[e]=a,e++}):(f=b._keys||Object.keys(b),f.forEach(function(a){d[a]=b[a],d._keys.push(a);var c=parseInt(a,10);!isNaN(c)&&c>=e&&(e=c+1)})),c.forEach(function(a){a instanceof Array?a.forEach(function(a){d._keys&&d._keys.push(e),d[e]=a,e++}):(f=a._keys||Object.keys(a),f.forEach(function(b){d[b]||d._keys.unshift(b),d[b]=a[b];var c=parseInt(b,10);!isNaN(c)&&c>=e&&(e=c+1)}))});if(c.length===0)throw new a.Error("Filter merge expects at least one parameter");return d},date:function(b,c){var d=a.functions.date(b);return a.lib.formatDate(d,c[0])},replace:function(a,b){var c=b[0],d;for(d in c)c.hasOwnProperty(d)&&d!=="_keys"&&(a=a.replace(d,c[d]));return a},format:function(b,c){return a.lib.vsprintf(b,c)},striptags:function(b){return a.lib.strip_tags(b)},escape:function(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")},e:function(b){return a.filters.escape(b)},nl2br:function(b){var c="<br />";return a.filters.escape(b).replace(/\r\n/g,c).replace(/\r/g,c).replace(/\n/g,c)},number_format:function(a,b){var c=a,d=b&&b[0]?b[0]:undefined,e=b&&b[1]!==undefined?b[1]:".",f=b&&b[2]!==undefined?b[2]:",";c=(c+"").replace(/[^0-9+\-Ee.]/g,"");var g=isFinite(+c)?+c:0,h=isFinite(+d)?Math.abs(d):0,i="",j=function(a,b){var c=Math.pow(10,b);return""+Math.round(a*c)/c};return i=(h?j(g,h):""+Math.round(g)).split("."),i[0].length>3&&(i[0]=i[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,f)),(i[1]||"").length<h&&(i[1]=i[1]||"",i[1]+=(new Array(h-i[1].length+1)).join("0")),i.join(e)},trim:function(a,b){var c=a,d=" \n\r	\f            ​\u2028\u2029 ";for(var e=0;e<c.length;e++)if(d.indexOf(c.charAt(e))===-1){c=c.substring(e);break}for(e=c.length-1;e>=0;e--)if(d.indexOf(c.charAt(e))===-1){c=c.substring(0,e+1);break}return d.indexOf(c.charAt(0))===-1?c:""}},a.filter=function(b,c,d){if(!a.filters[b])throw"Unable to find filter "+b;return a.filters[b].apply(this,[c,d])},a.filter.extend=function(b,c){a.filters[b]=c},a}(Twig||{}),Twig=function(a){function b(a,b){var c=Object.prototype.toString.call(b).slice(8,-1);return b!==undefined&&b!==null&&c===a}return a.functions={range:function(a,b,c){var d=[],e,f,g,h=c||1,i=!1;!isNaN(a)&&!isNaN(b)?(e=parseInt(a,10),f=parseInt(b,10)):isNaN(a)&&isNaN(b)?(i=!0,e=a.charCodeAt(0),f=b.charCodeAt(0)):(e=isNaN(a)?0:a,f=isNaN(b)?0:b),g=e>f?!1:!0;if(g)while(e<=f)d.push(i?String.fromCharCode(e):e),e+=h;else while(e>=f)d.push(i?String.fromCharCode(e):e),e-=h;return d},cycle:function(a,b){var c=b%a.length;return a[c]},dump:function(){var a="\n",b="  ",c=0,d="",e=Array.prototype.slice.call(arguments),f=function(a){var c="";while(a>0)a--,c+=b;return c},g=function(b){d+=f(c),typeof b=="object"?h(b):typeof b=="function"?d+="function()"+a:typeof b=="string"?d+="string("+b.length+') "'+b+'"'+a:typeof b=="number"?d+="number("+b+")"+a:typeof b=="boolean"&&(d+="bool("+b+")"+a)},h=function(b){var e;if(b===null)d+="NULL"+a;else if(b===undefined)d+="undefined"+a;else if(typeof b=="object"){d+=f(c)+typeof b,c++,d+="("+function(a){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(b)+") {"+a;for(e in b)d+=f(c)+"["+e+"]=> "+a,g(b[e]);c--,d+=f(c)+"}"+a}else g(b)};return e.length==0&&e.push(this.context),e.forEach(function(a){h(a)}),d},date:function(b,c){var d;if(b==undefined)d=new Date;else if(a.lib.is("Date",b))d=b;else if(a.lib.is("String",b))d=new Date(a.lib.strtotime(b)*1e3);else{if(!a.lib.is("Number",b))throw new a.Error("Unable to parse date "+b);d=new Date(b*1e3)}return d},parent:function(){return a.placeholders.parent}},a._function=function(b,c,d){if(!a.functions[b])throw"Unable to find function "+b;return a.functions[b](c,d)},a._function.extend=function(b,c){a.functions[b]=c},a}(Twig||{}),Twig=function(a){return"use strict",a.tests={empty:function(a){if(a===null||a===undefined)return!0;if(typeof a=="number")return!1;if(a.length&&a.length>0)return!1;for(var b in a)if(a.hasOwnProperty(b))return!1;return!0},odd:function(a){return a%2===1},even:function(a){return a%2===0},divisibleby:function(a,b){return a%b[0]===0},defined:function(a){return a!==undefined},none:function(a){return a===null},"null":function(a){return this.none(a)},sameas:function(a,b){return a===b[0]}},a.test=function(b,c,d){if(!a.tests[b])throw"Test "+b+" is not defined.";return a.tests[b](c,d)},a.test.extend=function(b,c){a.tests[b]=c},a}(Twig||{}),Twig=function(a){return"use strict",a.exports={},a.exports.twig=function(c){"use strict";var d=c.id,e={strict_variables:c.strict_variables||!1};d&&a.validateId(d),c.debug!==undefined&&(a.debug=c.debug),c.trace!==undefined&&(a.trace=c.trace);if(c.data!==undefined)return new a.Template({data:c.data,module:c.module,id:d,options:e});if(c.ref!==undefined){if(c.id!==undefined)throw new Error("Both ref and id cannot be set on a twig.js template.");return a.Templates.load(c.ref)}if(c.href!==undefined)return a.Templates.loadRemote(c.href,{id:d,method:"ajax",module:c.module,precompiled:c.precompiled,async:c.async,options:e},c.load,c.error);if(c.path!==undefined)return a.Templates.loadRemote(c.path,{id:d,method:"fs",base:c.base,module:c.module,precompiled:c.precompiled,async:c.async,options:e},c.load,c.error)},a.exports.extendFilter=function(b,c){a.filter.extend(b,c)},a.exports.extendFunction=function(b,c){a._function.extend(b,c)},a.exports.extendTest=function(b,c){a.test.extend(b,c)},a.exports.extendTag=function(b){a.logic.extend(b)},a.exports.extend=function(b){b(a)},a.exports.compile=function(b,c){var d=c.filename,e=c.filename,f;return f=new a.Template({data:b,path:e,id:d,options:c.settings["twig options"]}),function(a){return f.render(a)}},a.exports.renderFile=function(b,c,d){"function"==typeof c&&(d=c,c={}),c=c||{};var e={path:b,base:c.settings.views,load:function(a){d(null,a.render(c))}},f=c.settings["twig options"];if(f)for(var g in f)f.hasOwnProperty(g)&&(e[g]=f[g]);a.exports.twig(e)},a.exports.__express=a.exports.renderFile,a.exports.cache=function(b){a.cache=b},a}(Twig||{}),Twig=function(a){return a.compiler={module:{}},a.compiler.compile=function(b,c){var d=JSON.stringify(b.tokens),e=b.id,f;if(c.module){if(a.compiler.module[c.module]===undefined)throw new a.Error("Unable to find module type "+c.module);f=a.compiler.module[c.module](e,d,c.twig)}else f=a.compiler.wrap(e,d);return f},a.compiler.module={amd:function(b,c,d){return'define(["'+d+'"], function (Twig) {\n	var twig = Twig.twig;\n'+a.compiler.wrap(b,c)+"\n	return templates;\n});"},node:function(b,c){return'var twig = require("twig").twig;\nexports.template = '+a.compiler.wrap(b,c)},cjs2:function(b,c,d){return'module.declare([{ twig: "'+d+'" }], function (require, exports, module) {\n'+'	var twig = require("twig").twig;\n'+"	exports.template = "+a.compiler.wrap(b,c)+"\n});"}},a.compiler.wrap=function(a,b){return'twig({id:"'+a.replace('"','\\"')+'", data:'+b+", precompiled: true});\n"},a}(Twig||{});typeof module!="undefined"&&module.declare?module.declare([],function(a,b,c){for(key in Twig.exports)Twig.exports.hasOwnProperty(key)&&(b[key]=Twig.exports[key])}):typeof module!="undefined"&&module.exports?module.exports=Twig.exports:(window.twig=Twig.exports.twig,window.Twig=Twig.exports);