UNPKG

lite

Version:

A cross platform template engine base on xml/html and javascript expression.

2,065 lines (1,929 loc) 390 kB
~function(){ var impls = arguments; var idIndex = [].pop.call(impls); var cached = {}; var previous_require = this.require; function internal_require(i){ if(typeof i=='number'){ var module = cached[i]; if(!module){ var id = "./"+i; module = cached[i] = {exports:{},id:id}; impls[i](module.exports,internal_require,module,id); } return module.exports; }else{ return require(i) ; } } function external_require(path){ var id = typeof path == 'number'?path:idIndex.indexOf(path); if(id>=0){ return internal_require(id); }else{ return external_require; } } if(previous_require && previous_require.backup){ previous_require.backup.push(external_require) }else{ this.require = function(pc){ if(pc instanceof Function){ var list = arguments; var i = list.length; var o = {}; while(--i){ copy(require(list[i]),o); } pc(o); return o; }else{ var list = require.backup; var i = list.length; while(i--){ var exports = list[i](pc); if(exports != list[i]){ return exports } } return previous_require?previous_require.apply(this,arguments):{} } } this.require.backup = [external_require]; } function copy(src,dest){ for(var n in src){ dest[n] = src[n]; } } copy(internal_require(0),this); }(function(exports,require){ var ResultContext=require(6).ResultContext; var URI=require(7).URI; var defaultBase = new URI("lite:///"); var loadLiteXML=require(8).loadLiteXML; var buildTopChain=require(9).buildTopChain; var ExtensionParser=require(10).ExtensionParser; var Extension=require(11).Extension; var parseDefaultXMLNode=require(12).parseDefaultXMLNode; var parseText=require(13).parseText; var XA_TYPE=require(14).XA_TYPE; var EL_TYPE=require(14).EL_TYPE; var XT_TYPE=require(14).XT_TYPE; var ParseConfig=require(15).ParseConfig; exports.ParseContext=ParseContext; function ParseContext(config,path){ config = config || new ParseConfig(); this.config = config; this.currentURI = defaultBase; this.configMap = config.getConfig(path); this.textType=0; this._path = path; this._attributeMap = [[],[],{}] this._result = new ResultContext(); this._context = this; this._result._context = this; this._resources = []; initializeParser(this,config.getExtensionMap(path)); } function initializeParser(context,extensionMap){ var extensionParser = new ExtensionParser(); for(var ns in extensionMap){ var exts = extensionMap[ns]; for(var len = exts.length,i=0;i<len;i++){ extensionParser.addExtension(ns,exts[i]) } } context._nodeParsers = [parseTextLeaf,parseDefaultXMLNode,parseExtension]; context._textParsers = [extensionParser]; context._extensionParser = extensionParser; context._topChain = buildTopChain(context); } function parseExtension(node,context,chain){ return context._extensionParser.parse(node,context,chain); } function parseTextLeaf(text,context){ if(typeof text == 'string'){ return parseText(text,context,context._textParsers) }else{ console.error("未知节点类型",typeof text,text) } } ParseContext.prototype = { parseText:function(source, textType) { switch(textType){ case XA_TYPE : case XT_TYPE : case EL_TYPE : break; default: console.error("未知编码模式:"+textType) throw new Error(); } var mark = this.mark(); var oldType = this.textType; this._context.textType = textType; parseTextLeaf(source,this); this._context.textType = oldType; var result = this.reset(mark); return result; }, parse:function(source) { var type = source.nodeType; if(type>0){ this._topChain.next(source); }else{ if(source instanceof URI){ var oldURI = this.currentURI; this.setCurrentURI(source); source = this.loadXML(source); if(typeof source == 'string'){ source=source.replace(/#.*[\r\n]*/,''); } } if(typeof source != 'string'){ var len = source.length; var nodeType = source.nodeType; if(nodeType === undefined && typeof source.item != 'undefined'){ if(len === 0){ return; } for(var i = 0;i<len;i++){ this._topChain.next(source.item(i)); } return; } } this._topChain.next(source); if(oldURI) this.setCurrentURI(oldURI) } }, createURI:function(path) { var base = this.config.root.toString(); if(!path){return path} path = String(path); if(path.indexOf(base) ==0){ path = path.substring(base.length-1); } var cu = this.currentURI; if(cu){ return cu.resolve(path); }else{ path= path.replace(/^[\\\/]/,'./'); return defaultBase.resolve(path); } }, loadText:function(uri){ if(uri.scheme == 'lite'){ var path = uri.path+(uri.query||''); path = path.replace(/^\//,'./') uri = this.config.root.resolve(path); } if(uri.scheme == 'file'){ var fs = require(4); var path = uri.path; if(fs.existsSync(path)){ return fs.readFileSync(path).toString() } }else{ var xhr = new XMLHttpRequest(); xhr.open("GET",uri,false) xhr.send(''); return xhr.responseText; } }, loadXML:function(path){ var t1 = +new Date(); if(path instanceof URI){ }else{ if(/^\s*</.test(path)){ doc = loadLiteXML(path,this.config.root) }else{ path = new URI(path) } } if(path instanceof URI){ var doc = loadLiteXML(path,this.config.root); this._context._loadTime+=(new Date()-t1); } var root = doc && doc.documentElement; if(root){ root.setAttribute('xmlns:xhtml',"http://www.w3.org/1999/xhtml") root.setAttribute('xmlns:c',"http://www.xidea.org/lite/core") } return doc; }, setAttribute:function(key,value){ _setByKey(this._context._attributeMap,key,value) }, getAttribute:function(key){ return _getByKey(this._context._attributeMap,key) }, addNodeParser:function(np){ this._nodeParsers.push(np); }, addTextParser:function(tp){ this._textParsers.push(tp); }, addExtension:function(ns,pkg){ this._extensionParser.addExtension(ns,pkg); }, getConfig:function(key){ return this.configMap[key]; }, getConfigMap:function(){ return this.configMap; }, setCurrentURI:function(uri){ this._context.addResource(uri=new URI(uri)); this._context.currentURI = uri; }, addResource:function(uri){ for(var rs = this._resources, i=0;i<rs.length;i++){ if(rs[i]+'' == uri){ return ; } } this._resources.push(uri); }, getResources:function(){ return this._resources; }, createNew:function(){ var nc = new ParseContext(this.config,this.currentURI); nc.config = this.config; nc.configMap = this.configMap; nc._resources = this._resources; return nc; }, _loadTime :0 } var rm = ResultContext.prototype; for(var n in rm){ if(rm[n] instanceof Function){ ParseContext.prototype[n] = buildResultWrapper(n); } } function buildResultWrapper(n){ return function(){ var result = this._result; return result[n].apply(result,arguments) } } function _getByKey(map,key){ if(typeof key == 'string'){ map = map[2]; return key in map ? map[key]:null; } var keys = map[0]; var values = map[1]; var i = keys.length; while(i--){ if(key === keys[i]){ return values[i]; } } } function _setByKey(map,key,value){ if(typeof key == 'string'){ map[2][key] = value; }else{ var keys = map[0]; var values = map[1]; var i = keys.length; while(i--){ if(key === keys[i]){ values[i] = value; if(value === undefined){ values.splice(i,1) keys.splice(i,1) } return; } } keys.push(key); values.push(value); } } } , function(exports,require){ var ELSE_TYPE=require(14).ELSE_TYPE; var TranslateContext=require(16).TranslateContext; var Expression=require(17).Expression; var GLOBAL_DEF_MAP ={ "parseInt":1, "parseFloat":1, "encodeURIComponent":1, "decodeURIComponent":1, "encodeURI":1, "decodeURI":1, "isFinite":1, "isNaN":1 }; var GLOBAL_VAR_MAP ={ "JSON":1, "Math":1 } copy(GLOBAL_DEF_MAP,GLOBAL_VAR_MAP); function JSTranslator(config){ this.config = config||{}; } JSTranslator.prototype = { translate:function(list,config){ config = config||{}; var params = config.params; var functionName = config.name; var ctx = new JSTranslateContext(list,functionName,params,config.defaults); var translatorConfig = this.config || {}; var liteImpl = translatorConfig.liteImpl ctx.waitPromise = translatorConfig.waitPromise && [[]]; ctx.hasBuildIn = !!liteImpl; ctx.liteImpl = liteImpl && (typeof liteImpl == 'string'?liteImpl:'liteImpl'); ctx.parse(); var code = genSource(ctx); try{ var fn = new Function('return '+code); var scope = ctx.scope; var refMap = scope.refMap; var varMap = scope.varMap; var externalRefs = Object.keys(refMap).filter(function(n){return !(n in varMap)}) if(externalRefs == 0 && params){ return 'function '+(functionName||'')+'(){return '+JSON.stringify(fn()()) + '}' } }catch(e){ var error = console.error("invalid code:",e,'<code>'+code+'</code>'); code = "return ("+JSON.stringify(error)+');'; } return code.replace(/<\/script>/g,'<\\/script>').replace(/^\s*[\r\n]+/,''); } } function genSource(ctx){ var header = ctx.header; var body = ctx.body; var functionName = ctx.name; var params = ctx.params var args = params?params.join(','):'__context__,__out__'; var result = ['function ',functionName,"(",args,'){\n',header,'\n'] if (ctx.waitPromise) { result.push("\t__g__ = __g__();", "function __n__(){", "var n = __g__.next().value;", "if(n instanceof Promise){", "n.then(__n__);console.log('is promise',n)", "}", "};__n__();\n"); result.push('\tfunction* __g__(){\n',body,'\n\treturn __out__.join("");\n\t}\n}\n'); }else{ if(params){ var m = body.match(/^\s*__out__\.push\((.*?)\);?\s*$/) if(m){ var item = '\treturn ['+m[1]+']' try{ new Function(item) if(item.indexOf(',')>0){ result.push(item,'.join("");\n}') }else{ result.push('\treturn ',m[1],';\n}'); } return result.join(''); }catch(e){} } result.push('\tvar __out__ = [];\n'); }else{ result.push('\tvar __out__ = __out__||[];\n'); } result.push(body,'\n\treturn __out__.join("");\n}\n'); } return result.join(''); } function genDecFunction(contents,functionName,params,defaults,modelVarsDec){ var modelVarsDecAndParams = modelVarsDec.concat(); var args = params?params.join(','):'__context__'; if(params && defaults && defaults.length){ modelVarsDecAndParams.push('\tswitch(arguments.length){\n'); var begin = params.length - defaults.length for(var i =0;i<params.length;i++){ modelVarsDecAndParams.push('\t case ',i,':\n'); if(i>=begin){ modelVarsDecAndParams.push('\t ',params[i],'=',JSON.stringify(defaults[i-begin]),';\n'); } } modelVarsDecAndParams.push('\t}\n'); } var source = contents.join('') var SP = /^\s*\__out__\.push\((?:(.*)\)\s*;?)\s*$/g; if(SP.test(source)){ var c =source.replace(SP,'$1'); if(c.indexOf(',')>0){ source = "\treturn ["+c+"].join('');"; }else{ source = "\treturn "+c+';'; } }else{ source = "\tvar __out__=[]\n"+source.replace(/^\s*\n|\s*\n\s*$/g,'')+"\n\treturn __out__.join('');\n"; } return 'function '+functionName+"("+args+'){\n'+modelVarsDecAndParams.join('')+source.replace(/^[\r\n]+/,'')+'\n}\n' } function genModelDecVars(ctx,scope,params){ var result = []; var map = {}; var refMap = scope.externalRefMap; var callMap = scope.callMap; var varMap = scope.varMap; var paramMap = scope.paramMap; copy(refMap,map); var vars = []; for(var n in map){ if(n != '*' && !((n in GLOBAL_VAR_MAP)|| (n in varMap) || (n in paramMap))){ if(params){ }else{ result.push('\tvar ',n,'=("',n,'" in __context__?__context__:this)["',n,'"];\n'); vars.push(n); } } } if(!params && ctx.waitPromise){ result.push(vars.join('\n').replace(/.+/mg,'\tif($& instanceof Promise){$&.then(function(v){$& = v});}'),'\n'); } return result; } function genBuildInSource(ctx){ if(ctx.hasBuildIn){return ''} var buf = ['']; var c = ctx.xmlEncoder + ctx.entityEncoder*2; if(c){ if(c>3){ ctx.optimizedEncoder = true; buf.push(" function __x__(source,e){return String(source).replace(e||/&(?!#\\d+;|#x[\\da-f]+;|[a-z]+;)|[<\"]/ig,function(c){return '&#'+c.charCodeAt()+';'});}\n"); }else{ buf.push(" function __r__(c){return '&#'+c.charCodeAt()+';'}\n"); } } if(ctx.safeGetter){ buf.push(' function __get__(o,p,a){try{return a?o[p].apply(o,a):o[p]}catch(e){return e}}\n') } if(ctx.forStack.hit){ buf.push(" if(!Object.keys)Object.keys=function(o){var r=[];for(var n in o){r.push(n)};return r;};\n") } var df = ctx.dateFormat; if(df.hit){ var dlstart = df.isFixLen?'__dl__(':'' var dlend = df.isFixLen?',format.length)':'' if(dlstart) buf.push(" function __dl__(date,len){return len > 1? ('000'+date).slice(-len):date;}\n"); if(df.T) buf.push(" function __tz__(offset){return offset?(offset>0?'-':offset*=-1,'+')+__dl__(offset/60,2)+':'+__dl__(offset%60,2):'Z'}\n"); if(df) buf.push(" function __df__(pattern,date){\n"); if(df) buf.push(" date = date?new Date(date):new Date();\n"); if(df) buf.push(" return pattern.replace(/", df.qute?"'[^']+'|\"[^\"]+\"|":'', "([YMDhms])\\1*", df['.']?"|\\.s":'', df.T?"|TZD$":'', "/g,function(format){\n"); if(df) buf.push(" switch(format.charAt()){\n"); if(df.Y) buf.push(" case 'Y' :return ",dlstart,"date.getFullYear()",dlend,";\n"); if(df.M) buf.push(" case 'M' :return ",dlstart,"date.getMonth()+1",dlend,";\n"); if(df.D) buf.push(" case 'D' :return ",dlstart,"date.getDate()",dlend,";\n"); if(df.h) buf.push(" case 'h' :return ",dlstart,"date.getHours()",dlend,";\n"); if(df.m) buf.push(" case 'm' :return ",dlstart,"date.getMinutes()",dlend,";\n"); if(df.s) buf.push(" case 's' :return ",dlstart,"date.getSeconds()",dlend,";\n"); if(df['.']) buf.push(" case '.':return '.'+",dlstart,"date.getMilliseconds(),3);\n"); if(df.T) buf.push(" case 'T':return __tz__(date.getTimezoneOffset());\n"); if(df.qute) buf.push(" case '\'':case '\"':return format.slice(1,-1);\n"); if(df) buf.push(" default :return format;\n"); if(df) buf.push(" }\n"); if(df) buf.push(" });\n"); if(df) buf.push(" }\n"); } return buf.join(''); } function createDateFormat(ctx,pattern,date){ var df = ctx.dateFormat; var patternSample=pattern[1]; var maxLen = 0; if(pattern[0] != -1){ patternSample='YYMMDDhhmmss.sTZD'; } patternSample.replace(/([YMDhms])\1*|\.s|TZD/g,function(c){ len = c.length; c = c.charAt(); if(c == '"' || c== '\''){ df.qute = 1; } maxLen = Math.max(maxLen,df[c]=Math.max(df[c]||0,len)); }) df.isEL = df.isEL || date[0] != -2; df.isFixLen = df.isFixLen || maxLen>1; df.hit ++; pattern = ctx.stringifyEL(pattern); date = ctx.stringifyEL(date) return {toString:function(){ return '__df__('+pattern+','+date+')'; }} } function JSTranslateContext(code,name,params,defaults){ TranslateContext.call(this,code,name,params,defaults); this.forStack = []; this.defaults = defaults; this.xmlEncoder = 0; this.entityEncoder=0; this.dateFormat = {hit:0}; this.safeGetter = {hit:0} } JSTranslateContext.prototype = new TranslateContext(); JSTranslateContext.prototype.parse=function(){ var params = this.params; this.out = []; var defs = this.scope.defs; var thiz = this; var defVars = [] for(var i=0;i<defs.length;i++){ var def = this.scope.defMap[defs[i]]; this.outputIndent=1; this.appendCode(def.code); var vars = genModelDecVars(this,def,def.params); var contents = thiz.reset(); defVars.push({ params:def.params, defaults:def.defaults, vars:vars, name:def.name, toString:function(){ var fn = genDecFunction(contents,this.name,def.params,def.defaults,[]); return String(fn).replace(/^(.)/mg,'\t$1'); }}); } try{ this.outputIndent=0; this.outputIndent++; this.appendCode(this.scope.code); this.outputIndent--; }catch(e){ throw e; } var headers = []; var headers = genModelDecVars(this,this.scope,this.params); var buildIn = genBuildInSource(this); if(buildIn){ headers.unshift(buildIn); } this.header = headers.concat(defVars).join(''); this.body = this.reset().join('').replace(/^[\r\n]+/,'') } JSTranslateContext.prototype.appendStatic = function(item){ appendOutput(this,JSON.stringify(item)); } JSTranslateContext.prototype.appendEL=function(item){ appendOutput(this,this.stringifyEL(item[1])) } JSTranslateContext.prototype.appendXT=function(item){ appendOutput(this,createXMLEncoder(this,item[1])) } JSTranslateContext.prototype.appendXA=function(item){ var el = item[1]; var value = this.stringifyEL(el); var attributeName = item.length>2 && item[2]; if(attributeName){ var testId = this.allocateId(value); if(testId != value){ el = new Expression(testId).token; this.append("var ",testId,"=",value); } this.append("if(",testId,"!=null){"); this.pushBlock(); appendOutput(this,"' "+attributeName+"=\"'",createXMLEncoder(this,el,true),"'\"'"); this.popBlock(); this.append("}"); this.freeId(testId); }else{ appendOutput(this,createXMLEncoder(this,el,true)) } } JSTranslateContext.prototype.appendVar=function(item){ this.append("var ",item[2],"=",this.stringifyEL(item[1]),";"); }, JSTranslateContext.prototype.appendEncodePlugin=function(item){ appendOutput(this,createEntityEncoder(this,item[1])); }, JSTranslateContext.prototype.appendDatePlugin=function(pattern,date){ appendOutput(this,createDateFormat(this,pattern[1],date[1])) } JSTranslateContext.prototype.processCapture = function(item){ var childCode = item[1]; if(childCode.length == 1 && childCode[0].constructor == String){ item[1] = JSON.stringify(childCode[0]); this.appendVar(item); }else{ var varName = item[2]; var bufbak = this.allocateId(); this.append("var ",bufbak,"=__out__;__out__=[];"); this.appendCode(childCode); this.append("var ",varName,"=__out__.join('');__out__=",bufbak,";"); this.freeId(bufbak); } }, JSTranslateContext.prototype.processIf=function(code,i){ var item = code[i]; var childCode = item[1]; var testEL = item[2]; var test = this.stringifyEL(testEL); this.append('if(',test,'){'); this.pushBlock(); this.appendCode(childCode) this.popBlock(); this.append("}"); var nextElse = code[i+1]; var notEnd = true; this.pushBlock(true); while(nextElse && nextElse[0] == ELSE_TYPE){ i++; var childCode = nextElse[1]; var testEL = nextElse[2]; var test = this.stringifyEL(testEL); if(test){ var wel = genWaitEL(this,testEL); this.append('else if(',wel?'('+wel+')||('+test+')':test,'){'); }else{ notEnd = false; this.append("else{"); } this.pushBlock(); this.appendCode(childCode) this.popBlock(); this.append("}"); nextElse = code[i+1]; } this.popBlock(true); return i; } JSTranslateContext.prototype.processFor=function(code,i){ this.forStack.hit = true; var item = code[i]; var indexId = this.allocateId(); var lastIndexId = this.allocateId(); var itemsId = this.allocateId(); var itemsEL = this.stringifyEL(item[2]); var varNameId = item[3]; var childCode = item[1]; var forInfo = this.findForStatus(item) this.append("var ",itemsId,'=',itemsEL,';'); this.append("var ",indexId,"=0;") this.append("var ",lastIndexId," = (", itemsId,'=',itemsId,' instanceof Array?',itemsId,':Object.keys(',itemsId,')' ,").length-1;"); var forRef = forInfo.ref ; var forAttr = forInfo.index || forInfo.lastIndex; if(forRef){ var statusId = this.allocateId(); this.forStack.unshift([statusId,indexId,lastIndexId]); this.append("var ",statusId," = {lastIndex:",lastIndexId,"};"); }else if(forAttr){ this.forStack.unshift(['for',indexId,lastIndexId]); } this.append("for(;",indexId,"<=",lastIndexId,";",indexId,"++){"); this.pushBlock(); if(forRef){ this.append(statusId,".index=",indexId,";"); } this.append("var ",varNameId,"=",itemsId,"[",indexId,"];"); this.appendCode(childCode); this.popBlock(); this.append("}"); var nextElse = code[i+1]; var notEnd = true; var elseIndex = 0; this.pushBlock(true); while(notEnd && nextElse && nextElse[0] == ELSE_TYPE){ i++; elseIndex++; var childCode = nextElse[1]; var testEL = nextElse[2]; var test = this.stringifyEL(testEL); var ifstart = elseIndex >1 ?'else if' :'if'; if(test){ var wel = genWaitEL(this,testEL); this.append(ifstart, '(',wel?'('+wel+')|| !':'!' ,indexId,'&&(',test,')){'); }else{ notEnd = false; this.append(ifstart,"(!",indexId,"){"); } this.pushBlock(); this.appendCode(childCode) this.popBlock(); this.append("}"); nextElse = code[i+1]; } this.popBlock(true); if(forRef){ this.freeId(statusId); this.forStack.shift(); }else if(forAttr){ this.forStack.shift(); } this.freeId(lastIndexId); this.freeId(itemsId);; this.freeId(indexId); return i; } JSTranslateContext.prototype.pushBlock = function(ignoreIndent){ if(!ignoreIndent){ this.outputIndent++ } var waitPromise = this.waitPromise; if(waitPromise){ var topStatus = waitPromise[waitPromise.length-1] waitPromise.push(topStatus?topStatus.concat():[]) } } JSTranslateContext.prototype.popBlock = function(ignoreIndent){ if(!ignoreIndent){ this.outputIndent--; } if(this.waitPromise){ this.waitPromise.pop() } } JSTranslateContext.prototype.appendModulePlugin = function(child,config){ if(this.waitPromise){ this.append('__out__.lazy(function* __lazy_widget_',config.id,'__(__out__){'); this.pushBlock(); this.appendCode(child) this.popBlock(); this.append('})'); }else{ this.appendCode(child) } } JSTranslateContext.prototype.stringifyEL= function (el){ return el?new Expression(el).toString(this):null; }; JSTranslateContext.prototype.visitEL= function (el,type){ el = el && genWaitEL(this,el); el && this.append(el); }; JSTranslateContext.prototype.getVarName = function(name){ if(name == 'for'){ console.error('invalue getVarName:') } return name; }; JSTranslateContext.prototype.getForName = function(){ var f = this.forStack[0]; return f && f[0]; }; JSTranslateContext.prototype.genGetCode = function(owner,property){ if(this.safeGetter){ this.safeGetter.hit = true; return '__get__('+owner+','+property+')' }else{ if(/^"[a-zA-Z_\$][_\$\w]*"$/.test(property)){ return owner+'.'+property.slice(1,-1); }else{ return owner+'['+property+']'; } } }; JSTranslateContext.prototype.findForAttribute= function(forName,forAttribute){ var stack = this.forStack; var index = forAttribute == 'index'?1:(forAttribute == 'lastIndex'?2:0); for(var i=0;index && i<stack.length;i++){ var s = stack[i]; if(s && s[0] == forName){ return s[index]; } } } function genWaitEL(ctx,el){ if(ctx.waitPromise){ var topWaitedVars = ctx.waitPromise[ctx.waitPromise.length-1]; if(topWaitedVars){ var vars = Object.keys(new Expression(el).getVarMap()); var vars2 = []; for(var i=0;i<vars.length;i++){ var v = vars[i]; if(v != 'for' && topWaitedVars.indexOf(v)<0){ vars2.push(v) topWaitedVars.push(v) } } if (vars2.length) { return 'yield* __out__.wait('+vars2.join(',')+')' }; } } } function appendOutput(ctx){ var outList = ctx.out; var lastOutGroup = ctx._lastOutGroup; var lastIndex = outList.length-1; var args = outList.splice.call(arguments,1); if(lastOutGroup && outList[lastIndex] === lastOutGroup){ lastOutGroup.list.push.apply(lastOutGroup.list,args) }else{ ctx.append(ctx._lastOutGroup = new OutputGroup(args)); } } function OutputGroup(args){ this.list = args; } OutputGroup.prototype.toString = function(){ return '__out__.push(' + this.list.join(',')+');' } function createXMLEncoder(thiz,el,isAttr){ thiz.xmlEncoder ++; el = thiz.stringifyEL(el); return {toString:function(){ var e = (isAttr?'/[&<\\"]/g':'/[&<]/g'); if(thiz.optimizedEncoder||thiz.hasBuildIn){ return '__x__('+el+','+e+')'; }else{ return 'String('+el+').replace('+e+',__r__)' } }} } function createEntityEncoder(thiz,el){ el = thiz.stringifyEL(el); thiz.entityEncoder ++; return { toString:function(){ if(thiz.optimizedEncoder || thiz.hasBuildIn){ return '__x__('+el+')'; }else{ return 'String('+el+').replace(/&(?!#\\d+;|#x[\\da-f]+;|[a-z]+;)|[<"]/ig,__r__)' } }} } function copy(source,target){ for(var n in source){ target[n] = source[n]; } } exports.JSTranslator=JSTranslator; exports.GLOBAL_DEF_MAP=GLOBAL_DEF_MAP; exports.GLOBAL_VAR_MAP=GLOBAL_VAR_MAP; } , function(exports,require,module){function Template(code,config){ try{ this.impl = code instanceof Function?code:eval('['+code+'][0]'); }catch(e){ this.impl = function(){throw e;}; } this.config = config; this.contentType = config.contentType; this.encoding = config.encoding; } Template.prototype.render = function(context,response){ try{ this.impl.call(null,context,wrapResponse(response)); }catch(e){ console.warn(this.impl+''); var rtv = require(5).inspect(e,true)+'\n\n'+(e.message +e.stack); response.end(rtv); throw e; } } function wrapResponse(resp){ var lazyList = []; var buf=[]; var bufLen=0; return { push:function(){ for(var len = arguments.length, i = 0;i<len;i++){ var txt = arguments[i]; buf.push(txt) if((bufLen+=txt)>1024){ resp.write(buf.join('')); buf = []; bufLen = 0; } } }, join:function(){ resp.write(buf.join('')); buf = []; if(!doMutiLazyLoad(lazyList,resp)){ resp.end(); } }, flush:function(){ resp.write(buf.join('')); buf = []; bufLen = 0; }, wait:modelWait, lazy:function(g){ lazyList.push(g); } } } try{ var modelWait = Function('return function* modelWait(){' + 'var i = arguments.length;while(i--){if (arguments[i] instanceof Promise) {' + 'this.flush();'+ 'yield arguments[i]}}}')() }catch(e){ console.error('es6 yield is not support!!'); var modelWait = function(){ return {done:true} } } function doMutiLazyLoad(lazyList,resp){ var len = lazyList.length; var dec = len; var first = true; for(var i = 0;i<len;i++){ startModule(lazyList[i],[]); } function startModule(g,r){ var id = g.name.replace(/^[^\d]+|[^\d]+$/g,''); r.flush = function(){}; r.wait = modelWait; g = g(r); function next(){ var n = g.next(); if(n.done){ var rtv = r.join(''); resp.write('<script>'+ (first?'!this.__widget_loaded__&&(this.__widget_loaded__=function(id,h){document.querySelector(id).innerHTML=h});':'') +'__widget_loaded__("*[data-lazy-widget-id=\''+id+'\']",'+JSON.stringify(rtv).replace(/<\/script>/ig,'<\\/script>')+')</script>') first = false; if(--dec == 0){ resp.end(); } return rtv; }else{ n.value.then(next); } } next(); } return len; } exports.wrapResponse = wrapResponse; exports.Template = Template; } , function(exports,require){if(typeof require == 'function'){ var XA_TYPE=require(14).XA_TYPE; var ELSE_TYPE=require(14).ELSE_TYPE; var EL_TYPE=require(14).EL_TYPE; var XT_TYPE=require(14).XT_TYPE; var TranslateContext=require(16).TranslateContext; var getELType=require(18).getELType; var TYPE_ANY=require(18).TYPE_ANY; var TYPE_BOOLEAN=require(18).TYPE_BOOLEAN; var TYPE_NULL=require(18).TYPE_NULL; var TYPE_NUMBER=require(18).TYPE_NUMBER; var GLOBAL_DEF_MAP=require(1).GLOBAL_DEF_MAP; var GLOBAL_VAR_MAP=require(1).GLOBAL_VAR_MAP; } var FOR_STATUS_KEY = '$__for'; var VAR_LITE_TEMP="$__tmp"; function PHPTranslator(config){ this.waitPromise = config.waitPromise; this.liteImpl = config.liteImpl||'lite__' } PHPTranslator.prototype = { translate:function(list,config){ var context = new PHPTranslateContext(list||this.code,config.name); context.waitPromise = this.waitPromise; context.htmlspecialcharsEncoding = context.encoding = config.encoding ||"UTF-8"; context.contentType = config.contentType; context.i18n = config.i18n context.resources = config.resources; context.parse(); var code = context.toSource(); return '<?php'+code ; } } function PHPTranslateContext(code,id){ TranslateContext.call(this,code,null); this.id = id; } function TCP(pt){ for(var n in pt){ this[n] = pt[n]; } } TCP.prototype = TranslateContext.prototype; function toArgList(params,defaults){ if(params.length){ if(defaults && defaults.length){ params = params.concat(); var i = params.length; var j = defaults.length; while(j--){ params[--i] += '='+stringifyPHP(defaults[j]); } } return '$'+params.join(',$') }else{ return ''; } } function _stringifyPHPLineArgs(line){ var endrn="'"; line = line.replace(/['\\]|(\?>)|([\r\n]+$)|[\r\n]/gm,function(a,pend,lend){ if(lend){ endrn = ''; return "',"+JSON.stringify(a); }else if(pend){ return "?','>"; }else{ if(a == '\\'){ return '\\\\'; }else if(a == "'"){ return "\\'"; }else{ console.error("非法输出行!!"+JSON.stringify(line)); } return a == '\\'?'\\\\': "\\'"; } }); line = "'"+line+endrn; if("''," == line.substring(0,3)){ line = line.substring(3) } return line; } function _encodeEL(text,model,encoding){ if(model == -1){ var encode = "htmlspecialchars("+text+",ENT_COMPAT,"+encoding+",false)"; }else if(model == XA_TYPE){ var encode = "htmlspecialchars("+text+",ENT_COMPAT,"+encoding+')'; }else if(model == XT_TYPE){ var encode = "htmlspecialchars("+text+",ENT_NOQUOTES,"+encoding+')'; }else{ var encode = text; } return encode; } function _appendFunctionName(context,scope){ for(var n in scope.refMap){ if(!(n in scope.varMap || n in scope.paramMap)){ if(n in GLOBAL_DEF_MAP){ context.append('$',n,"='",n,"';"); }else if(n in GLOBAL_VAR_MAP){ }else{ context.append('$',n,"=function_exists('lite__",n,"')?'",n,"':null;"); } } } } PHPTranslateContext.prototype = new TCP({ stringifyEL:function (el){ return el?stringifyPHPEL(el,this):null; }, parse:function(){ this.depth = 0; this.out = []; var defs = this.scope.defs; for(var i=0;i<defs.length;i++){ var def = this.scope.defMap[defs[i]]; var n = def.name; this.append("if(!function_exists('lite__",n,"')){function lite__", n,"(",toArgList(def.params,def.defaults),'){') this.depth++; this.append("ob_start();"); _appendFunctionName(this,def); this.appendCode(def.code); this.append("$rtv= ob_get_contents();ob_end_clean();return $rtv;"); this.depth--; this.append("}}"); } try{ this.append("function lite_template",this.id,'($__context__){') this.depth++; if(this.contentType){ this.append("if(!headers_sent())header('ContentType:"+this.contentType+"');") } this.append("mb_internal_encoding('"+this.encoding+"');") _appendFunctionName(this,this.scope); this.append("extract($__context__,EXTR_OVERWRITE);"); if(this.i18n && this.resources){ var i18ncode = new Function("return "+this.i18n)(); var resources = this.resources; var resourceMap = {}; var resourceList = []; for(var i=0;i<resources.length;i++){ resourceMap[i18nHash(resources[i],'_').slice(0,-1)] = resources[i] } console.warn(resources,resourceMap) for(var n in i18ncode){ n = n.substring(0,n.indexOf('__')+2); if(n in resourceMap){ resourceList.push(n.slice(0,-2)); delete resourceMap[n]; } } this.append("$I18N = "+stringifyPHP(resourceList).replace(/^array/,'lite_i18n')+";") this.append("$I18N = array_merge("+stringifyPHP(i18ncode)+",$I18N);") } this.appendCode(this.scope.code); if(this.__lazy_module_){ this.append('lite_lazy_block($__lazy_module_);'); } this.depth--; this.append("}"); }catch(e){ console.error("PHP编译失败:"+this.id,e); throw e; } }, appendStatic:function(value){ var lines = value.match(/.+[\r\n]*|[\r\n]+/g); for(var i=0; i<lines.length; i++) { var line = lines[i]; var start = i==0?'echo ':'\t,' var end = i == lines.length-1?';':''; line = _stringifyPHPLineArgs(line); this.append(start,line,end); } }, _appendEL:function(el,model,text,prefix){ var encoding = "'"+this.htmlspecialcharsEncoding+"'"; prefix = prefix!=null? prefix : 'echo ' var text = text || this.stringifyEL(el); var type = getELType(el); if(isSimplePHPEL(text)){ var initText = text; var tmpId = text; }else{ tmpId = VAR_LITE_TEMP; initText = '('+tmpId+'='+text+')'; } if(type != TYPE_ANY){ if(type == TYPE_NULL){ this.append(prefix,"'null';"); return; }else if(type == TYPE_BOOLEAN){ this.append(prefix,text,"?'true':'false';"); return; }else if(type == TYPE_NUMBER){ this.append(prefix,text,";"); return; } if((TYPE_NULL|TYPE_BOOLEAN)==type){ this.append(prefix,initText,"?'true':(",tmpId,"===null?'null':'false');"); return; }else if(!((TYPE_NULL|TYPE_BOOLEAN) & type)){ this.append(prefix,_encodeEL(text,model,encoding),";"); return; } if(!(type & TYPE_NULL)){ this.append(prefix, initText," === true?'true':", "(",tmpId,"===false?'false':",_encodeEL(tmpId,model,encoding),");"); return ; }else if(!(type & TYPE_BOOLEAN)){ this.append(prefix, initText,"===null?'null':",_encodeEL(tmpId,model,encoding),";"); return ; } } this.append(prefix,'(',initText,'===null||',tmpId,'===false || ',tmpId,'===true)?json_encode(',tmpId,'):',_encodeEL(tmpId,model,encoding),';') }, appendEL:function(item){ this._appendEL(item[1],EL_TYPE) }, appendXT:function(item){ this._appendEL(item[1],XT_TYPE) }, appendXA:function(item){ var el = item[1]; var value = this.stringifyEL(el); var attributeName = item.length>2 && item[2]; var testAutoId = this.allocateId(value); if(testAutoId != value){ this.append(testAutoId,"=",value,';'); } if(attributeName){ this.append("if(",testAutoId,"!=null){"); this.depth++; this.append("echo ' "+attributeName+"=\"';"); this._appendEL(el,XA_TYPE,testAutoId) this.append("echo '\"';"); this.depth--; this.append("}"); }else{ this._appendEL(el,XA_TYPE,testAutoId); } this.freeId(testAutoId); }, appendVar:function(item){ this.append("$",item[2],"=",this.stringifyEL(item[1]),";"); }, processCapture:function(item){ var childCode = item[1]; var varName = item[2]; this.append("ob_start();"); this.appendCode(childCode); this.append("$",varName,"= ob_get_contents();ob_end_clean();"); }, appendEncodePlugin:function(item){ this._appendEL(item[1],-1,this.stringifyEL(item[1])); }, appendDatePlugin:function(pattern,date){ var pattern = this.stringifyEL(pattern[1]); var date = this.stringifyEL(date[1]); if(/^(?:'[^']+'|"[^"]+")$/.test(pattern)){ date = date + ',true'; } this.append('echo lite__2(',pattern,',',date,');') }, appendModulePlugin:function(child,config){ if(this.waitPromise){ this.append("ob_start();"); this.outputIndent++; this.appendCode(child) this.outputIndent--; if(this.__lazy_module_){ this.append('array_push($__lazy_module_,'+config.id+');'); this.append('array_push($__lazy_module_,ob_get_contents());'); }else{ this.append('$__lazy_module_=array('+config.id+',ob_get_contents());') } this.append('ob_end_clean();'); this.__lazy_module_ = true; }else{ this.appendCode(child) } }, processIf:function(code,i){ var item = code[i]; var childCode = item[1]; var testEL = item[2]; var test = this.stringifyEL(testEL); this.append("if(",php2jsBoolean(testEL,test),"){"); this.depth++; this.appendCode(childCode) this.depth--; this.append("}"); var nextElse = code[i+1]; var notEnd = true; while(nextElse && nextElse[0] == ELSE_TYPE){ i++; var childCode = nextElse[1]; var testEL = nextElse[2]; var test = this.stringifyEL(testEL); if(test){ this.append("else if(",php2jsBoolean(testEL,test),"){"); }else{ notEnd = false; this.append("else{"); } this.depth++; this.appendCode(childCode) this.depth--; this.append("}"); nextElse = code[i+1]; } return i; }, processFor:function(code,i){ var item = code[i]; var indexAutoId = this.allocateId(); var keyAutoId = this.allocateId(); var isKeyAutoId = this.allocateId(); var itemsEL = this.stringifyEL(item[2]); var varName = '$'+item[3]; var childCode = item[1]; var forInfo = this.findForStatus(item) if(forInfo.depth){ var preForAutoId = this.allocateId(); } if(/^\$[\w_]+$/.test(itemsEL)){ var itemsAutoId = itemsEL; }else{ var itemsAutoId = this.allocateId(); this.append(itemsAutoId,'=',itemsEL,';'); } this.append('if(',itemsAutoId,'<=PHP_INT_MAX){',itemsAutoId,'=',itemsAutoId,'>0?range(1,',itemsAutoId,'):array();}'); var needForStatus = forInfo.ref || forInfo.index || forInfo.lastIndex; if(needForStatus){ if(forInfo.depth){ this.append(preForAutoId ,"=",FOR_STATUS_KEY,";"); } this.append(FOR_STATUS_KEY," = array('lastIndex'=>count(",itemsAutoId,")-1);"); } this.append(indexAutoId,"=-1;") this.append(isKeyAutoId,'=false;') this.append("foreach(",itemsAutoId," as ",keyAutoId,"=>",varName,"){"); this.depth++; this.append("if(++",indexAutoId," === 0){"); this.depth++; this.append(isKeyAutoId,"=",keyAutoId," !== 0;"); this.depth--; this.append("}"); this.append("if(",isKeyAutoId,"){",varName,'=',keyAutoId,";}"); if(needForStatus){ this.append(FOR_STATUS_KEY,"['index']=",indexAutoId,";"); } this.appendCode(childCode); this.depth--; this.append("}"); if(needForStatus && forInfo.depth){ this.append(FOR_STATUS_KEY,"=",preForAutoId,';'); } this.freeId(isKeyAutoId); this.freeId(keyAutoId); this.freeId(itemsAutoId); if(forInfo.depth){ this.freeId(preForAutoId); } var nextElse = code[i+1]; var notEnd = true; var elseIndex = 0; while(notEnd && nextElse && nextElse[0] == ELSE_TYPE){ i++; elseIndex++; var childCode = nextElse[1]; var testEL = nextElse[2]; var test = this.stringifyEL(testEL); var ifstart = elseIndex >1 ?'else if' :'if'; if(test){ this.append(ifstart,"(",indexAutoId,"<0&&",php2jsBoolean(testEL,test),"){"); }else{ notEnd = false; this.append(ifstart,"(",indexAutoId,"<0){"); } this.depth++; this.appendCode(childCode) this.depth--; this.append("}"); nextElse = code[i+1]; } this.freeId(indexAutoId); return i; }, toSource:function(){ return this.out.join(''); } }); if(typeof require == 'function'){ exports.PHPTranslator=PHPTranslator; var php2jsBoolean=require(19).php2jsBoolean; var isSimplePHPEL=require(19).isSimplePHPEL; var stringifyPHP=require(19).stringifyPHP; var stringifyPHPEL=require(19).stringifyPHPEL; var i18nHash=require(20).i18nHash; } } , function(exports,require,module){console.log("read module err!!!fs\nError: ENOENT: no such file or directory, open 'fs'") } , function(exports,require,module){console.log("read module err!!!util\nError: ENOENT: no such file or directory, open 'util'") } , function(exports,require){ function ResultContext(){ this.result = []; } function checkVar(v){ var exp = /^(break|case|catch|const|continue|default|do|else|false|finally|for|function|if|in|instanceof|new|null|return|switch|this|throw|true|try|var|void|while|with)$|^[a-zA-Z_][\w_]*$/; var match = v.match(exp); if(v == null || !match || match[1]!=null){ throw new Error("无效变量名:Lite有效变量名为(不包括括弧中的保留字):"+exp+"\n当前变量名为:"+v); } return v; } ResultContext.prototype = { parseEL : function(el){ try{ new Function("return ("+el.replace(/\bfor\b/g,"f")+')'); return new Expression(el).token; }catch(e){ console.info("表达式解析失败[fileName:"+this._context.currentURI+"]",el,e.message) throw new Error(); } }, appendText:function( text){ for(var len = arguments.length,i=0;i<len;i++){ this.result.push(String(arguments[i])); } }, appendAll:function(ins){ for(var len = ins.length,i=0;i<len;i++){ this.result.push(ins[i]); } }, appendEL:function( el){ this.result.push([EL_TYPE, requireEL(this,el)]); }, appendXA:function(attributeName, el){ this.result.push([XA_TYPE, requireEL(this,el), attributeName ]); }, appendXT:function(el){ this.result.push([XT_TYPE, requireEL(this,el)]); }, appendIf:function(testEL){ this.result.push([IF_TYPE, requireEL(this,testEL) ]); }, appendElse:function(testEL){ clearPreviousText(this.result); this.result.push([ELSE_TYPE, testEL && requireEL(this,testEL) || null ]); }, appendFor:function(varName, itemsEL, statusName){ this.result.push([FOR_TYPE,requireEL(this,itemsEL), varName ]); if(statusName){ this.appendVar(checkVar(statusName) , this.parseEL('for')); } }, appendEnd:function(){ this.result.push([]) }, appendVar:function(varName, valueEL){ this.result.push([VAR_TYPE,requireEL(this,valueEL),checkVar(varName)]); }, appendCapture:function(varName){ this.result.push([CAPTURE_TYPE,checkVar(varName)]); }, appendPlugin:function(clazz, config){ if(typeof config == 'string'){ config = JSON.parse(config); } config['class'] = clazz; this.result.push([PLUGIN_TYPE,config]); }, allocateId:function(){ if(this.inc){ this.inc++; }else{ this.inc = 1; } return 'gid_'+this.inc.toString(32); }, mark:function(){ return this.result.length; }, reset:function(mark){ return optimizeResult(this.result.splice(mark,this.result.length)); }, toList:function(){ if(!this.optimized){ var result = optimizeResult(this.result); var defMap = {}; var pureCode = buildTreeResult(result,defMap); this.optimized = doOptimize(defMap,pureCode); } return this.optimized; } } function requireEL(context,el){ if(typeof el == 'string'){ el = context.parseEL(el); } return el; } function clearPreviousText(result){ var i = result.length; while(i--){ var item = result[i]; if(typeof item == 'string'){ result.pop(); }else{ break; } } } if(typeof require == 'function'){ exports.ResultContext=ResultContext; var Expression=require(17).Expression; var PLUGIN_TYPE=require(14).PLUGIN_TYPE; var buildTreeResult=require(21).buildTreeResult; var optimizeResult=require(21).optimizeResult; var doOptimize=require(21).doOptimize; var VAR_TYPE=require(14).VAR_TYPE; var XA_TYPE=require(14).XA_TYPE; var ELSE_TYPE=require(14).ELSE_TYPE; var PLUGIN_TYPE=require(14).PLUGIN_TYPE; var CAPTURE_TYPE=require(14).CAPTURE_TYPE; var IF_TYPE=require(14).IF_TYPE; var EL_TYPE=require(14).EL_TYPE; var XT_TYPE=require(14).XT_TYPE; var FOR_TYPE=require(14).FOR_TYPE; } } , function(exports,require){ var uriPattern = /^([a-zA-Z][\w\.]*)\:(?:(\/\/[^\/]*))?(\/?[^?#]*)(\?[^#]*)?(#[\s\S]*)?$/; var absURIPattern = /^[a-zA-Z][\w\.]*\:/; var uriChars = /\\|[\x22\x3c\x3e\x5c\x5e\x60\u1680\u180e\u202f\u205f\u3000]|[\x00-\x20]|[\x7b-\x7d]|[\x7f-\xa0]|[\u2000-\u200b]|[\u2028-\u2029]/g; var allEncodes = /[\x2f\x60]|[\x00-\x29]|[\x2b-\x2c]|[\x3a-\x40]|[\x5b-\x5e]|[\x7b-\uffff]/g; function encodeChar(i){ return "%"+(0x100+i).toString(16).substring(1) } function decodeChar(c){ var n = c.charCodeAt(); if (n < 0x80){ return encodeChar(n); }else if (n < 0x800){ return encodeChar(0xc0 | (n >>> 6))+encodeChar(0x80 | (n & 0x3f)) }else{ return encodeChar( 0xe0 | ((n >>> 12) & 0x0f))+ encodeChar(0x80 | ((n >>> 6) & 0x3f))+ encodeChar(0x80 | (n & 0x3f)) } } function uriDecode(source){ for(var result = [], i=1;i<source.length;i+=3){ var c = parseInt(source.substr(i,2),16); if(c>=240){ c = (c & 0x07)<<18; c += (parseInt(source.substr(i+=3,2),16) &0x3f)<<12; c += (parseInt(source.substr(i+=3,2),16) &0x3f)<<6; c += (parseInt(source.substr(i+=3,2),16) &0x3f); }else if(c>=224){ c = (c & 0x0f)<<12; c += (parseInt(source.substr(i+=3,2),16) &0x3f)<<6; c += (parseInt(source.substr(i+=3,2),16) &0x3f); }else if(c>=192){ c = (c & 0x1f)<<6; c += (parseInt(source.substr(i+=3,2),16) &0x3f); } result.push(String.fromCharCode(c)) } return result.join(''); } function uriReplace(c){ if(c == '\\'){ return '/'; }else{ return decodeChar(c); } } function URI(path){ if(path instanceof URI){ return path; } if(/^\s*[<]/i.test(path)){ path = String(path).replace(uriChars,decodeChar) return new URI("data:text/xml,"+path); }else{ path = String(path).replace(uriChars,uriReplace) } path = path.replace(/\/\.\/|\\\.\\|\\/g,'/'); if(/^\/|^[a-z]\:\//i.test(path)){ path = 'file://'+path; } while(path != (path = path.replace(/[^\/]+\/\.\.\//g,''))); var match = path.match(uriPattern); if(match){ setupURI(this,match); }else{ console.error("url must be absolute,"+path) } } function setupURI(uri,match){ uri.value = match[0]; uri.scheme = match[1]; uri.authority = match[2]; uri.path = match[3]; uri.query = match[4]; uri.fragment = match[5]; if('data' == uri.scheme){ match = uri.value uri.source = decodeURIComponent(match.substring(match.indexOf(',')+1)); } } URI.prototype = { resolve:function(path){ path = String(path); if( /^\s*[#<]/.test(path) ||absURIPattern.test(path)){ path = new URI(path.replace(/^\s+/,'')); return path; } path = path.replace(uriChars,uriReplace) if(path.charAt() != '/'){ var p = this.path; path = p.replace(/[^\/]*$/,path); } return new URI(this.scheme + ':'+(this.authority||'') + path); }, toString:function(){ return this.value; } } var btoa = this.btoa || function(bs){ var b64 = []; var bi = 0; var len = bs.length; while (bi <len) { var b0 = bs.charCodeAt(bi++); var b1 = bs.charCodeAt(bi++); var b2 = bs.charCodeAt(bi++); var data = (b0 << 16) + (b1 << 8) + (b2||0); b64.push( b64codes[(data >> 18) & 0x3F ], b64codes[(data >> 12) & 0x3F], b64codes[isNaN(b1) ? 64 : (data >> 6) & 0x3F], b64codes[isNaN(b2) ? 64 : data & 0x3F]) ; } return b64.join(''); } var b64codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''); function utf8Replacer(c){ var n = c.charCodeAt(); if (n < 0x800){ return String.fromCharCode( (0xc0 | (n >>> 6)), (0x80|(n & 0x3f))); }else{ return String.fromCharCode( (0xe0 | ((n >>> 12) & 0x0f)), (0x80 | ((n >>> 6) & 0x3f)), (0x80 | (n & 0x3f))); } } function base64Encode(data){ data = data && data.replace(/[\u0080-\uFFFF]/g,utf8Replacer)||'' data = btoa(data) ; return encodeURIComponent(data); } function buildURIMatcher(pattern){ var matcher = /\*+|[^\*\\\/]+?|[\\\/]/g; var buf = ["^"]; var m matcher.lastIndex = 0; while (m = matcher.exec(pattern)) { var item = m[0]; var len = item.length; var c = item.charAt(0); if (c == '*') { if (len > 1) { buf.push(".*"); } else { buf.push("[^\\\\/]*"); } } else if(len == 1 && c == '/' || c == '\\') { buf.push("[\\\\/]"); }else{ buf.push(item.replace(/[^\w]/g,quteReqExp)); } } buf.push("$"); return buf.join(''); } function quteReqExp(x){ switch(x){ case '.': return '\\.'; case '\\': return '\\\\'; default: return '\\x'+(0x100 + x.charCodeAt()).toString(16).substring(1); } } if(typeof require == 'function'){ exports.URI=URI; exports.buildURIMatcher = buildURIMatcher; exports.base64Encode=base64Encode; } } , function(exports,require){function loadLiteXML(uri,root){ try{ if(uri instanceof URI){ if(uri.source){ return parseXMLByText(uri.source.replace(/^[\s\ufeff]*/,uri)) }else if(uri.scheme == 'lite'){ var path = uri.path+(uri.query||'')+(uri.fragment || ''); path = root.resolve(path.replace(/^\//,'./'))+''; }else{ var path = String(uri); } }else{ var path = String(uri); } if(/^[\s\ufeff]*[<#]/.test(path)){ return parseXMLByText(path.replace(/^[\s\ufeff]*/,''),root) }else{ if(/^(?:\w+\:\/\/|\w\:\\|\/).*$/.test(path)){ var pos = path.indexOf('#')+1; var xpath = pos && path.substr(pos); var path = pos?path.substr(0,pos-1):path; var source = loadTextByPath(path.replace(/^file\:\/\/?/,'')); var doc = parseXMLByText(source,uri); if(xpath && doc.nodeType){ doc = selectByXPath(doc,xpath); } return doc; }else{ return parseXMLByText(path); } } }catch(e){ console.error("文档解析失败:"+uri,e) throw e; } } function txt2xml(source){ return "<out xmlns='http://www.xidea.org/lite/core'><![CDATA["+ source.replace(/^\ufeff?#.*[\r\n]*/, "").replace(/]]>/, "]]]]><![CDATA[>")+ "]]></out>"; } function addInst(xml,s){ var p = /^\s*<\?(\w+)\s+(.*)\?>/; var m; var first = xml.firstChild; while(m = s.match(p)){ if(m[1] == 'xml'){ var pi = xml.createProcessingInstruction(m[1], m[2]); xml.insertBefore(pi, first); } s = s.substring(m[0].length); } return xml; } function parseXMLByText(text,path){ if(!/^[\s\ufeff]*</.test(text)){ text = txt2xml(text); } try{ var doc = new DOMParser({locator:{systemId:path}, xmlns:defaultNSMap }).parseFromString(text,"text/html") if(!doc.querySelectorAll){ var elp = doc.documentElement.constructor.prototype; elp.querySelector = querySelector; elp.querySelectorAll = querySelectorAll; elp = doc.constructor.prototype; elp.querySelector = querySelector; elp.querySelectorAll = querySelectorAll; } return addInst(doc,text); }catch(e){ console.error("解析xml失败:",e,text); } } function loadTextByPath(path){ var fs = require(4); try{ var text = fs.readFileSync(path,'utf-8'); }catch(e){ return fs.readFileSync(decodeURI(path),'utf-8'); } return text; } function selectorInit(node){ var doc = node.ownerDocument||node; var nw = doc.nwmatcher; if(!nw){ nw = doc.nwmatcher = nwmatcher({document:doc}); nw.configure( { USE_QSAPI: false, VERBOSITY: true } ); } return nw; } function querySelectorAll(selector){ var nodes = selectorInit(this).select(selector,this); nodes.item = nodeListItem; return nodes; } function querySelector(selector){ return selectorInit(this).first(selector,this) } function selectByXPath(currentNode,xpath){ var nodes = xpathSelectNodes(currentNode,xpath); nodes.item = nodeListItem; return nodes; } function nodeListItem(i){ return this[i]; } function findXMLAttribute(el,key){ if(el.nodeType == 2){ return el.value; } try{ var required = key.charAt() == '*'; if(required){ key = key.substr(1); } for(var i=1,len = arguments.length;i<len;i++){ var an = arguments[i]; if(an == '#text'){ return el.textContent||el.text; }else{ var v = el.getAttribute(an); if(v || (typeof el.hasAttribute != 'undefined') && el.hasAttribute(an)){ if(i>1 && key.charAt(0) != '#'){ console.warn(el.tagName+" 标准属性名为:"+key +'; 您采用的是:'+an); } return v; } } } if(required){ console.error("标记:"+el.tagName+"属性:'"+key +"' 为必要属性。"); } }catch(e){ console.error('findXMLAttribute error:',e) } return null; } function findXMLAttributeAsEL(el){ el = findXMLAttribute.apply(null,arguments); if(el !== null){ var el2 = el.replace(/^\s*\$\{([\s\S]*)\}\s*$/,"$1") if(el == el2){ if(el2){ console.warn("缺少表达式括弧,文本将直接按表达式返回",el); } }else{ el2 = el2.replace(/^\s+|\s+$/g,''); if(!el2){ console.warn("表达式内容为空:",el); } el = el2; } } return el; } function getLiteTagInfo(node){ return node.lineNumber + ','+ node.columnNumber+'@'+node.ownerDocument.documentURI; } var defaultNSMap = {c:'http://www.xidea.org/lite/core',h:'http://www.xidea.org/lite/html-ext'} var nwmatcher = require(23); var URI=require(7).URI; var DOMParser = require(22).DOMParser; var xpathSelectNodes = require(26); exports.defaultNSMap = defaultNSMap; exports.querySelector = querySelector; exports.querySelectorAll = querySelectorAll; exports.loadLiteXML=loadLiteXML; exports.selectByXPath=selectByXPath; exports.findXMLAttribute=findXMLAttribute; exports.findXMLAttributeAsEL=findXMLAttributeAsEL; exports.getLiteTagInfo = getLiteTagInfo; } , function(exports,require){ exports.buildTopChain=buildTopChain; function buildTopChain(context){ function TopChain(){ } TopChain.prototype = context; var pt = TopChain.prototype = new TopChain(); pt.index = context._nodeParsers.length; pt.subIndex = -1; pt.getSubChain = getSubChain; pt.next = doNext; pt.constructor = TopChain; return new TopChain(); } function doNext(node){ if (this.subIndex > 0) { var next = this.getSubChain(this.subIndex - 1); } else { next = this.nextChain||buildNext(this,this.index-1); } doParse(node,next); } function doParse(node,chain){ var parser = chain._nodeParsers[chain.index]; if(parser == null){ console.error('解析栈异常',parser,chain.index,chain._nodeParsers); } parser(node,chain,chain); } function getSubChain(subIndex){ if (this.subChains == null) { this.subChains =[]; } var i = this.subChains.length; for (;i <= subIndex; i++) { var subChain = new this.constructor(); subChain.index = this.index subChain.subIndex = i; subChain.subChains = this.subChains; this.subChains.push(subChain); } if (subChain == null) { subChain = this.subChains[subIndex]; } return subChain; } function buildNext(thiz,index){ if(index>=0){ var n = new thiz.constructor(); n.index = index return thiz.nextChain = n; } return null; } } , function(exports,require){ var CORE_URI = "http://www.xidea.org/lite/core" var HTML_EXT_URI = "http://www.xidea.org/lite/html-ext" var HTML_URI = "http://www.w3.org/1999/xhtml" var currentExtension; var defaultNodeLocal={ get:function(){ return this.node }, set:fun