├── .gitignore ├── ISSUE_TEMPLATE.md ├── package.json ├── wuJs.js ├── README.md ├── wuConfig.js ├── wuWxapkg.js ├── wuLib.js ├── wuRestoreZ.js ├── DETAILS.md ├── wuWxss.js ├── wuWxml.js └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | example/ 3 | node_modules/ 4 | package-lock.json 5 | .idea/ -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 发表 Issue 前请仔细阅读以下内容: 2 | 3 | 1. 如果你是要反馈 bug, 请按以下`模板`书写 Issue; 4 | 2. 如果你遇到的是 Node.js 使用问题, 请尽可能依赖搜索引擎解决问题; 5 | 3. 遇到包依赖问题,请联系对应项目; 6 | 4. 任何对某类小程序包的适配问题都应提供 wxapkg 程序包,否则直接 Close 处理; 7 | 5. 提交前请确认 wxapkg 程序包版本不小于 v0.6vv_20180111_fbi (直接用文本编辑器打开 wxapkg包搜索 v0.6vv 或 v0.5vv 即可查到,注意版本大小主要比较的是日期), 旧版本不提供支持, 相关 Issue 直接 Close 处理; 8 | 6. 直接分包和直接处理含插件的包两个功能暂不支持, 请勿重复发表 Issue, 新样例可在已存在的 Issue 下提出; 9 | 7. 请不要在其他 Issue 下发表与该 Issue 无关的回复, 否则将有可能被删除。 10 | 11 | 模板内容如下: 12 | 13 | 程序执行命令(可选): 14 | 15 | 程序执行错误信息(如果反馈是抛出异常的错误,必填): 16 | 17 | ``` 18 | 复制到这里 19 | ``` 20 | 21 | 程序结果错误信息(如果反馈不是抛出异常的错误, 必填, 请尽可能详细描述): 22 | 23 | 程序包(你所要解压的程序包地址, 可为网盘链接, 也可直接上传[上传前请先打包]. 必填): 24 | 25 | 其他附加内容: 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wxapp-unpacker", 3 | "version": "0.3", 4 | "description": "Wechat App(微信小程序, .wxapkg)解包及相关文件(.wxss, .json, .wxs, .wxml)还原工具", 5 | "main": "wuWxapkg.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/qwerty472123/wxappUnpacker.git" 9 | }, 10 | "author": "qwerty472123", 11 | "license": "GPL-3.0-or-later", 12 | "bugs": { 13 | "url": "https://github.com/qwerty472123/wxappUnpacker/issues" 14 | }, 15 | "homepage": "https://github.com/qwerty472123/wxappUnpacker#readme", 16 | "dependencies": { 17 | "css-tree": "^1.0.0-alpha.28", 18 | "cssbeautify": "^0.3.1", 19 | "escodegen": "^1.11.0", 20 | "esprima": "^4.0.0", 21 | "js-beautify": "^1.7.5", 22 | "uglify-es": "^3.3.9", 23 | "vm2": "^3.6.0", 24 | "cheerio": "^1.0.0-rc.2" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /wuJs.js: -------------------------------------------------------------------------------- 1 | const wu=require("./wuLib.js"); 2 | const path=require("path"); 3 | const UglifyJS=require("uglify-es"); 4 | const {js_beautify}=require("js-beautify"); 5 | const {VM}=require('vm2'); 6 | function jsBeautify(code){ 7 | return UglifyJS.minify(code,{mangle:false,compress:false,output:{beautify:true,comments:true}}).code; 8 | } 9 | function splitJs(name,cb){ 10 | let dir=path.dirname(name); 11 | wu.get(name,code=>{ 12 | let needDelList={}; 13 | let vm=new VM({sandbox:{ 14 | require(){}, 15 | define(name,func){ 16 | let code=func.toString(); 17 | code=code.slice(code.indexOf("{")+1,code.lastIndexOf("}")-1).trim(); 18 | let bcode=code; 19 | if(code.startsWith('"use strict";')||code.startsWith("'use strict';"))code=code.slice(13); 20 | else if((code.startsWith('(function(){"use strict";')||code.startsWith("(function(){'use strict';"))&&code.endsWith("})();"))code=code.slice(25,-5); 21 | let res=jsBeautify(code); 22 | if(typeof res=="undefined"){ 23 | console.log("Fail to delete 'use strict' in \""+name+"\"."); 24 | res=jsBeautify(bcode); 25 | } 26 | needDelList[path.resolve(dir,name)]=-8; 27 | wu.save(path.resolve(dir,name),jsBeautify(res)); 28 | } 29 | }}); 30 | vm.run(code.slice(code.indexOf("define("))); 31 | console.log("Splitting \""+name+"\" done."); 32 | if(!needDelList[name])needDelList[name]=8; 33 | cb(needDelList); 34 | }); 35 | } 36 | module.exports={jsBeautify:jsBeautify,wxsBeautify:js_beautify,splitJs:splitJs}; 37 | if(require.main===module){ 38 | wu.commandExecute(splitJs,"Split and beautify weapp js file.\n\n\n\n js files to split and beautify."); 39 | } 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wxappUnpacker 2 | 3 | ![版本 0.3](https://img.shields.io/badge/版本-0.3-red.svg) ![支持的微信版本 >20180111](https://img.shields.io/badge/%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC-%3E=20180111-brightgreen.svg) ![高级特性支持度 0](https://img.shields.io/badge/%E6%94%AF%E6%8C%81-0%25-yellow.svg) 4 | 5 | > Wechat App(微信小程序, .wxapkg)解包及相关文件(.wxss, .json, .wxs, .wxml)还原工具 6 | 7 | ## 当前功能如下(分包功能尚未完成!) 8 | 9 | - `node wuConfig.js ` 将 app-config.json 中的内容拆分到各个文件对应的 .json 和 app.json , 并通过搜索 app-config.json 所在文件夹下的所有文件尝试将 iconData 还原为 iconPath 。 10 | - `node wuJs.js ` 将 app-service.js (或小游戏中的 game.js ) 拆分成一系列原先独立的 javascript 文件,并使用 Uglify-ES 美化,从而尽可能还原编译前的情况。 11 | - `node wuWxml.js [-m] ` 将编译/混合到 page-frame.html ( 或 app-wxss.js ) 中的 wxml 和 wxs 文件还原为独立的、未编译的文件。如果加上`-m`指令,就会阻止`block`块自动省略,可能帮助解决一些相关过程的 bug 。 12 | - `node wuWxss.js ` 通过获取文件夹下的 page-frame.html ( 或 app-wxss.js ) 和其他 html 文件的内容,还原出编译前 wxss 文件的内容。 13 | - `node wuWxapkg.js [-o] [-d] [-s=
] ` 将 wxapkg 文件解包,并将包中上述命令中所提的被编译/混合的文件自动地恢复原状。如果加上`-o`指令,表示仅解包,不做后续操作。如果加上`-d`指令,就会保留编译/混合后所生成的新文件,否则会自动删去这些文件。同时,前面命令中的指令也可直接加在这一命令上。而如果需要解压分包,请先解压主包,然后执行`node wuWxapkg.js [-d] -s=
`,其中`Main Dir`为主包解压地址。除`-d`与`-s`外,这些指令两两共存的后果是未定义的(当然,是不会有危险的)。 14 | 15 | ### wxapkg 包的获取 16 | 17 | Android 手机最近使用过的微信小程序所对应的 wxapkg 包文件都存储在特定文件夹下,可通过以下命令查看: 18 | 19 | adb pull /data/data/com.tencent.mm/MicroMsg/{User}/appbrand/pkg 20 | 21 | 其中`{User}` 为当前用户的用户名,类似于 `2bc**************b65`。 22 | 23 | ### 另注 24 | 25 | 所有命令上都可以使用`-f`指令来提高一定的并行度,但输出信息会混乱。 26 | 27 | 如果发现包内文件“缺失”,请先检查解包时是否出现提示`NOTICE: SubPackages exist in this package.`。如存在,请在寻找好分包后,按上文提示操作。(小程序需要访问特定页面;小游戏需要触发特定函数,然后分包才会被下载。) 28 | 29 | ### 局限(包括但可能不限于以下内容) 30 | 31 | - 实现中很多功能基于特定的版本(`wcc-v0.6vv_20180111_fbi`, 且不考虑面向低版本适配)和字符串搜索,所以不能很好的适应各种特殊情况。 32 | - wxml 文件拥有不同于 xml 和 html 文件的字符转义规则,且尚未公开(并非"没有"),因此未能很好的还原相关内容。 33 | - js 文件被压缩后会丢失原始变量名等信息内容无法还原;wxss 文件压缩后的注释也会丢失。 34 | - wxs 文件会将所有的变量如 Math 改为 nv_Math ,这里仅通过字符串替换去除。 35 | - 一些被引用 wxss 文件本身的源文件丢失,因此无法恢复原始目录。 36 | - 有些项目开启了难以复原的`es6转es5`选项,检验本项目结果是否正确时需要关闭项目中的`es6转es5`选项。 37 | - wxml 中一些无法找到相对应 的正向语句的内容无法还原。 38 | - json 中`components`项丢失,仅会标注被其他包引用的自定义组件。 39 | 40 | ## 依赖 41 | 42 | 这些 node.js 程序除了自带的 API 外还依赖于以下包: 43 | [cssbeautify](https://github.com/senchalabs/cssbeautify)、[CSSTree](https://github.com/csstree/csstree)、[VM2](https://github.com/patriksimek/vm2)、[Esprima](https://github.com/jquery/esprima)、[UglifyES](https://github.com/mishoo/UglifyJS2/tree/harmony)、[js-beautify](https://github.com/beautify-web/js-beautify) 44 | 45 | 您需要安装这些包才能正确执行这些程序,为了做到这一点,您可以执行`npm install`;另外如需全局安装这些包可执行以下命令: 46 | 47 | npm install esprima -g 48 | npm install css-tree -g 49 | npm install cssbeautify -g 50 | npm install vm2 -g 51 | npm install uglify-es -g 52 | npm install js-beautify -g 53 | npm install escodegen -g 54 | 55 | 此外,这些 node.js 程序之间也有一定的依赖关系,比如他们都依赖于 wuLib.js 。 56 | 57 | 58 | ## 参考 59 | 60 | 这些实现除了参考微信小程序开发文档、 wxapkg 文件解包后的内容以及通过开发者工具编译的一些 wxml 外,还参考了一些 github 上的相关内容的分析( [unwxapkg.py](https://gist.github.com/feix/32ab8f0dfe99aa8efa84f81ed68a0f3e)、[wechat-app-unpack](https://github.com/leo9960/wechat-app-unpack/) ),在此感谢他们。 61 | 62 | 另外,如果您对本程序的一些具体实现细节感兴趣,可以参考 [DETAILS.md](https://github.com/qwerty472123/wxappUnpacker/blob/master/DETAILS.md) 。 63 | -------------------------------------------------------------------------------- /wuConfig.js: -------------------------------------------------------------------------------- 1 | const wu=require("./wuLib.js"); 2 | const fs=require("fs"); 3 | const path=require("path"); 4 | const crypto=require("crypto"); 5 | const {VM}=require('vm2'); 6 | function getWorkerPath(name){ 7 | let code=fs.readFileSync(name,{encoding:'utf8'}); 8 | let commPath=false; 9 | let vm=new VM({sandbox:{ 10 | require(){}, 11 | define(name){ 12 | name=path.dirname(name)+'/'; 13 | if(commPath===false)commPath=name; 14 | commPath=wu.commonDir(commPath,name); 15 | } 16 | }}); 17 | vm.run(code.slice(code.indexOf("define("))); 18 | if(commPath.length>0)commPath=commPath.slice(0,-1); 19 | console.log("Worker path: \""+commPath+"\""); 20 | return commPath; 21 | } 22 | function doConfig(configFile,cb){ 23 | let dir=path.dirname(configFile); 24 | wu.get(configFile,content=>{ 25 | let e=JSON.parse(content); 26 | let k=e.pages; 27 | k.splice(k.indexOf(wu.changeExt(e.entryPagePath)),1); 28 | k.unshift(wu.changeExt(e.entryPagePath)); 29 | let app={pages:k,window:e.global&&e.global.window,tabBar:e.tabBar,networkTimeout:e.networkTimeout}; 30 | if(e.subPackages){ 31 | app.subPackages=e.subPackages; 32 | console.log("=======================================================\nNOTICE: SubPackages exist in this package.\nDetails: ",app.subPackages,"\n======================================================="); 33 | } 34 | if(e.navigateToMiniProgramAppIdList)app.navigateToMiniProgramAppIdList=e.navigateToMiniProgramAppIdList; 35 | if(fs.existsSync(path.resolve(dir,"workers.js")))app.workers=getWorkerPath(path.resolve(dir,"workers.js")); 36 | if(e.extAppid) 37 | wu.save(path.resolve(dir,'ext.json'),JSON.stringify({extEnable:true,extAppid:e.extAppid,ext:e.ext},null,4)); 38 | if(typeof e.debug!="undefined")app.debug=e.debug; 39 | let cur=path.resolve("./file"); 40 | for(let a in e.page)if(e.page[a].window.usingComponents) 41 | for(let name in e.page[a].window.usingComponents){ 42 | let componentPath=e.page[a].window.usingComponents[name]+".html"; 43 | let file=componentPath.startsWith('/')?componentPath.slice(1):wu.toDir(path.resolve(path.dirname(a),componentPath),cur); 44 | if(!e.page[file])e.page[file]={}; 45 | if(!e.page[file].window)e.page[file].window={}; 46 | e.page[file].window.component=true; 47 | } 48 | if(fs.existsSync(path.resolve(dir,"app-service.js"))){ 49 | let matches=fs.readFileSync(path.resolve(dir,"app-service.js"),{encoding:'utf8'}).match(/\_\_wxAppCode\_\_\['[^\.]+\.json[^;]+\;/g); 50 | if(matches){ 51 | let attachInfo={}; 52 | (new VM({sandbox:{ 53 | __wxAppCode__:attachInfo 54 | }})).run(matches.join("")); 55 | for(let name in attachInfo)e.page[wu.changeExt(name,".html")]={window:attachInfo[name]}; 56 | } 57 | } 58 | let delWeight=8; 59 | for(let a in e.page){ 60 | let fileName=path.resolve(dir,wu.changeExt(a,".json")); 61 | wu.save(fileName,JSON.stringify(e.page[a].window,null,4)); 62 | if(configFile==fileName)delWeight=0; 63 | } 64 | if(app.tabBar&&app.tabBar.list) wu.scanDirByExt(dir,"",li=>{//search all files 65 | let digests=[],digestsEvent=new wu.CntEvent,rdir=path.resolve(dir); 66 | function fixDir(dir){return dir.startsWith(rdir)?dir.slice(rdir.length+1):dir;} 67 | digestsEvent.add(()=>{ 68 | for(let e of app.tabBar.list){ 69 | e.pagePath=wu.changeExt(e.pagePath); 70 | if(e.iconData){ 71 | let hash=crypto.createHash("MD5").update(e.iconData,'base64').digest(); 72 | for(let [buf,name] of digests)if(hash.equals(buf)){ 73 | delete e.iconData; 74 | e.iconPath=fixDir(name).replace(/\\/g,'/'); 75 | break; 76 | } 77 | } 78 | if(e.selectedIconData){ 79 | let hash=crypto.createHash("MD5").update(e.selectedIconData,'base64').digest(); 80 | for(let [buf,name] of digests)if(hash.equals(buf)){ 81 | delete e.selectedIconData; 82 | e.selectedIconPath=fixDir(name).replace(/\\/g,'/'); 83 | break; 84 | } 85 | } 86 | } 87 | wu.save(path.resolve(dir,'app.json'),JSON.stringify(app,null,4)); 88 | cb({[configFile]:delWeight}); 89 | }); 90 | for(let name of li){ 91 | digestsEvent.encount(); 92 | wu.get(name,data=>{ 93 | digests.push([crypto.createHash("MD5").update(data).digest(),name]); 94 | digestsEvent.decount(); 95 | },{}); 96 | } 97 | });else{ 98 | wu.save(path.resolve(dir,'app.json'),JSON.stringify(app,null,4)); 99 | cb({[configFile]:delWeight}); 100 | } 101 | }); 102 | } 103 | module.exports={doConfig:doConfig}; 104 | if(require.main===module){ 105 | wu.commandExecute(doConfig,"Split and make up weapp app-config.json file.\n\n\n\n app-config.json files to split and make up."); 106 | } 107 | -------------------------------------------------------------------------------- /wuWxapkg.js: -------------------------------------------------------------------------------- 1 | const wu=require("./wuLib.js"); 2 | const wuJs=require("./wuJs.js"); 3 | const wuCfg=require("./wuConfig.js"); 4 | const wuMl=require("./wuWxml.js"); 5 | const wuSs=require("./wuWxss.js"); 6 | const path=require("path"); 7 | const fs=require("fs"); 8 | function header(buf){ 9 | console.log("\nHeader info:"); 10 | let firstMark=buf.readUInt8(0); 11 | console.log(" firstMark: 0x%s",firstMark.toString(16)); 12 | let unknownInfo=buf.readUInt32BE(1); 13 | console.log(" unknownInfo: ",unknownInfo); 14 | let infoListLength=buf.readUInt32BE(5); 15 | console.log(" infoListLength: ",infoListLength); 16 | let dataLength=buf.readUInt32BE(9); 17 | console.log(" dataLength: ",dataLength); 18 | let lastMark=buf.readUInt8(13); 19 | console.log(" lastMark: 0x%s",lastMark.toString(16)); 20 | if(firstMark!=0xbe||lastMark!=0xed)throw Error("Magic number is not correct!"); 21 | return [infoListLength,dataLength]; 22 | } 23 | function genList(buf){ 24 | console.log("\nFile list info:"); 25 | let fileCount=buf.readUInt32BE(0); 26 | console.log(" fileCount: ",fileCount); 27 | let fileInfo=[],off=4; 28 | for(let i=0;i{ 53 | wu.addIO(()=>{ 54 | console.log("Split and make up done."); 55 | if(!order.includes("d")){ 56 | console.log("Delete files..."); 57 | wu.addIO(()=>console.log("Deleted.\n\nFile done.")); 58 | for(let name in needDelete)if(needDelete[name]>=8)wu.del(name); 59 | } 60 | cb(); 61 | }); 62 | }); 63 | function doBack(deletable){ 64 | for(let key in deletable){ 65 | if(!needDelete[key])needDelete[key]=0; 66 | needDelete[key]+=deletable[key];//all file have score bigger than 8 will be delete. 67 | } 68 | weappEvent.decount(); 69 | } 70 | //This will be the only func running this time, so async is needless. 71 | if(fs.existsSync(path.resolve(dir,"app-service.js"))){//weapp 72 | console.log("Split app-service.js and make up configs & wxss & wxml & wxs..."); 73 | wuCfg.doConfig(path.resolve(dir,"app-config.json"),doBack); 74 | wuJs.splitJs(path.resolve(dir,"app-service.js"),doBack); 75 | if(fs.existsSync(path.resolve(dir,"workers.js"))) 76 | wuJs.splitJs(path.resolve(dir,"workers.js"),doBack); 77 | if(fs.existsSync(path.resolve(dir,"page-frame.html"))) 78 | wuMl.doFrame(path.resolve(dir,"page-frame.html"),doBack,order); 79 | else if(fs.existsSync(path.resolve(dir,"app-wxss.js"))) { 80 | wuMl.doFrame(path.resolve(dir,"app-wxss.js"),doBack,order); 81 | if(!needDelete[path.resolve(dir,"page-frame.js")])needDelete[path.resolve(dir,"page-frame.js")]=8; 82 | } else throw Error("page-frame-like file is not found in the package by auto."); 83 | wuSs.doWxss(dir,doBack);//Force it run at last, becuase lots of error occured in this part 84 | }else if(fs.existsSync(path.resolve(dir,"game.js"))){//wegame 85 | console.log("Split game.js and rewrite game.json..."); 86 | let gameCfg=path.resolve(dir,"app-config.json"); 87 | wu.get(gameCfg,cfgPlain=>{ 88 | let cfg=JSON.parse(cfgPlain); 89 | if(cfg.subContext){ 90 | console.log("Found subContext, splitting it...") 91 | delete cfg.subContext; 92 | let contextPath=path.resolve(dir,"subContext.js"); 93 | wuJs.splitJs(contextPath,()=>wu.del(contextPath)); 94 | } 95 | wu.save(path.resolve(dir,"game.json"),JSON.stringify(cfg,null,4)); 96 | wu.del(gameCfg); 97 | }); 98 | wuJs.splitJs(path.resolve(dir,"game.js"),()=>{ 99 | wu.addIO(()=>{ 100 | console.log("Split and rewrite done."); 101 | cb(); 102 | }); 103 | }); 104 | }else throw Error("This package is unrecognizable.\nMay be this package is a subPackage which should be unpacked with -s=.\nOtherwise, please decrypted every type of file by hand.") 105 | } 106 | function doFile(name,cb,order){ 107 | for(let ord of order)if(ord.startsWith("s="))global.subPack=ord.slice(3); 108 | console.log("Unpack file "+name+"..."); 109 | let dir=path.resolve(name,"..",path.basename(name,".wxapkg")); 110 | wu.get(name,buf=>{ 111 | let [infoListLength,dataLength]=header(buf.slice(0,14)); 112 | if(order.includes("o"))wu.addIO(console.log.bind(console),"Unpack done."); 113 | else wu.addIO(packDone,dir,cb,order); 114 | saveFile(dir,buf,genList(buf.slice(14,infoListLength+14))); 115 | },{}); 116 | } 117 | module.exports={doFile:doFile}; 118 | if(require.main===module){ 119 | wu.commandExecute(doFile,"Unpack a wxapkg file.\n\n[-o] [-d] [-s=
] \n\n-d Do not delete transformed unpacked files.\n-o Do not execute any operation after unpack.\n-s=
Regard all packages provided as subPackages and\n regard
as the directory of sources of the main package.\n wxapkg files to unpack"); 120 | } 121 | -------------------------------------------------------------------------------- /wuLib.js: -------------------------------------------------------------------------------- 1 | const fs=require("fs"); 2 | const path=require("path"); 3 | class CntEvent{ 4 | constructor(){ 5 | this.cnt=0; 6 | this.emptyEvent=[]; 7 | this.encount=this.encount.bind(this); 8 | this.decount=this.decount.bind(this); 9 | this.add=this.add.bind(this); 10 | } 11 | encount(delta=1){ 12 | this.cnt+=delta; 13 | } 14 | decount(){ 15 | if(this.cnt>0)--this.cnt; 16 | if(this.cnt==0){ 17 | for(let info of this.emptyEvent)info[0](...info[1]); 18 | this.emptyEvent=[]; 19 | } 20 | } 21 | add(cb,...attach){ 22 | this.emptyEvent.push([cb,attach]); 23 | } 24 | check(cb,...attach){ 25 | if(this.cnt==0)cb(...attach); 26 | else this.add(cb,...attach); 27 | } 28 | } 29 | class LimitedRunner{ 30 | constructor(limit){ 31 | this.limit=limit; 32 | this.cnt=0; 33 | this.funcs=[]; 34 | } 35 | run(func){ 36 | if(this.cnt0)this.cnt--; 45 | if(this.funcs.length>0){ 46 | this.cnt++; 47 | setTimeout(this.funcs.shift(),0); 48 | } 49 | } 50 | runWithCb(func,...args){ 51 | let cb=args.pop(),self=this; 52 | function agent(...args){ 53 | self.done(); 54 | return cb.apply(this,args); 55 | } 56 | args.push(agent); 57 | this.run(()=>func(...args)); 58 | } 59 | } 60 | let ioEvent=new CntEvent; 61 | let ioLimit=new LimitedRunner(4096); 62 | function mkdirs(dir,cb){ 63 | ioLimit.runWithCb(fs.stat.bind(fs),dir,(err,stats)=>{ 64 | if(err)mkdirs(path.dirname(dir),()=>fs.mkdir(dir,cb)); 65 | else if(stats.isFile())throw Error(dir+" was created as a file, so we cannot put file into it."); 66 | else cb(); 67 | }); 68 | } 69 | function save(name,content){ 70 | ioEvent.encount(); 71 | mkdirs(path.dirname(name),()=>ioLimit.runWithCb(fs.writeFile.bind(fs),name,content,err=>{ 72 | if(err)throw Error("Save file error: "+err); 73 | ioEvent.decount(); 74 | })); 75 | } 76 | function get(name,cb,opt={encoding:'utf8'}){ 77 | ioEvent.encount(); 78 | ioLimit.runWithCb(fs.readFile.bind(fs),name,opt,(err,data)=>{ 79 | if(err)throw Error("Read file error: "+err); 80 | else cb(data); 81 | ioEvent.decount(); 82 | }); 83 | } 84 | function del(name){ 85 | ioEvent.encount(); 86 | ioLimit.runWithCb(fs.unlink.bind(fs),name,ioEvent.decount); 87 | } 88 | function changeExt(name,ext=""){ 89 | return name.slice(0,name.lastIndexOf("."))+ext; 90 | } 91 | function scanDirByExt(dir,ext,cb){ 92 | let result=[],scanEvent=new CntEvent; 93 | function helper(dir){ 94 | scanEvent.encount(); 95 | ioLimit.runWithCb(fs.readdir.bind(fs),dir,(err,files)=>{ 96 | if(err)throw Error("Scan dir error: "+err); 97 | for(let file of files){ 98 | scanEvent.encount(); 99 | let name=path.resolve(dir,file); 100 | fs.stat(name,(err,stats)=>{ 101 | if(err)throw Error("Scan dir error: "+err); 102 | if(stats.isDirectory())helper(name); 103 | else if(stats.isFile()&&name.endsWith(ext))result.push(name); 104 | scanEvent.decount(); 105 | }); 106 | } 107 | scanEvent.decount(); 108 | }); 109 | } 110 | scanEvent.add(cb,result); 111 | helper(dir,ext,scanEvent); 112 | } 113 | function toDir(to,from){//get relative path without posix/win32 problem 114 | if(from[0]==".")from=from.slice(1); 115 | if(to[0]==".")to=to.slice(1); 116 | from=from.replace(/\\/g,'/');to=to.replace(/\\/g,'/'); 117 | let a=Math.min(to.length,from.length); 118 | for(let i=1,m=Math.min(to.length,from.length);i<=m;i++)if(!to.startsWith(from.slice(0,i))){a=i-1;break;} 119 | let pub=from.slice(0,a); 120 | let len=pub.lastIndexOf("/")+1; 121 | let k=from.slice(len); 122 | let ret=""; 123 | for(let i=0;iconsole.timeEnd("Total use")); 140 | } 141 | let orders=[]; 142 | for(let order of process.argv)if(order.startsWith("-"))orders.push(order.slice(1)); 143 | let iter=process.argv[Symbol.iterator](),nxt=iter.next(),called=false,faster=orders.includes("f"),fastCnt; 144 | if(faster){ 145 | fastCnt=new CntEvent; 146 | fastCnt.add(endTime); 147 | } 148 | function doNext(){ 149 | let nxt=iter.next(); 150 | while(!nxt.done&&nxt.value.startsWith("-"))nxt=iter.next(); 151 | if(nxt.done){ 152 | if(!called)console.log("Command Line Helper:\n\n"+helper); 153 | else if(!faster)endTime(); 154 | }else{ 155 | called=true; 156 | if(faster)fastCnt.encount(),cb(nxt.value,fastCnt.decount,orders),doNext(); 157 | else cb(nxt.value,doNext,orders); 158 | } 159 | } 160 | while(!nxt.done&&!nxt.value.endsWith(".js"))nxt=iter.next(); 161 | doNext(); 162 | } 163 | module.exports={mkdirs:mkdirs,get:get,save:save,toDir:toDir,del:del,addIO:ioEvent.add, 164 | changeExt:changeExt,CntEvent:CntEvent,scanDirByExt:scanDirByExt,commonDir:commonDir, 165 | commandExecute:commandExecute}; 166 | -------------------------------------------------------------------------------- /wuRestoreZ.js: -------------------------------------------------------------------------------- 1 | const wu=require("./wuLib.js"); 2 | const {VM}=require('vm2'); 3 | function catchZGroup(code,groupPreStr,cb){ 4 | const debugPre="(function(z){var a=11;function Z(ops,debugLine){"; 5 | let zArr={}; 6 | for(let preStr of groupPreStr){ 7 | let content=code.slice(code.indexOf(preStr)),z=[]; 8 | content=content.slice(content.indexOf("(function(z){var a=11;")); 9 | content=content.slice(0,content.indexOf("})(__WXML_GLOBAL__.ops_cached.$gwx"))+"})(z);"; 10 | let vm=new VM({sandbox:{z:z,debugInfo:[]}}); 11 | vm.run(content); 12 | if(content.startsWith(debugPre))for(let i=0;i=":11,"<=":11,">":11,"<":11,"<<":12,">>":12, 98 | "-":len==3?13:16 99 | }; 100 | return priorList[op]?priorList[op]:0; 101 | } 102 | function getOp(i){ 103 | let ret=restoreNext(ops[i],true); 104 | if(ops[i] instanceof Object&&typeof ops[i][0]=="object"&&ops[i][0][0]==2){ 105 | //Add brackets if we need 106 | if(getPrior(op[1],ops.length)>getPrior(ops[i][0][1],ops[i].length))ret=enBrace(ret,'(');; 107 | } 108 | return ret; 109 | } 110 | switch(op[1]){ 111 | case"?:": 112 | ans=getOp(1)+"?"+getOp(2)+":"+getOp(3); 113 | break; 114 | case "!": 115 | case "~": 116 | ans=op[1]+getOp(1); 117 | break; 118 | case"-": 119 | if(ops.length!=3){ 120 | ans=op[1]+getOp(1); 121 | break; 122 | }//shoud not add more in there![fall through] 123 | default: 124 | ans=getOp(1)+op[1]+getOp(2); 125 | } 126 | break; 127 | } 128 | case 4://unkown-arrayStart? 129 | ans=restoreNext(ops[1],true); 130 | break; 131 | case 5://merge-array 132 | { 133 | switch (ops.length) { 134 | case 2: 135 | ans=enBrace(restoreNext(ops[1],true),'['); 136 | break; 137 | case 1: 138 | ans='[]'; 139 | break; 140 | default: 141 | { 142 | let a=restoreNext(ops[1],true); 143 | //console.log(a,a.startsWith('[')&&a.endsWith(']')); 144 | if(a.startsWith('[')&&a.endsWith(']')){ 145 | if(a!='[]'){ 146 | ans=enBrace(a.slice(1,-1).trim()+','+restoreNext(ops[2],true),'['); 147 | //console.log('-',a); 148 | }else{ 149 | ans=enBrace(restoreNext(ops[2],true),'['); 150 | } 151 | }else{ 152 | ans=enBrace('...'+a+','+restoreNext(ops[2],true),'[');//may/must not support in fact 153 | } 154 | } 155 | } 156 | break; 157 | } 158 | case 6://get value of an object 159 | { 160 | let sonName=restoreNext(ops[2],true); 161 | if(sonName._type==="var") 162 | ans=restoreNext(ops[1],true)+enBrace(sonName,'['); 163 | else{ 164 | let attach=""; 165 | if(/^[A-Za-z\_][A-Za-z\d\_]*$/.test(sonName)/*is a qualified id*/) 166 | attach='.'+sonName; 167 | else attach=enBrace(sonName,'['); 168 | ans=restoreNext(ops[1],true)+attach; 169 | } 170 | break; 171 | } 172 | case 7://get value of str 173 | { 174 | switch(ops[1][0]){ 175 | case 11: 176 | ans=enBrace("__unTestedGetValue:"+enBrace(jsoToWxon(ops),'['),'{'); 177 | break; 178 | case 3: 179 | ans=new String(ops[1][1]); 180 | ans._type="var"; 181 | break; 182 | default: 183 | throw Error("Unknown type to get value"); 184 | } 185 | break; 186 | } 187 | case 8://first object 188 | ans=enBrace(ops[1]+':'+restoreNext(ops[2],true),'{');//ops[1] have only this way to define 189 | break; 190 | case 9://object 191 | { 192 | function type(x){ 193 | if(x.startsWith('...'))return 1; 194 | if(x.startsWith('{')&&x.endsWith('}'))return 0; 195 | return 2; 196 | } 197 | let a=restoreNext(ops[1],true); 198 | let b=restoreNext(ops[2],true); 199 | let xa=type(a),xb=type(b); 200 | if(xa==2||xb==2)ans=enBrace("__unkownMerge:"+enBrace(a+","+b,'['),'{'); 201 | else{ 202 | if(!xa)a=a.slice(1,-1).trim(); 203 | if(!xb)b=b.slice(1,-1).trim(); 204 | //console.log(l,r); 205 | ans=enBrace(a+','+b,'{'); 206 | } 207 | break; 208 | } 209 | case 10://...object 210 | ans='...'+restoreNext(ops[1],true); 211 | break; 212 | case 12: 213 | { 214 | let arr=restoreNext(ops[2],true); 215 | if(arr.startsWith('[')&&arr.endsWith(']')) 216 | ans=restoreNext(ops[1],true)+enBrace(arr.slice(1,-1).trim(),'('); 217 | else ans=restoreNext(ops[1],true)+'.apply'+enBrace('null,'+arr,'('); 218 | break; 219 | } 220 | default: 221 | ans=enBrace("__unkownSpecific:"+jsoToWxon(ops),'{'); 222 | } 223 | return scope(ans); 224 | } 225 | } 226 | function restoreGroup(z){ 227 | let ans=[]; 228 | for(let g in z.mul){ 229 | let singleAns=[]; 230 | for(let e of z.mul[g])singleAns.push(restoreSingle(e,false)); 231 | ans[g]=singleAns; 232 | } 233 | let ret=[];//Keep a null array for remaining global Z array. 234 | ret.mul=ans; 235 | return ret; 236 | } 237 | function restoreAll(z){ 238 | if(z.mul)return restoreGroup(z); 239 | let ans=[]; 240 | for(let e of z)ans.push(restoreSingle(e,false)); 241 | return ans; 242 | } 243 | module.exports={getZ(code,cb){ 244 | catchZ(code,z=>cb(restoreAll(z))); 245 | }}; 246 | -------------------------------------------------------------------------------- /DETAILS.md: -------------------------------------------------------------------------------- 1 | # 关于还原的详细信息 2 | 3 | ### wxapkg 包 4 | 5 | 对于 wxapkg 包文件格式的分析已在网上广泛流传,可整理为如下内容(请注意该文件中的`uint32`都是以`大端序`方式存放): 6 | 7 | ```c++ 8 | typedef unsigned char uint8; 9 | typedef unsigned int uint32;//Notice: uint32 use BIG-ENDIAN, not Little. 10 | 11 | struct wxHeader { 12 | uint8 firstMark;// one of magic number, which is equal to 0xbe 13 | uint32 unknownInfo;// this info was always set to zero. maybe it's the verison of file? 14 | uint32 infoListLength;// the length of wxFileInfoList 15 | uint32 dataLength;// the length of dataBuf 16 | uint8 lastMark;// another magic number, which is equal to 0xed 17 | }; 18 | 19 | struct wxFileInfo {// illustrate one file in wxapkg pack 20 | uint32 nameLen;// the length of filename 21 | char name[nameLen];// filename, use UTF-8 encoding (translating it to GBK is required in Win) 22 | uint32 fileOff;// the offset of this file (0 is pointing to the begining of this file[struct wxapkgFile]) 23 | uint32 fileLen;// the length of this file 24 | }; 25 | 26 | struct wxFileInfoList { 27 | uint32 fileCount;// The count of file 28 | wxFileInfo fileInfos[fileCount]; 29 | }; 30 | 31 | struct wxapkgFile { 32 | wxHeader header; 33 | wxFileInfoList fileInfoList; 34 | uint8 dataBuf[dataLength]; 35 | }; 36 | ``` 37 | 38 | 由上可知,在wxapkg 包中文件头后的位置上有`文件名+文件内容起始地址及长度`信息,且各个文件内容也全是以明文方式存放在包内,从而我们可以获取包内文件。 39 | 40 | 通过解包可知,这个包中的文件内容主要如下: 41 | 42 | - app-config.json 43 | - app-service.js 44 | - page-frame.html ( 也可能是由 app-wxss.js 和 page-frame.js 组成相关信息 ) 45 | - 其他一堆放在各文件夹中的.html文件 46 | - 和源码包内位置和内容相同的图片等资源文件 47 | 48 | 微信开发者工具并不能识别这些文件,它要求我们提供由`wxml/wxss/js/wxs/json`组成的源码才能进行模拟/调试。 49 | 50 | ### js 51 | 52 | 注意到`app-service.js`中的内容由 53 | 54 | ```javascript 55 | define('xxx.js',function(...){ 56 | //The content of xxx.js 57 | });require('xxx.js'); 58 | define('yyy.js',function(...){ 59 | //The content of xxx.js 60 | });require('yyy.js'); 61 | .... 62 | ``` 63 | 64 | 组成,很显然,我们只要定义自己的`define`函数就可以将这些 js 文件恢复到源码中所对应的位置。当然,这些 js 文件中的内容经过压缩,即使使用 UglifyJS 这样的工具进行美化,也无法还原一些原始变量名。 65 | 66 | ### wxss 67 | 68 | 所有在 wxapkg 包中的 html 文件都调用了`setCssToHead`函数,其代码如下 69 | 70 | ```javascript 71 | var setCssToHead = function(file, _xcInvalid) { 72 | var Ca = {}; 73 | var _C = [...arrays...]; 74 | function makeup(file, suffix) { 75 | var _n = typeof file === "number"; 76 | if (_n && Ca.hasOwnProperty(file)) return ""; 77 | if (_n) Ca[file] = 1; 78 | var ex = _n ? _C[file] : file; 79 | var res = ""; 80 | for (var i = ex.length - 1; i >= 0; i--) { 81 | var content = ex[i]; 82 | if (typeof content === "object") { 83 | var op = content[0]; 84 | if (op == 0) res = transformRPX(content[1]) + "px" + res; else if (op == 1) res = suffix + res; else if (op == 2) res = makeup(content[1], suffix) + res; 85 | } else res = content + res; 86 | } 87 | return res; 88 | } 89 | return function(suffix, opt) { 90 | if (typeof suffix === "undefined") suffix = ""; 91 | if (opt && opt.allowIllegalSelector != undefined && _xcInvalid != undefined) { 92 | if (opt.allowIllegalSelector) console.warn("For developer:" + _xcInvalid); else { 93 | console.error(_xcInvalid + "This wxss file is ignored."); 94 | return; 95 | } 96 | } 97 | Ca = {}; 98 | css = makeup(file, suffix); 99 | var style = document.createElement("style"); 100 | var head = document.head || document.getElementsByTagName("head")[0]; 101 | style.type = "text/css"; 102 | if (style.styleSheet) { 103 | style.styleSheet.cssText = css; 104 | } else { 105 | style.appendChild(document.createTextNode(css)); 106 | } 107 | head.appendChild(style); 108 | }; 109 | }; 110 | ``` 111 | 112 | 阅读这段代码可知,它把 wxss 代码拆分成几段数组,数组中的内容可以是一段将要作为 css 文件的字符串,也可以是一个表示 这里要添加一个公共后缀 或 这里要包含另一段代码 或 要将以 wxss 专供的 rpx 单位表达的数字换算成能由浏览器渲染的 px 单位所对应的数字 的数组。 113 | 114 | 同时,它还将所有被`@import`引用的 wxss 文件所对应的数组内嵌在该函数中的 _C 变量中。 115 | 116 | 我们可以修改`setCssToHead`,然后执行所有的`setCssToHead`,第一遍先判断出 _C 变量中所有的内容是哪个要被引用的 wxss 提供的,第二遍还原所有的 wxss。值得注意的是,可能出于兼容性原因,微信为很多属性自动补上含有`-webkit-`开头的版本,另外几乎所有的 tag 都加上了`wx-`前缀,并将`page`变成了`body`。通过一些 CSS 的 AST ,例如 [CSSTree](https://github.com/csstree/csstree),我们可以去掉这些东西。 117 | 118 | ### json 119 | 120 | app-config.json 中的`page`对象内就是其他各页面所对应的 json , 直接还原即可,余下的内容便是 app.json 中的内容了,除了格式上要作相应转换外,微信还将`iconPath`的内容由原先指向图片文件的地址转换成`iconData`中图片内容的 base64 编码,所幸原来的图片文件仍然保留在包内,通过比较`iconData`中的内容和其他包内文件,我们找到原始的`iconPath`。 121 | 122 | ### wxs 123 | 124 | 在 page-frame.html ( 或 app-wxss.js ) 中,我们找到了这样的内容 125 | 126 | ```javascript 127 | f_['a/comm.wxs'] = nv_require("p_a/comm.wxs"); 128 | function np_0(){var nv_module={nv_exports:{}};nv_module.nv_exports = ({nv_bar:nv_some_msg,});return nv_module.nv_exports;} 129 | 130 | f_['b/comm.wxs'] = nv_require("p_b/comm.wxs"); 131 | function np_1(){var nv_module={nv_exports:{}};nv_module.nv_exports = ({nv_bar:nv_some_msg,});return nv_module.nv_exports;} 132 | 133 | f_['b/index.wxml']={}; 134 | f_['b/index.wxml']['foo'] =nv_require("m_b/index.wxml:foo"); 135 | function np_2(){var nv_module={nv_exports:{}};var nv_some_msg = "hello world";nv_module.nv_exports = ({nv_msg:nv_some_msg,});return nv_module.nv_exports;} 136 | f_['b/index.wxml']['some_comms'] =f_['b/comm.wxs'] || nv_require("p_b/comm.wxs"); 137 | f_['b/index.wxml']['some_comms'](); 138 | f_['b/index.wxml']['some_commsb'] =f_['a/comm.wxs'] || nv_require("p_a/comm.wxs"); 139 | f_['b/index.wxml']['some_commsb'](); 140 | ``` 141 | 142 | 可以看出微信将内嵌和外置的 wxs 都转译成`np_%d`函数,并由`f_`数组来描述他们。转译的主要变换是调用的函数名称都加上了`nv_`前缀。在不严谨的场合,我们可以直接通过文本替换去除这些前缀。 143 | 144 | ### wxml 145 | 146 | 相比其他内容,这一段比较复杂,因为微信将原本 类 xml 格式的 wxml 文件直接编译成了 js 代码放入 page-frame.html ( 或 app-wxss.js ) 中,之后通过调用这些代码来构造 virtual-dom,进而渲染网页。 147 | 首先,微信将所有要动态计算的变量放在了一个由函数构造的`z`数组中,构造部分代码如下: 148 | 149 | ```javascript 150 | (function(z){var a=11;function Z(ops){z.push(ops)} 151 | Z([3,'index']); 152 | Z([[8],'text',[[4],[[5],[[5],[[5],[1,1]],[1,2]],[1,3]]]]); 153 | })(z); 154 | ``` 155 | 156 | 其实可以将`[[id],xxx,yyy]`看作由指令与操作数的组合。注意每个这样的数组作为指令所产生的结果会作为外层数组中的操作数,这样可以构成一个树形结构。通过将递归计算的过程改成拼接源代码字符串的过程,我们可以还原出每个数组所对应的实际内容(值得注意的是,由于微信的`Token`解析程序采用了贪心算法,我们必须将连续的`}`翻译为`} }`而非`}}`,否则会被误认为是`Mustache`的结束符)。下文中,将这个数组中记为`z`。 157 | 158 | 然后,对于 wxml 文件的结构,可以将每种可能的 js 语句拆分成 指令 来分析,这里可以用到 [Esprima](https://github.com/jquery/esprima) 这样的 js 的 AST 来简化识别操作,可以很容易分析出以下内容,例如: 159 | 160 | - `var {name}=_n('{tag}')` 创建名称为`{name}`, tag 为`{tag}`的节点。 161 | - `_r({name},'{attrName}',{id},e,s,gg)` 将`{name}`的`{attrName}`属性修改为`z[{id}]`的值。 162 | - `_({parName},{name})` 将`{name}`作为`{parName}`的子节点。 163 | - `var {name}=_o({id},..,..,..)` 创建名称为`{name}`,内容为`z[{id}]`的文本节点。 164 | - `var {name}=_v()` 创建名称为`{name}`的虚节点( wxml 里恰好提供了功能相当的虚结点`block`, 这句话相当于`var {name}=_n('block')`)。 165 | - `var {name}=_m('{tag}',['{attrName1}',{id1},'{attrName2}',{id2},...],[],..,..,..)` 创建名称为`{name}`, tag 为`{tag}`的节点,同时将`{attrNameX}`属性修改为`z[f({idX})]`的值(`f`定义为`{idX}`与`{base}`的和;`{base}`初始为`0`,`f`返回的第一个正值后`{base}`即改为该返回值;若返回负值,表示该属性无值)。 166 | - `return {name}` 名称为`{name}`的节点设为主节点。 167 | - `cs.***` 调试用语句,无视之。 168 | 169 | 此外`wx:if`结构和`wx:for`可做递归处理。例如,对于如下`wx:if`结构: 170 | 171 | ```javascript 172 | var {name}=_v() 173 | _({parName},{name}) 174 | if(_o({id1},e,s,gg)){oD.wxVkey=1 175 | //content1 176 | } 177 | else if(_o({id2},e,s,gg)){oD.wxVkey=2 178 | //content2 179 | } 180 | else{oD.wxVkey=3 181 | //content3 182 | } 183 | ``` 184 | 185 | 相当于将以下节点放入`{parName}`节点下(`z[{id1}]`应替换为对应的`z`数组中的值): 186 | 187 | ```xml 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | ``` 198 | 199 | 具体实现中可以将递归时创建好多个`block`,调用子函数时指明将放入`{name}`下(`_({name},{son})`)识别为放入对应`{block}`下。`wx:for`也可类似处理,例如: 200 | 201 | ```javascript 202 | var {name}=_v() 203 | _({parName},{name}) 204 | var {funcName}=function(..,..,{fakeRoot},..){ 205 | //content 206 | return {fakeRoot} 207 | } 208 | aDB.wxXCkey=2 209 | _2({id},{funcName},..,..,..,..,'{item}','{index}','{key}') 210 | ``` 211 | 212 | 对应(`z[{id1}]`应替换为对应的`z`数组中的值): 213 | 214 | ```xml 215 | 216 | 217 | 218 | ``` 219 | 220 | 调用子函数时指明将放入`{fakeRoot}`下(`_({fakeRoot},{son})`)识别为放入`{name}`下。 221 | 222 | 除此之外,有时我们还要将一组代码标记为一个指令,例如下面: 223 | 224 | ```javascript 225 | var lK=_v() 226 | _({parName},lK) 227 | var aL=_o({isId},e,s,gg) 228 | var tM=_gd(x[0],aL,e_,d_) 229 | if(tM){ 230 | var eN=_1({dataId},e,s,gg) || {} 231 | var cur_globalf=gg.f 232 | lK.wxXCkey=3 233 | tM(eN,eN,lK,gg) 234 | gg.f=cur_globalf 235 | } 236 | else _w(aL,x[0],11,26) 237 | ``` 238 | 239 | 对应于`{parName}`下添加如下节点: 240 | 241 | ```xml 242 | 243 | ``` 244 | 245 | 还有`import`和`include`的代码比较分散,但其实只要抓住重点的一句话就可以了,例如: 246 | 247 | ```javascript 248 | var {name}=e_[x[{to}]].i 249 | //Other code 250 | _ai({name},x[{from}],e_,x[{to}],..,..) 251 | //Other code 252 | {name}.pop() 253 | ``` 254 | 255 | 对应与(其中的`x`是直接定义在 page-frame.html ( 或 app-wxss.js ) 中的字符串数组): 256 | 257 | ```xml 258 | 259 | ``` 260 | 261 | 而`include`类似: 262 | 263 | ```javascript 264 | var {name}=e_[x[0]].j 265 | //Other code 266 | _ic(x[{from}],e_,x[{to}],..,..,..,..); 267 | //Other code 268 | {name}.pop() 269 | ``` 270 | 271 | 对应与: 272 | 273 | ```xml 274 | 275 | ``` 276 | 277 | 可以看到我们可以在处理时忽略前后两句话,把中间的`_ic`和`_ai`处理好就行了。 278 | 279 | 通过解析 js 把 wxml 大概结构还原后,可能相比编译前的 wxml 显得臃肿,可以考虑自动简化,例如: 280 | 281 | ```xml 282 | 283 | 284 | 285 | 286 | 287 | ``` 288 | 289 | 可简化为: 290 | 291 | ```xml 292 | 293 | 294 | 295 | ``` 296 | 297 | 这样,我们完成了几乎所有 wxapkg包 内容的还原。 298 | 299 | ### 对`z`数组优化后的支持方法 300 | 301 | `wcc-v0.5vv_20180626_syb_zp`后通过只加载`z`数组中需要的部分来提高小程序运行速度,这也会导致仅考虑到上述内容的解包程序解包失败,这一更新的主要内容如下: 302 | 303 | - 增加z数组的函数:`_rz` `_2z` `_mz` `_1z` `_oz` 304 | - 在每个函数头部增加了`var z=gz$gwx_{$id}()`,来标识使用的z数组id 305 | - 原有的z数组不再存在 306 | - z数组已以下固定格式出现: 307 | 308 | ```javascript 309 | function gz$gwx_{$id}(){ 310 | if( __WXML_GLOBAL__.ops_cached.$gwx_{$id})return __WXML_GLOBAL__.ops_cached.$gwx_{$id} 311 | __WXML_GLOBAL__.ops_cached.$gwx_{$id}=[]; 312 | (function(z){var a=11;function Z(ops){z.push(ops)} 313 | 314 | //... (Z({$content})) 315 | 316 | })(__WXML_GLOBAL__.ops_cached.$gwx_{$id});return __WXML_GLOBAL__.ops_cached.$gwx_{$id} 317 | } 318 | ``` 319 | 320 | 对于上述变更,将获取`z`数组处修改并添加对`_rz` `_2z` `_mz` `_1z` `_oz`的支持即可。 321 | 322 | 需要注意的是开发版的`z`数组转为如下结构: 323 | 324 | ```javascript 325 | (function(z){var a=11;function Z(ops,debugLine){z.push(['11182016',ops,debugLine])} 326 | //... 327 | })//... 328 | ``` 329 | 330 | 探测到为开发版后应将获取到的`z`数组仅保留数组中的第二项。 331 | 332 | 以及含分包的子包采用 `gz$gwx{$subPackageId}_{$id}` 命名,其中`{$subPackageId}`是一个数字。 333 | 334 | 另外还需要注意,`template`的 `var z=gz$gwx_{$id}` 在`try`块外。 -------------------------------------------------------------------------------- /wuWxss.js: -------------------------------------------------------------------------------- 1 | const wu=require("./wuLib.js"); 2 | const path=require("path"); 3 | const fs=require("fs"); 4 | const {VM}=require('vm2'); 5 | const cssbeautify=require('cssbeautify'); 6 | const csstree=require('css-tree'); 7 | const cheerio = require('cheerio'); 8 | function chomp_balanced(input_str, scan_start, open_char, close_char) { 9 | quote_chars = ['\"', '\'']; 10 | let now = scan_start - 1; 11 | let depth = 0; 12 | let in_quote = false; 13 | let start = -1; 14 | let end = -1; 15 | let end_index = input_str.length - 1; 16 | let now_quote_char = undefined; 17 | let c = undefined; 18 | let last_char = undefined; 19 | 20 | let escape_char = '\\'; 21 | while (true) { 22 | now += 1; 23 | if (now > end_index) { 24 | break 25 | } 26 | last_char = c; 27 | c = input_str[now]; 28 | if (quote_chars.indexOf(c) > -1 && c !== open_char) { 29 | if (in_quote && c === now_quote_char && last_char !== escape_char) { 30 | in_quote = false; 31 | now_quote_char = undefined 32 | } else { 33 | if (!in_quote) { 34 | now_quote_char = c; 35 | } 36 | in_quote = true; 37 | } 38 | continue; 39 | } 40 | if (in_quote) { 41 | continue; 42 | } 43 | 44 | if (open_char !== close_char) { 45 | if (c === open_char) { 46 | depth += 1; 47 | if (start === -1) { 48 | start = now 49 | } 50 | // let left = input_str.substr(now); 51 | // console.log(left); 52 | } else if (c === close_char) { 53 | depth -= 1; 54 | if (depth === 0) { 55 | end = now; 56 | break; 57 | } 58 | } 59 | 60 | } else { 61 | //开闭相同的时候,相同即可退出 62 | if (c === open_char) { 63 | depth += 1; 64 | if (start === -1) { 65 | start = now 66 | } 67 | if (depth === 2) { 68 | // 开闭相同,这个时候就满足条件了 69 | end = now; 70 | break 71 | } 72 | } 73 | } 74 | } 75 | if (start >= 0 && end > 0) { 76 | return { 77 | start: start, 78 | end: end 79 | } 80 | 81 | } 82 | return undefined; 83 | } 84 | 85 | function doWxss(dir,cb){ 86 | function GwxCfg(){} 87 | GwxCfg.prototype={$gwx(){}}; 88 | for(let i=0;i<300;i++)GwxCfg.prototype["$gwx"+i]=GwxCfg.prototype.$gwx; 89 | let runList={},pureData={},result={},actualPure={},importCnt={},frameName="",onlyTest=true,blockCss=[];//custom block css file which won't be imported by others.(no extension name) 90 | function cssRebuild(data){//need to bind this as {cssFile:__name__} before call 91 | let cssFile; 92 | function statistic(data){ 93 | function addStat(id){ 94 | if(!importCnt[id])importCnt[id]=1,statistic(pureData[id]); 95 | else ++importCnt[id]; 96 | } 97 | if(typeof data==="number")return addStat(data); 98 | for(let content of data)if(typeof content==="object"&&content[0]==2)addStat(content[1]); 99 | } 100 | function makeup(data){ 101 | var isPure=typeof data==="number"; 102 | if(onlyTest){ 103 | statistic(data); 104 | if(!isPure){ 105 | if(data.length==1&&data[0][0]==2)data=data[0][1]; 106 | else return ""; 107 | } 108 | if(!actualPure[data]&&!blockCss.includes(wu.changeExt(wu.toDir(cssFile,frameName),""))){ 109 | console.log("Regard "+cssFile+" as pure import file."); 110 | actualPure[data]=cssFile; 111 | } 112 | return ""; 113 | } 114 | let res=[],attach=""; 115 | if(isPure&&actualPure[data]!=cssFile){ 116 | if(actualPure[data])return '@import "'+wu.changeExt(wu.toDir(actualPure[data],cssFile),".wxss")+'";\n'; 117 | else{ 118 | res.push("/*! Import by _C["+data+"], whose real path we cannot found. */"); 119 | attach="/*! Import end */"; 120 | } 121 | } 122 | let exactData=isPure?pureData[data]:data; 123 | for(let content of exactData) 124 | if(typeof content==="object"){ 125 | switch(content[0]){ 126 | case 0://rpx 127 | res.push(content[1]+"rpx"); 128 | break; 129 | case 1://add suffix, ignore it for restoring correct! 130 | break; 131 | case 2://import 132 | res.push(makeup(content[1])); 133 | break; 134 | } 135 | }else res.push(content); 136 | return res.join("")+attach; 137 | } 138 | return ()=>{ 139 | cssFile=this.cssFile; 140 | if(!result[cssFile])result[cssFile]=""; 141 | result[cssFile]+=makeup(data); 142 | }; 143 | } 144 | function runVM(name,code){ 145 | let wxAppCode={},handle={cssFile:name}; 146 | let vm=new VM({sandbox:Object.assign(new GwxCfg(),{__wxAppCode__:wxAppCode,setCssToHead:cssRebuild.bind(handle)})}); 147 | vm.run(code); 148 | for(let name in wxAppCode)if(name.endsWith(".wxss")){ 149 | handle.cssFile=path.resolve(frameName,"..",name); 150 | wxAppCode[name](); 151 | } 152 | } 153 | function preRun(dir,frameFile,mainCode,files,cb){ 154 | wu.addIO(cb); 155 | runList[path.resolve(dir,"./app.wxss")]=mainCode; 156 | for(let name of files)if(name!=frameFile){ 157 | wu.get(name,code=>{ 158 | code=code.slice(0,code.indexOf("\n")); 159 | if(code.indexOf("setCssToHead")>-1)runList[name]=code.slice(code.indexOf("setCssToHead")); 160 | }); 161 | } 162 | } 163 | function runOnce(){ 164 | for(let name in runList)runVM(name,runList[name]); 165 | } 166 | function transformCss(style){ 167 | let ast=csstree.parse(style); 168 | csstree.walk(ast,function(node){ 169 | if(node.type=="Comment"){//Change the comment because the limit of css-tree 170 | node.type="Raw"; 171 | node.value="\n/*"+node.value+"*/\n"; 172 | } 173 | if(node.type=="TypeSelector"){ 174 | if(node.name.startsWith("wx-"))node.name=node.name.slice(3); 175 | else if(node.name=="body")node.name="page"; 176 | } 177 | if(node.children){ 178 | const removeType=["webkit","moz","ms","o"]; 179 | let list={}; 180 | node.children.each((son,item)=>{ 181 | if(son.type=="Declaration"){ 182 | if(list[son.property]){ 183 | let a=item,b=list[son.property],x=son,y=b.data,ans=null; 184 | if(x.value.type=='Raw'&&x.value.value.startsWith("progid:DXImageTransform")){ 185 | node.children.remove(a); 186 | ans=b; 187 | }else if(y.value.type=='Raw'&&y.value.value.startsWith("progid:DXImageTransform")){ 188 | node.children.remove(b); 189 | ans=a; 190 | }else{ 191 | let xValue=x.value.children&&x.value.children.head&&x.value.children.head.data.name,yValue=y.value.children&&y.value.children.head&&y.value.children.head.data.name; 192 | if(xValue&&yValue)for(let type of removeType)if(xValue==`-${type}-${yValue}`){ 193 | node.children.remove(a); 194 | ans=b; 195 | break; 196 | }else if(yValue==`-${type}-${xValue}`){ 197 | node.children.remove(b); 198 | ans=a; 199 | break; 200 | }else{ 201 | let mValue=`-${type}-`; 202 | if(xValue.startsWith(mValue))xValue=xValue.slice(mValue.length); 203 | if(yValue.startsWith(mValue))yValue=yValue.slice(mValue.length); 204 | } 205 | if(ans===null)ans=b; 206 | } 207 | list[son.property]=ans; 208 | }else list[son.property]=item; 209 | } 210 | }); 211 | for(let name in list)if(!name.startsWith('-')) 212 | for(let type of removeType){ 213 | let fullName=`-${type}-${name}`; 214 | if(list[fullName]){ 215 | node.children.remove(list[fullName]); 216 | delete list[fullName]; 217 | } 218 | } 219 | } 220 | }); 221 | return cssbeautify(csstree.generate(ast),{indent:' ',autosemicolon:true}); 222 | } 223 | wu.scanDirByExt(dir,".html",files=>{ 224 | let frameFile=""; 225 | if(fs.existsSync(path.resolve(dir,"page-frame.html"))) 226 | frameFile=path.resolve(dir,"page-frame.html"); 227 | else if(fs.existsSync(path.resolve(dir,"app-wxss.js"))) 228 | frameFile=path.resolve(dir,"app-wxss.js"); 229 | else if(fs.existsSync(path.resolve(dir,"page-frame.js"))) 230 | frameFile=path.resolve(dir,"page-frame.js"); 231 | else throw Error("page-frame-like file is not found in the package by auto."); 232 | wu.get(frameFile,code=>{ 233 | 234 | let scriptCode = code; 235 | //extract script content from html 236 | if (frameFile.endsWith(".html")) { 237 | try { 238 | const $ = cheerio.load(code); 239 | scriptCode = [].join.apply($('html').find('script').map(function (item) { 240 | return $(this).html(); 241 | }, "\n")); 242 | } catch (e) { 243 | //ignore 244 | } 245 | } 246 | 247 | let window = { 248 | screen: { 249 | width: 720, 250 | height: 1028, 251 | orientation: { 252 | type: 'vertical' 253 | } 254 | } 255 | }; 256 | let navigator = { 257 | userAgent: "iPhone" 258 | }; 259 | 260 | 261 | let mainCode = 'window= ' + JSON.stringify(window) + 262 | ';\nnavigator=' + JSON.stringify(navigator) + 263 | //";\ndocument=" + document + 264 | ";\n" + scriptCode; 265 | 266 | //remove setCssToHead function 267 | let setCssToHeadFuctionStartIndex = mainCode.indexOf("var setCssToHead = function"); 268 | let setCssToHeadFunctionParamIndexes = chomp_balanced(mainCode, setCssToHeadFuctionStartIndex, '(', ')'); 269 | let setCssToHeadFunctionEndIndexes = chomp_balanced(mainCode, setCssToHeadFunctionParamIndexes.end + 1, '{', '}'); 270 | mainCode = mainCode.substr(0, setCssToHeadFuctionStartIndex) + mainCode.substr(setCssToHeadFunctionEndIndexes.end + 1); 271 | 272 | //remove var __wxAppCode__ = {}; 273 | let wxAppCodeVarDeclare = "var __wxAppCode__={};"; 274 | let wxAppCodeVarDeclareIndex = mainCode.indexOf(wxAppCodeVarDeclare); 275 | let wxAppCodeVarDeclareEnd = wxAppCodeVarDeclareIndex + wxAppCodeVarDeclare.length; 276 | mainCode = mainCode.substr(0, wxAppCodeVarDeclareIndex) + mainCode.substr(wxAppCodeVarDeclareEnd); 277 | 278 | code=code.slice(code.indexOf('var setCssToHead = function(file, _xcInvalid')); 279 | code=code.slice(code.indexOf('\nvar _C= ')+1); 280 | //let oriCode=code; 281 | code=code.slice(0,code.indexOf('\n')); 282 | let vm=new VM({sandbox:{}}); 283 | pureData=vm.run(code+"\n_C"); 284 | //let mainCode=oriCode.slice(oriCode.indexOf("setCssToHead"),oriCode.lastIndexOf(";var __pageFrameEndTime__")); 285 | console.log("Guess wxss(first turn)..."); 286 | preRun(dir,frameFile,mainCode,files,()=>{ 287 | frameName=frameFile; 288 | onlyTest=true; 289 | runOnce(); 290 | onlyTest=false; 291 | console.log("Import count info: %j",importCnt); 292 | for(let id in pureData)if(!actualPure[id]){ 293 | if(!importCnt[id])importCnt[id]=0; 294 | if(importCnt[id]<=1){ 295 | console.log("Cannot find pure import for _C["+id+"] which is only imported "+importCnt[id]+" times. Let importing become copying."); 296 | }else{ 297 | let newFile=path.resolve(dir,"__wuBaseWxss__/"+id+".wxss"); 298 | console.log("Cannot find pure import for _C["+id+"], force to save it in ("+newFile+")."); 299 | id=Number.parseInt(id); 300 | actualPure[id]=newFile; 301 | cssRebuild.call({cssFile:newFile},id)(); 302 | } 303 | } 304 | console.log("Guess wxss(first turn) done.\nGenerate wxss(second turn)..."); 305 | runOnce() 306 | console.log("Generate wxss(second turn) done.\nSave wxss..."); 307 | for(let name in result)wu.save(wu.changeExt(name,".wxss"),transformCss(result[name])); 308 | let delFiles={}; 309 | for(let name of files)delFiles[name]=8; 310 | delFiles[frameFile]=4; 311 | cb(delFiles); 312 | }); 313 | }); 314 | }); 315 | } 316 | module.exports={doWxss:doWxss}; 317 | if(require.main===module){ 318 | wu.commandExecute(doWxss,"Restore wxss files.\n\n\n\n restore wxss file from a unpacked directory(Have page-frame.html (or app-wxss.js) and other html file)."); 319 | } 320 | -------------------------------------------------------------------------------- /wuWxml.js: -------------------------------------------------------------------------------- 1 | const wu=require("./wuLib.js"); 2 | const {getZ}=require("./wuRestoreZ.js"); 3 | const {wxsBeautify}=require("./wuJs.js"); 4 | const fs=require('fs'); 5 | const path=require("path"); 6 | const esprima=require('esprima'); 7 | const {VM}=require('vm2'); 8 | const escodegen=require('escodegen'); 9 | function analyze(core,z,namePool,xPool,fakePool={},zMulName="0"){ 10 | function anaRecursion(core,fakePool={}){ 11 | return analyze(core,z,namePool,xPool,fakePool,zMulName); 12 | } 13 | function push(name,elem){ 14 | namePool[name]=elem; 15 | } 16 | function pushSon(pname,son){ 17 | if(fakePool[pname])fakePool[pname].son.push(son); 18 | else namePool[pname].son.push(son); 19 | } 20 | for(let ei=0;ei0) 116 | throw Error("Noticable generics content: "+dec.init.arguments[2].toString()); 117 | let mv={}; 118 | let name=null,base=0; 119 | for(let x of dec.init.arguments[1].elements){ 120 | let v=x.value; 121 | if(!v&&typeof v!="number"){ 122 | if(x.type=="UnaryExpression"&&x.operator=="-")v=-x.argument.value; 123 | else throw Error("Unknown type of object in _m attrs array: "+x.type); 124 | } 125 | if(name===null){ 126 | name=v; 127 | }else{ 128 | if(base+v<0)mv[name]=null;else{ 129 | mv[name]=z[base+v]; 130 | if(base==0)base=v; 131 | } 132 | name=null; 133 | } 134 | } 135 | push(dec.id.name,{tag:dec.init.arguments[0].value,son:[],v:mv}); 136 | } 137 | break; 138 | case "_mz": 139 | { 140 | if(dec.init.arguments[3].elements.length>0) 141 | throw Error("Noticable generics content: "+dec.init.arguments[3].toString()); 142 | let mv={}; 143 | let name=null,base=0; 144 | for(let x of dec.init.arguments[2].elements){ 145 | let v=x.value; 146 | if(!v&&typeof v!="number"){ 147 | if(x.type=="UnaryExpression"&&x.operator=="-")v=-x.argument.value; 148 | else throw Error("Unknown type of object in _mz attrs array: "+x.type); 149 | } 150 | if(name===null){ 151 | name=v; 152 | }else{ 153 | if(base+v<0)mv[name]=null;else{ 154 | mv[name]=z.mul[zMulName][base+v]; 155 | if(base==0)base=v; 156 | } 157 | name=null; 158 | } 159 | } 160 | push(dec.id.name,{tag:dec.init.arguments[1].value,son:[],v:mv}); 161 | } 162 | break; 163 | case "_gd"://template use/is 164 | { 165 | let is=namePool[dec.init.arguments[1].name].content; 166 | let data=null,obj=null; 167 | ei++; 168 | for(let e of core[ei].consequent.body){ 169 | if(e.type=="VariableDeclaration"){ 170 | for(let f of e.declarations){ 171 | if(f.init.type=="LogicalExpression"&&f.init.left.type=="CallExpression"){ 172 | if(f.init.left.callee.name=="_1")data=z[f.init.left.arguments[0].value]; 173 | else if(f.init.left.callee.name=="_1z")data=z.mul[zMulName][f.init.left.arguments[1].value]; 174 | } 175 | } 176 | }else if(e.type=="ExpressionStatement"){ 177 | let f=e.expression; 178 | if(f.type=="AssignmentExpression"&&f.operator=="="&&f.left.property&&f.left.property.name=="wxXCkey"){ 179 | obj=f.left.object.name; 180 | } 181 | } 182 | } 183 | namePool[obj].tag="template"; 184 | Object.assign(namePool[obj].v,{is:is,data:data}); 185 | } 186 | break; 187 | default: 188 | { 189 | let funName=dec.init.callee.name; 190 | if(funName.startsWith("gz$gwx")){ 191 | zMulName=funName.slice(6); 192 | }else throw Error("Unknown init callee "+funName); 193 | } 194 | } 195 | }else if(dec.init.type=="FunctionExpression"){ 196 | push(dec.id.name,{tag:"gen",func:dec.init}); 197 | }else if(dec.init.type=="MemberExpression"){ 198 | if(dec.init.object.type=="MemberExpression"&&dec.init.object.object.name=="e_"&&dec.init.object.property.type=="MemberExpression"&&dec.init.object.property.object.name=="x"){ 199 | if(dec.init.property.name=="j"){//include 200 | //do nothing 201 | }else if(dec.init.property.name=="i"){//import 202 | //do nothing 203 | }else throw Error("Unknown member expression declaration."); 204 | }else throw Error("Unknown member expression declaration."); 205 | }else throw Error("Unknown declaration init type " + dec.init.type); 206 | } 207 | break; 208 | case "IfStatement": 209 | if(e.test.callee.name.startsWith("_o")){ 210 | function parse_OFun(e){ 211 | if(e.test.callee.name=="_o")return z[e.test.arguments[0].value]; 212 | else if(e.test.callee.name=="_oz")return z.mul[zMulName][e.test.arguments[1].value]; 213 | else throw Error("Unknown if statement test callee name:"+e.test.callee.name); 214 | } 215 | let vname=e.consequent.body[0].expression.left.object.name; 216 | let nif={tag:"block",v:{"wx:if":parse_OFun(e)},son:[]}; 217 | anaRecursion(e.consequent.body,{[vname]:nif}); 218 | pushSon(vname,nif); 219 | if(e.alternate){ 220 | while(e.alternate&&e.alternate.type=="IfStatement"){ 221 | e=e.alternate; 222 | nif={tag:"block",v:{"wx:elif":parse_OFun(e)},son:[]}; 223 | anaRecursion(e.consequent.body,{[vname]:nif}); 224 | pushSon(vname,nif); 225 | } 226 | if(e.alternate&&e.alternate.type=="BlockStatement"){ 227 | e=e.alternate; 228 | nif={tag:"block",v:{"wx:else":null},son:[]}; 229 | anaRecursion(e.body,{[vname]:nif}); 230 | pushSon(vname,nif); 231 | } 232 | } 233 | }else throw Error("Unknown if statement."); 234 | break; 235 | default: 236 | throw Error("Unknown type "+e.type); 237 | } 238 | } 239 | } 240 | function wxmlify(str,isText){ 241 | if(typeof str=="undefined"||str===null)return "Empty";//throw Error("Empty str in "+(isText?"text":"prop")); 242 | if(isText)return str;//may have some bugs in some specific case(undocumented by tx) 243 | else return str.replace(/"/g, '\\"'); 244 | } 245 | function elemToString(elem,dep,moreInfo=false){ 246 | const longerList=[];//put tag name which can't be style. 247 | const indent=' '.repeat(4); 248 | function isTextTag(elem){ 249 | return elem.tag=="__textNode__"&&elem.textNode; 250 | } 251 | function elemRecursion(elem,dep){ 252 | return elemToString(elem,dep,moreInfo); 253 | } 254 | function trimMerge(rets){ 255 | let needTrimLeft=false,ans=""; 256 | for(let ret of rets){ 257 | if(ret.textNode==1){ 258 | if(!needTrimLeft){ 259 | needTrimLeft=true; 260 | ans=ans.trimRight(); 261 | } 262 | }else if(needTrimLeft){ 263 | needTrimLeft=false; 264 | ret=ret.trimLeft(); 265 | } 266 | ans+=ret; 267 | } 268 | return ans; 269 | } 270 | if(isTextTag(elem)){ 271 | //In comment, you can use typify text node, which beautify its code, but may destroy ui. 272 | //So, we use a "hack" way to solve this problem by letting typify program stop when face textNode 273 | let str=new String(wxmlify(elem.content,true)); 274 | str.textNode=1; 275 | return wxmlify(str,true);//indent.repeat(dep)+wxmlify(elem.content.trim(),true)+"\n"; 276 | } 277 | if(elem.tag=="block"&&!moreInfo){ 278 | if(elem.son.length==1&&!isTextTag(elem.son[0])){ 279 | let ok=true,s=elem.son[0]; 280 | for(let x in elem.v)if(x in s.v){ 281 | ok=false; 282 | break; 283 | } 284 | if(ok&&!(("wx:for" in s.v||"wx:if" in s.v)&&("wx:if" in elem.v||"wx:else" in elem.v||"wx:elif" in elem.v))){//if for and if in one tag, the default result is an if in for. And we should block if nested in elif/else been combined. 285 | Object.assign(s.v,elem.v); 286 | return elemRecursion(s,dep); 287 | } 288 | }else if(Object.keys(elem.v).length==0){ 289 | let ret=[]; 290 | for(let s of elem.son)ret.push(elemRecursion(s,dep)); 291 | return trimMerge(ret); 292 | } 293 | } 294 | let ret=indent.repeat(dep)+"<"+elem.tag; 295 | for(let v in elem.v)ret+=" "+v+(elem.v[v]!==null?"=\""+wxmlify(elem.v[v])+"\"":""); 296 | if(elem.son.length==0){ 297 | if(longerList.includes(elem.tag))return ret+" />\n"; 298 | else return ret+">\n"; 299 | } 300 | ret+=">\n"; 301 | let rets=[ret]; 302 | for(let s of elem.son)rets.push(elemRecursion(s,dep+1)); 303 | rets.push(indent.repeat(dep)+"\n"); 304 | return trimMerge(rets); 305 | } 306 | function doWxml(state,dir,name,code,z,xPool,rDs,wxsList,moreInfo){ 307 | let rname=code.slice(code.lastIndexOf("return")+6).replace(/[\;\}]/g,"").trim(); 308 | code=code.slice(code.indexOf("\n"),code.lastIndexOf("return")).trim(); 309 | let r={son:[]}; 310 | analyze(esprima.parseScript(code).body,z,{[rname]:r},xPool,{[rname]:r}); 311 | let ans=[]; 312 | for(let elem of r.son)ans.push(elemToString(elem,0,moreInfo)); 313 | let result=[ans.join("")]; 314 | for(let v in rDs){ 315 | state[0]=v; 316 | let oriCode=rDs[v].toString(); 317 | let rname=oriCode.slice(oriCode.lastIndexOf("return")+6).replace(/[\;\}]/g,"").trim(); 318 | let tryPtr=oriCode.indexOf("\ntry{"); 319 | let zPtr=oriCode.indexOf("var z=gz$gwx"); 320 | let code=oriCode.slice(tryPtr+5,oriCode.lastIndexOf("\n}catch(")).trim(); 321 | if(zPtr!=-1&&tryPtr>zPtr){ 322 | let attach=oriCode.slice(zPtr); 323 | attach=attach.slice(0,attach.indexOf("()"))+"()\n"; 324 | code=attach+code; 325 | } 326 | let r={tag:"template",v:{name:v},son:[]}; 327 | analyze(esprima.parseScript(code).body,z,{[rname]:r},xPool,{[rname]:r}); 328 | result.unshift(elemToString(r,0,moreInfo)); 329 | } 330 | name=path.resolve(dir,name); 331 | if(wxsList[name])result.push(wxsList[name]); 332 | wu.save(name,result.join("")); 333 | } 334 | function tryWxml(dir,name,code,z,xPool,rDs,...args){ 335 | console.log("Decompile "+name+"..."); 336 | let state=[null]; 337 | try{ 338 | doWxml(state,dir,name,code,z,xPool,rDs,...args); 339 | console.log("Decompile success!"); 340 | }catch(e){ 341 | console.log("error on "+name+"("+(state[0]===null?"Main":"Template-"+state[0])+")\nerr: ",e); 342 | if(state[0]===null)wu.save(path.resolve(dir,name+".ori.js"),code); 343 | else wu.save(path.resolve(dir,name+".tem-"+state[0]+".ori.js"),rDs[state[0]].toString()); 344 | } 345 | } 346 | function doWxs(code){ 347 | const before='nv_module={nv_exports:{}};'; 348 | return wxsBeautify(code.slice(code.indexOf(before)+before.length,code.lastIndexOf('return nv_module.nv_exports;}')).replace(/nv\_/g,'')); 349 | } 350 | function doFrame(name,cb,order){ 351 | let moreInfo=order.includes("m"); 352 | wxsList={}; 353 | wu.get(name,code=>{ 354 | getZ(code,z=>{ 355 | const before="\nvar nv_require=function(){var nnm="; 356 | code=code.slice(code.indexOf(before)+before.length,code.lastIndexOf("if(path&&e_[path]){")); 357 | json=code.slice(0,code.indexOf("};")+1); 358 | let endOfRequire=code.indexOf("()\r\n")+4; 359 | if(endOfRequire==4-1)endOfRequire=code.indexOf("()\n")+3; 360 | code=code.slice(endOfRequire); 361 | let rD={},rE={},rF={},requireInfo,x,vm=new VM({sandbox:{d_:rD,e_:rE,f_:rF,_vmRev_(data){ 362 | [x,requireInfo]=data; 363 | },nv_require(path){ 364 | return ()=>path; 365 | }}}); 366 | vm.run(code+"\n_vmRev_([x,"+json+"])"); 367 | let dir=path.dirname(name),pF=[]; 368 | for(let info in rF)if(typeof rF[info]=="function"){ 369 | let name=path.resolve(dir,(info[0]=='/'?'.':'')+info),ref=rF[info](); 370 | pF[ref]=info; 371 | wu.save(name,doWxs(requireInfo[ref].toString())); 372 | } 373 | for(let info in rF)if(typeof rF[info]=="object"){ 374 | let name=path.resolve(dir,(info[0]=='/'?'.':'')+info); 375 | let res=[],now=rF[info]; 376 | for(let deps in now){ 377 | let ref=now[deps](); 378 | if(ref.includes(":"))res.push("\n"+doWxs(requireInfo[ref].toString())+"\n"); 379 | else if(pF[ref])res.push(""); 380 | else res.push(""); 381 | wxsList[name]=res.join("\n"); 382 | } 383 | } 384 | for(let name in rE)tryWxml(dir,name,rE[name].f.toString(),z,x,rD[name],wxsList,moreInfo); 385 | cb({[name]:4}); 386 | }); 387 | }); 388 | } 389 | module.exports={doFrame:doFrame}; 390 | if(require.main===module){ 391 | wu.commandExecute(doFrame,"Restore wxml files.\n\n\n\n restore wxml file from page-frame.html or app-wxss.js."); 392 | } 393 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------