├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── 1.bug-report.yml │ └── feature_request.md ├── dependabot.yml └── workflows │ ├── manual-trigger.yml │ └── release.yml ├── .gitignore ├── .gitmodules ├── .prettierignore ├── .prettierrc.js ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── bin └── index.js ├── images ├── logo.svg └── sponsor.jpg ├── package.json ├── rollup.config.js ├── scripts ├── pkg.js └── release.js ├── src ├── cli │ ├── commands │ │ └── wxapkg.ts │ ├── index.ts │ └── outputConfig.ts ├── core │ ├── controller │ │ ├── ConfigController.ts │ │ ├── PathController.ts │ │ ├── SaveController.ts │ │ ├── TraverseController.ts │ │ ├── WorkerController.ts │ │ └── WxapkgController.ts │ ├── decryptor │ │ ├── BaseDecryptor.ts │ │ └── WxapkgDecryptor.ts │ ├── extractor │ │ ├── BaseExtractor.ts │ │ └── WxapkgExtractor.ts │ ├── parser │ │ ├── BaseParser.ts │ │ └── wxapkg │ │ │ ├── AppConfigParser.ts │ │ │ ├── ScriptParser.ts │ │ │ ├── WxmlParser.ts │ │ │ ├── WxssParser.ts │ │ │ └── types.d.ts │ └── workers │ │ └── traverse.ts ├── enum │ ├── PackageSuffix.ts │ ├── Wxapkg.ts │ └── index.ts ├── index.ts ├── lib │ └── wxml-parser-js │ │ ├── index.d.ts │ │ ├── index.js │ │ └── vendor-e192f276.js ├── test │ └── index.ts └── utils │ ├── ast.ts │ ├── checkWxapkg.ts │ ├── classes │ └── Saver.ts │ ├── clearConsole.ts │ ├── colors.ts │ ├── crypto.ts │ ├── exceptions.ts │ ├── getConfigurator.ts │ ├── getWccVersion.ts │ ├── hasOwnProperty.ts │ ├── isDev.ts │ ├── isWorkerRuntime.ts │ ├── logger.ts │ ├── matchScripts.ts │ ├── reformat.ts │ ├── transformStyle.ts │ ├── unlink.ts │ └── wxmlParserJs.ts ├── tsconfig.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | lib 2 | node_modules 3 | dist 4 | bin 5 | scripts 6 | rollup.config.js 7 | 8 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line no-undef 2 | module.exports = { 3 | env: { 4 | browser: false, 5 | es2021: true, 6 | }, 7 | extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'], 8 | overrides: [], 9 | parser: '@typescript-eslint/parser', 10 | parserOptions: { 11 | ecmaVersion: 'latest', 12 | sourceType: 'module', 13 | }, 14 | plugins: ['@typescript-eslint'], 15 | rules: {}, 16 | } 17 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: ['http://r3x5ur.me/sponsor'] 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/1.bug-report.yml: -------------------------------------------------------------------------------- 1 | title: "[Bug]: " 2 | labels: ["bug"] 3 | name: 🐛 Bug report 4 | assignees: "@r3x5ur" 5 | description: 创建报告以帮助我们改进 6 | 7 | body: 8 | - type: markdown 9 | attributes: 10 | value: | 11 | **🤝感谢提交** 12 | **📝请填写以下字段,便于更好的排查和解决问题,共同维护靠大家** 13 | - type: input 14 | attributes: 15 | label: unveilr版本 16 | description: 填写 `unveilr -v` 的输出 17 | validations: 18 | required: true 19 | - type: input 20 | attributes: 21 | label: NodeJs版本 22 | description: 填写 `node -v` 的输出 _(使用二进制文件的可以不填)_ 23 | - type: dropdown 24 | id: sys-version 25 | attributes: 26 | label: 操作系统 27 | description: 运行时的操作系统 28 | options: 29 | - windows 30 | - linux 31 | - macOS 32 | validations: 33 | required: true 34 | - type: input 35 | attributes: 36 | label: 运行时命令 37 | description: 路径自己脱敏如:`unveilr /path/to/dir` 38 | validations: 39 | required: true 40 | - type: input 41 | attributes: 42 | label: wcc版本 43 | description: "当控制台有输出`wcc version is: [v0.xxx]`时,请填入[]中的内容" 44 | - type: textarea 45 | attributes: 46 | label: 重现步骤(最好能上传反编译失败的样本) 47 | description: 输入有关您的错误的详细信息 48 | validations: 49 | required: true 50 | - type: textarea 51 | attributes: 52 | label: 预期结果 53 | description: 请提供文本输出而不是屏幕截图 54 | validations: 55 | required: true 56 | - type: textarea 57 | attributes: 58 | label: 实际结果 59 | description: 请提供文本输出而不是屏幕截图 60 | validations: 61 | required: true 62 | - type: textarea 63 | attributes: 64 | label: 其他信息 65 | description: 其他你觉得可能有用的信息 66 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/manual-trigger.yml: -------------------------------------------------------------------------------- 1 | name: Manual Trigger 2 | on: 3 | # 手动触发事件 4 | workflow_dispatch: 5 | inputs: 6 | tags: 7 | description: 'Test scenario tags' 8 | 9 | jobs: 10 | printInputs: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - run: | 14 | echo "NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}" | base64 15 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | permissions: 3 | contents: write 4 | on: 5 | push: 6 | tags: 7 | - "v*" 8 | jobs: 9 | build-and-release: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v2 14 | 15 | - name: Setup Node.js and Yarn 16 | uses: actions/setup-node@v2 17 | with: 18 | node-version: '14.x' 19 | cache: 'yarn' 20 | 21 | - name: Install dependencies 22 | run: yarn 23 | 24 | - name: Build 25 | run: yarn pkg 26 | 27 | - name: "Build Changelog" 28 | id: build_changelog 29 | uses: mikepenz/release-changelog-builder-action@v3.7.0 30 | 31 | - name: Create Release and Upload Release Asset 32 | uses: softprops/action-gh-release@v1 33 | if: startsWith(github.ref, 'refs/tags/') 34 | with: 35 | tag_name: ${{ github.ref_name }} 36 | name: ${{ github.ref_name }} 37 | body: | 38 | ${{steps.build_changelog.outputs.changelog}} 39 | draft: true 40 | prerelease: true 41 | files: release/*.tar.gz 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | 106 | # Docusaurus cache and generated files 107 | .docusaurus 108 | 109 | # Serverless directories 110 | .serverless/ 111 | 112 | # FuseBox cache 113 | .fusebox/ 114 | 115 | # DynamoDB Local files 116 | .dynamodb/ 117 | 118 | # TernJS port file 119 | .tern-port 120 | 121 | # Stores VSCode versions used for testing VSCode extensions 122 | .vscode-test 123 | 124 | # yarn v2 125 | .yarn/cache 126 | .yarn/unplugged 127 | .yarn/build-state.yml 128 | .yarn/install-state.gz 129 | .pnp.* 130 | 131 | 132 | .idea/ 133 | files/ 134 | release/ 135 | .npmrc 136 | .release.lock 137 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/lib/wxml-parser"] 2 | path = src/lib/wxml-parser 3 | url = git@47.243.177.122:wxml-parser.git 4 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | wxml-parser-js 2 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | // 一行最多 120 字符 3 | printWidth: 120, 4 | // 使用 2 个空格缩进 5 | tabWidth: 2, 6 | // 不使用 tab 缩进,而使用空格 7 | useTabs: false, 8 | // 行尾需要有分号 9 | semi: false, 10 | // 使用单引号代替双引号 11 | singleQuote: true, 12 | // 对象的 key 仅在必要时用引号 13 | quoteProps: 'as-needed', 14 | // jsx 不使用单引号,而使用双引号 15 | jsxSingleQuote: false, 16 | // 末尾使用逗号 17 | trailingComma: 'all', 18 | // 大括号内的首尾需要空格 { foo: bar } 19 | bracketSpacing: true, 20 | // jsx 标签的反尖括号需要换行 21 | jsxBracketSameLine: false, 22 | // 箭头函数,只有一个参数的时候,也需要括号 23 | arrowParens: 'always', 24 | // 每个文件格式化的范围是文件的全部内容 25 | rangeStart: 0, 26 | rangeEnd: Infinity, 27 | // 不需要写文件开头的 @prettier 28 | requirePragma: false, 29 | // 不需要自动在文件开头插入 @prettier 30 | insertPragma: false, 31 | // 使用默认的折行标准 32 | proseWrap: 'preserve', 33 | // 根据显示样式决定 html 要不要折行 34 | htmlWhitespaceSensitivity: 'css', 35 | // 换行符使用 lf 36 | endOfLine: 'lf', 37 | }; 38 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 更改日志 2 | 3 | ### [:bookmark:v2.0.0-beta.1 :loud_sound:2023-04-02](https://github.com/r3x5ur/unveilr/tree/v2.0.0-beta.1) 4 | * [PR] fix bug (#45,#46) by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/47 5 | * 🐛fix bug [#54](https://github.com/r3x5ur/unveilr/issues/54) 6 | * ✨add feat [#51](https://github.com/r3x5ur/unveilr/issues/51) 7 | * 🐛fix bug [#32](https://github.com/r3x5ur/unveilr/issues/32) 8 | * ⬆️Replace `colors`with `chalk` 9 | * ♻️Refactor `Saver`Components 10 | 11 | ### [:bookmark:v2.0.0-alpha.3 :loud_sound:2023-03-29](https://github.com/r3x5ur/unveilr/tree/v2.0.0-alpha.3) 12 | * 添加更友好的 bug-report by @0xNoobS3c in https://github.com/r3x5ur/unveilr/pull/30 13 | * [PR] 添加 wcc_version 检测 by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/33 14 | * Bump @typescript-eslint/parser from 5.56.0 to 5.57.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/35 15 | * Bump typescript from 4.9.5 to 5.0.2 by @dependabot in https://github.com/r3x5ur/unveilr/pull/39 16 | * Bump prettier from 2.8.6 to 2.8.7 by @dependabot in https://github.com/r3x5ur/unveilr/pull/38 17 | * Bump @typescript-eslint/eslint-plugin from 5.56.0 to 5.57.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/37 18 | * Bump rollup from 3.20.0 to 3.20.2 by @dependabot in https://github.com/r3x5ur/unveilr/pull/36 19 | * [PR] 添加CI工具 by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/41 20 | * :bug:(clean) "Clean rely parse (Resolves #40)" by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/42 21 | * :fire:(core) "Add APP_V4 support(Resolves #29)" by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/43 22 | --- 23 | 24 | ### [:bookmark:v2.0.0-alpha.2 :loud_sound:2023-03-27](https://github.com/r3x5ur/unveilr/tree/v2.0.0-alpha.2) 25 | - 🐛解决Worker读取配置失败的问题 [#28](https://github.com/r3x5ur/unveilr/issues/28) 26 | - 🐛解决部分已知问题 27 | --- 28 | 29 | ### [:bookmark:v2.0.0-alpha.1 :loud_sound:2023-03-26](https://github.com/r3x5ur/unveilr/tree/v2.0.0-alpha.1) 30 | - 🔥支持 `APP_V3,APP_SUBPACKAGE_V2` 31 | - 🔥支持 `APP_PLUGIN_V1` 32 | - 🔥添加 `arm` 架构可执行文件 33 | - 🐛解决部分已知问题 34 | --- 35 | 36 | ### [:bookmark:v2.0.0-alpha.0 :loud_sound:2023-03-24](https://github.com/r3x5ur/unveilr/tree/v2.0.0-alpha.0) 37 | - 🔥支持构建可执行文件 38 | - 🔥使用`ast`解析代码 39 | - 🔥解密时自动提取`wxAppId` 40 | - 🐛解决旧版底层无法解决的bug 41 | --- 42 |
1.x版本 43 |

44 | 45 | ### [:bookmark:v1.0.2 :loud_sound:2023-03-17](https://github.com/r3x5ur/unveilr/tree/v1.0.2) 46 | - ⚡ improve performance 47 | - 🐛 Fix some known issues. 48 | - 停止对 1.x 的维护 49 | --- 50 | 51 | ### [:bookmark:v1.0.1 :loud_sound:2023-01-10](https://github.com/r3x5ur/unveilr/tree/v1.0.1) 52 | - ⚡ improve performance 53 | - 🐛 Fix some known issues. 54 | --- 55 |

56 |
57 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | 2352327206@qq.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## :money_with_wings:保护头发,感谢支持 2 | ![sponsor](images/sponsor.jpg) 3 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![logo](./images/logo.svg)
2 | [![badge](https://img.shields.io/badge/r3x5ur-unveilr-red)][repo] 3 | [![license](https://img.shields.io/github/license/r3x5ur/unveilr?v=2)][repo] 4 | [![languages](https://img.shields.io/github/languages/top/r3x5ur/unveilr)][repo] 5 | [![visitor](https://visitor-badge.glitch.me/badge?page_id=https://github.com/r3x5ur/unveilr)][repo] 6 | [![visitor](https://img.shields.io/github/commit-activity/m/r3x5ur/unveilr)][repo] 7 | [![https://img.shields.io/npm/v/unveilr.svg](https://img.shields.io/npm/v/unveilr.svg)][npm] 8 | [![unveilr](https://img.shields.io/npm/dt/unveilr.svg)][npm] 9 | [![unveilr](https://img.shields.io/node/v/unveilr)][npm] 10 | [![release](https://github.com/r3x5ur/unveilr/actions/workflows/release.yml/badge.svg?event=push)][release] 11 | [![release](https://img.shields.io/github/downloads/r3x5ur/unveilr/total)][release] 12 | [![vul](https://img.shields.io/snyk/vulnerabilities/github/r3x5ur/unveilr)][repo] 13 | 14 | ## !!!声明!!! 15 | 16 | **本程序仅供于学习交流,请使用者遵守《中华人民共和国网络安全法》,勿将此工具用于非授权的测试,开发者不负任何连带法律责任。** 17 | 18 | ### :loud_sound:公告 19 | - :rocket:[v2.0.0-beta.1](https://github.com/r3x5ur/unveilr/releases/tag/)已经发布,快来试试吧~ 20 | - 一些常见问题移到[讨论区](https://github.com/r3x5ur/unveilr/discussions)去了 21 | 22 | ### ✨新版本特性 23 | 24 | - 🔥支持自动解密(`windows`从路径上提取`wxAppId`) 25 | - 🔥自动合并子包 26 | - 🔥支持解析最新版`wxapkg` (`APP_V3`/`APP_V4`/`APP_SUBPACKAGE_V2`) 27 | - 🔥支持解析最新版小程序插件 (`APP_PLUGIN_V1`) 28 | - 🔥采用`@babel/core`直接解析语法树,精准提取源码(`1.x`是正则提取) 29 | - 🔥使用`Threadjs`做的线程池,`cpu`直接干到顶(🤡解析语法树特别吃`cpu`) 30 | 31 | ### ✅安装方法 32 | 33 | #### 1. 下载可执行文件 34 | 35 | - 从[下载地址][release]下载对应操作系统的可执行文件 36 | - 运行 `unveilr@[version]-[platform]-[arch][.exe] --help` 37 | 38 | #### 2. npm 安装 39 | 40 | ```bash 41 | # npm 42 | npm i unveilr -g 43 | # yarn 44 | yarn global add unveilr 45 | 46 | unveilr --help 47 | # 简称 48 | uvr -h 49 | # 当 'unveilr' 不是内部或外部命令,也不是可运行的程序或批处理文件。 50 | # 尝试在命令前面加一个 npx, 例如: 51 | npx unveilr --help 52 | ``` 53 | 54 | ### 📝参数详解 55 | 56 | - 子命令是为了后续集成别的平台小程序解包功能 **([其他小程序反编译方案收集](https://github.com/r3x5ur/unveilr/discussions/24))** 57 | - 子命令默认为 `wx` 58 | 59 | | 子命令 | 参数 | 解释 | 60 | |----------|---------------------------|------------------------------------------------| 61 | | `global` | `-l, --log-level ` | 设置日志等级 `debug`,`info`,`warn`,`error` 默认 `info` | 62 | | `wx` | `` | `wxapkg`的路径,可以是多个,也可以是一个目录 | 63 | | `wx` | `-i, --appid ` | 解密`windows`上的 `wxapkg`时需要提供**🔥已经支持自动从路径中提取** | 64 | | `wx` | `-f, --format` | 是否需要格式化解析出来的代码 | 65 | | `wx` | `--no-clear-decompile` | 不清除反编译时的残留文件 | 66 | | `wx` | `--no-clear-save` | 不清除之前的编译结果 | 67 | | `wx` | `--no-parse` | 只提取`wxapkg`中的文件,不进行反编译 | 68 | | `wx` | `-d, --depth ` | 设置从目录中查找`wxapkg`的深度默认: `1` 设置为`0`时不限制深度 | 69 | | `wx` | ` -o, --output ` | 设置反编译输出路径 | 70 | 71 | ### 💡使用示例 72 | 73 | ```bash 74 | # 直接解包整个目录 75 | $ unveilr /path/to/wxapkg/dir/ 76 | # 解包多个包 77 | $ unveilr /path/to/1.wxapkg /path/to/2.wxapkg ... 78 | # 指定子命令并指定微信AppId 79 | $ unveilr wx /path/to/wxapkg/dir/ -i wx11aa22bb33cc44dd 80 | # 格式化解析出来的代码 81 | $ unveilr wx /path/to/wxapkg/dir/ -f 82 | # 只提取源文件不解析进行反编译 83 | $ unveilr wx /path/to/wxapkg/dir/ --no-parse 84 | ``` 85 | 86 | #### 旧版本可以使用 [1.0.2版本](https://github.com/r3x5ur/unveilr/releases/tag/v1.0.2) 87 | 88 | ### [:bulb:提交问题](https://github.com/r3x5ur/wxapkg-unpacker/issues) 89 | 90 | ### [:triangular_flag_on_post:社区讨论](https://github.com/r3x5ur/unveilr/discussions) 91 | 92 | ### [:memo:更改日志](https://github.com/r3x5ur/wxapkg-unpacker/blob/master/CHANGELOG.md) 93 | 94 | ### [:money_with_wings:赞助(开源不易,感谢支持)](https://github.com/r3x5ur/wxapkg-unpacker/blob/master/CONTRIBUTING.md) 95 | 96 | ### 💬其他说明 97 | 98 | - 本程序现在使用的开源协议是 [GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.html) 99 | 100 | ### 🍻特别感谢 101 | 102 | - [wxappUnpacker](https://github.com/qwerty472123/wxappUnpacker) 103 | - [pc_wxapkg_decrypt](https://github.com/BlackTrace/pc_wxapkg_decrypt) 104 | - [mac_wxapkg_decrypt](https://github.com/TinyNiko/mac_wxapkg_decrypt) 105 | 106 | [repo]:https://github.com/r3x5ur/unveilr 107 | 108 | [npm]:https://www.npmjs.com/package/unveilr 109 | 110 | [release]:https://github.com/r3x5ur/unveilr/releases 111 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 5.1.x | :white_check_mark: | 11 | | 5.0.x | :x: | 12 | | 4.0.x | :white_check_mark: | 13 | | < 4.0 | :x: | 14 | 15 | ## Reporting a Vulnerability 16 | 17 | Use this section to tell people how to report a vulnerability. 18 | 19 | Tell them where to go, how often they can expect to get an update on a 20 | reported vulnerability, what to expect if the vulnerability is accepted or 21 | declined, etc. 22 | -------------------------------------------------------------------------------- /bin/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | require('../dist') 3 | -------------------------------------------------------------------------------- /images/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /images/sponsor.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/broken5/unveilr/c79b9b2a0e418f15ee987ed46595f7b08bf6dd25/images/sponsor.jpg -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "unveilr", 3 | "author": "r3x5ur", 4 | "version": "2.0.0-beta.1", 5 | "displayName": "小程序反编译", 6 | "keywords": [ 7 | "wxapkg", 8 | "unpack", 9 | "微信小程序", 10 | "微信小游戏", 11 | "反编译", 12 | "unveilr", 13 | "抖音小程序", 14 | "抖音小游戏" 15 | ], 16 | "description": "将小程序包反编译成源码,小程序安全利器", 17 | "main": "dist/index.js", 18 | "license": "GPL-3.0", 19 | "repository": { 20 | "type": "git", 21 | "url": "https://github.com/r3x5ur/unveilr" 22 | }, 23 | "bugs": "https://github.com/r3x5ur/unveilr/issues", 24 | "engines": { 25 | "node": ">=12.0.0" 26 | }, 27 | "scripts": { 28 | "eslint": "eslint --fix src --ext .ts --max-warnings=0", 29 | "dev": "ts-node-dev -r tsconfig-paths/register --respawn --transpile-only src/index.ts", 30 | "run": "ts-node -r tsconfig-paths/register --transpile-only src/index.ts", 31 | "ts-node": "ts-node -r tsconfig-paths/register --transpile-only", 32 | "build": "npx rollup -c --bundleConfigAsCjs", 33 | "pkg": "node scripts/pkg.js", 34 | "release": "node scripts/release.js" 35 | }, 36 | "dependencies": { 37 | "@babel/core": "^7.21.3", 38 | "chalk": "4.1.2", 39 | "commander": "^10.0.0", 40 | "crypto-js": "^4.1.1", 41 | "css-tree": "^2.3.1", 42 | "observable-fns": "^0.6.1", 43 | "prettier": "^2.8.5", 44 | "shelljs": "^0.8.5", 45 | "threads": "^1.7.0", 46 | "winston": "^3.8.2" 47 | }, 48 | "devDependencies": { 49 | "@rollup/plugin-commonjs": "^24.0.1", 50 | "@rollup/plugin-json": "^6.0.0", 51 | "@rollup/plugin-node-resolve": "^15.0.1", 52 | "@types/babel__core": "^7.20.0", 53 | "@types/babel__traverse": "^7.18.3", 54 | "@types/crypto-js": "^4.1.1", 55 | "@types/css-tree": "^2.3.1", 56 | "@types/node": "^18.14.4", 57 | "@types/prettier": "^2.7.2", 58 | "@types/shelljs": "^0.8.11", 59 | "@typescript-eslint/eslint-plugin": "^5.56.0", 60 | "@typescript-eslint/parser": "^5.54.0", 61 | "compressing": "^1.8.0", 62 | "eslint": "8.22.0", 63 | "pkg": "^5.8.1", 64 | "rollup": "^3.19.1", 65 | "rollup-plugin-clear": "^2.0.7", 66 | "rollup-plugin-license": "^3.0.1", 67 | "rollup-plugin-terser": "^7.0.2", 68 | "rollup-plugin-typescript2": "^0.34.1", 69 | "ts-node-dev": "^2.0.0", 70 | "tsconfig-paths": "^4.1.2", 71 | "typescript": "^5.0.2" 72 | }, 73 | "bin": { 74 | "unveilr": "bin/index.js", 75 | "uvr": "bin/index.js" 76 | }, 77 | "files": [ 78 | "bin/", 79 | "dist/", 80 | "images/logo.svg", 81 | "package.json", 82 | "README.md", 83 | "CHANGELOG.md", 84 | "CONTRIBUTING.md", 85 | "LICENSE" 86 | ] 87 | } 88 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import json from '@rollup/plugin-json' 2 | import commonjs from '@rollup/plugin-commonjs' 3 | import nodeResolve from '@rollup/plugin-node-resolve' 4 | import typescript from 'rollup-plugin-typescript2' 5 | import packages from './package.json' 6 | import { terser } from 'rollup-plugin-terser' 7 | import license from 'rollup-plugin-license' 8 | import { join } from 'path' 9 | import clear from 'rollup-plugin-clear' 10 | 11 | export const output = { 12 | dir: 'dist', 13 | format: 'cjs', 14 | manualChunks(id) { 15 | if (id.includes('wxml-parser-js')) return 'parser' 16 | if (id.includes('traverse.ts')) return 'traverse' 17 | }, 18 | } 19 | const external = Object.keys(packages['dependencies']) 20 | export default { 21 | input: 'src/index.ts', 22 | output, 23 | external, 24 | plugins: [ 25 | clear({ 26 | targets: [output.dir], 27 | }), 28 | typescript({ 29 | tsconfigOverride: { 30 | compilerOptions: { 31 | module: 'ES2015', 32 | declaration: false, 33 | }, 34 | }, 35 | }), 36 | commonjs(), 37 | nodeResolve({ preferBuiltins: true }), 38 | json(), 39 | terser(), 40 | license({ 41 | banner: { 42 | commentStyle: 'ignored', 43 | content: 44 | '<%= pkg.name %> v<%= pkg.version %>\n' + 45 | '(c) 2023 <%= pkg.author %>\n' + 46 | 'Released under the <%= pkg.license %> License.', 47 | }, 48 | thirdParty: { 49 | output: join(__dirname, 'dist', 'dependencies.txt'), 50 | }, 51 | }), 52 | ], 53 | cache: false, 54 | strictDeprecations: true, 55 | treeshake: { 56 | moduleSideEffects: false, 57 | propertyReadSideEffects: false, 58 | tryCatchDeoptimization: false, 59 | }, 60 | } 61 | -------------------------------------------------------------------------------- /scripts/pkg.js: -------------------------------------------------------------------------------- 1 | const { rmSync, readdirSync } = require('fs') 2 | const { join } = require('path') 3 | const { execSync } = require('child_process') 4 | const { exec } = require('pkg') 5 | const { name, version } = require('../package.json') 6 | const { tgz } = require('compressing') 7 | 8 | const distIndex = 'dist/index.js' 9 | const release = 'release' 10 | 11 | function log(message) { 12 | console.log(`[PKG] ${message}`) 13 | } 14 | 15 | /** 16 | * - nodeRange (node8), node10, node12, node14, node16 or latest 17 | * - platform alpine, linux, linuxstatic, win, macos, (freebsd) 18 | * - arch x64, arm64, (armv6, armv7) 19 | * */ 20 | async function pkg() { 21 | log('Clean up old binaries...') 22 | rmSync(release, { force: true, recursive: true }) 23 | const targets = [ 24 | 'node14-win-x64', 25 | 'node14-win-arm64', 26 | 'node14-macos-x64', 27 | 'node14-macos-arm64', 28 | 'node14-linux-x64', 29 | 'node14-linux-arm64', 30 | ] 31 | const pkgCmd = 32 | `-C GZip -t ${targets.toString()} --no-bytecode --public-packages "*" --public -o ${release}/${name}@${version} ${distIndex}` 33 | .split(' ') 34 | .filter(Boolean) 35 | log('Generating binaries...') 36 | await exec(pkgCmd) 37 | } 38 | 39 | async function _tgz() { 40 | const files = readdirSync(release) 41 | for (const p of files) { 42 | const source = join(release, p) 43 | const dest = source + '.tar.gz' 44 | log(`Generating dest ${dest}`) 45 | await tgz.compressFile(source, dest) 46 | rmSync(source) 47 | } 48 | } 49 | async function main() { 50 | log('Building distribution...') 51 | execSync('yarn build') 52 | await pkg() 53 | await _tgz() 54 | } 55 | 56 | main().then() 57 | -------------------------------------------------------------------------------- /scripts/release.js: -------------------------------------------------------------------------------- 1 | const { readFileSync, writeFileSync, rmSync, existsSync } = require('fs') 2 | const { resolve } = require('path') 3 | const { execSync, exec } = require('child_process') 4 | const { version } = require('../package.json') 5 | 6 | function log(message) { 7 | console.log(`[RELEASE] ${message}`) 8 | } 9 | 10 | function getDate() { 11 | const d = new Date() 12 | const to2 = (s) => ('00' + s).slice(-2) 13 | return `${d.getFullYear()}-${to2(d.getMonth() + 1)}-${to2(d.getDate())}` 14 | } 15 | 16 | function isAlreadyRelease(log, version) { 17 | const versionRE = `${version}`.replace(/[.-]/g, (r) => '\\' + r) 18 | const d = new RegExp(`### \\[:bookmark:(v${versionRE})\\s*:loud_sound:`) 19 | return d.exec(log) !== null 20 | } 21 | 22 | async function main() { 23 | const releaseLock = resolve(__dirname, '../.release.lock') 24 | 25 | // new version 26 | const newVersion = () => { 27 | const version = execSync('npm version prerelease --preid=alpha --no-git-tag-version').toString().trim() 28 | const logPath = resolve(__dirname, '../CHANGELOG.md') 29 | const changLog = readFileSync(logPath, 'utf8') 30 | if (!isAlreadyRelease(changLog, version)) { 31 | const newVersion = `# 更改日志 32 | 33 | ### [:bookmark:v${version} :loud_sound:${getDate()}](https://github.com/r3x5ur/unveilr/tree/v${version}) 34 | - 🐛解决部分已知问题 35 | --- 36 | ` 37 | const newLog = newVersion + changLog.replace('# 更改日志\n', '') 38 | writeFileSync(logPath, newLog) 39 | } 40 | execSync(`git add . && git commit -m ":bookmark:v${version}" && git tag v${version} -m "v${version}"`) 41 | } 42 | const submit = () => { 43 | return new Promise((resolve, reject) => { 44 | const release = exec(`git push && git push --tag`) 45 | release.stdout.on('data', log) 46 | release.stderr.on('data', log) 47 | release.on('close', (code) => { 48 | if (code !== 0) return reject(code) 49 | log(`v${version} released!`) 50 | resolve() 51 | }) 52 | }) 53 | } 54 | const release = async () => { 55 | const maxRetry = 3 56 | let retry = 0 57 | while (retry <= maxRetry) { 58 | try { 59 | await submit() 60 | break 61 | } catch (e) { 62 | retry++ 63 | retry !== maxRetry - 1 && log('retry...') 64 | } 65 | if (retry > maxRetry) { 66 | writeFileSync(releaseLock, Buffer.from('')) 67 | await Promise.reject('release failed!') 68 | } else { 69 | rmSync(releaseLock, { force: true }) 70 | execSync(`npm publish`) 71 | } 72 | } 73 | } 74 | if (existsSync(releaseLock)) { 75 | log('release lock file exists!') 76 | } else { 77 | newVersion() 78 | } 79 | await release() 80 | } 81 | 82 | main().catch(log) 83 | -------------------------------------------------------------------------------- /src/cli/commands/wxapkg.ts: -------------------------------------------------------------------------------- 1 | import { Command, Argument, Option, CommanderError } from 'commander' 2 | import { outputConfig } from '@/cli/outputConfig' 3 | 4 | const wxCommand = new Command('wx') 5 | // read-depth 6 | const noParseOption = new Option('-p, --no-parse', 'Only extract files, do not parse').implies({ 7 | clearDecompile: false, 8 | }) 9 | const depthOptions = new Option('-d, --depth ', 'Set read-depth') 10 | .argParser((v) => { 11 | const depth = parseInt(v) 12 | if (isNaN(depth)) throw new CommanderError(1, 'depth.error', 'Invalid depth') 13 | return depth 14 | }) 15 | .default(1) 16 | wxCommand 17 | .option('-i, --appid ', 'Set wxAppId, not provided will try to fetch from path') 18 | .option('-f, --format', 'Enable format code') 19 | .option('--no-clear-decompile', 'Retain decompiling residual files') 20 | .option('--no-clear-save', 'The path to be saved will not be cleared') 21 | .addOption(noParseOption) 22 | .addOption(depthOptions) 23 | .option('-o, --output ', 'Set output path, default: main package whit out') 24 | .description('Decompile the WeChat applet') 25 | .addArgument(new Argument('', 'Set package path, could be a file, directory or multiple files')) 26 | .showHelpAfterError() 27 | .configureOutput(outputConfig) 28 | export default wxCommand 29 | 30 | export interface WxConfigurator { 31 | appid?: string 32 | format?: boolean 33 | clearDecompile: boolean 34 | clearSave: boolean 35 | parse: boolean 36 | depth: number 37 | output?: string 38 | packages: string[] 39 | } 40 | -------------------------------------------------------------------------------- /src/cli/index.ts: -------------------------------------------------------------------------------- 1 | import { Command, Option } from 'commander' 2 | import wxCommand, { WxConfigurator } from '@/cli/commands/wxapkg' 3 | import { LoggerLevel } from '@utils/logger' 4 | import { outputConfig } from '@/cli/outputConfig' 5 | 6 | export interface CliConfigurator { 7 | global: { 8 | logLevel: LoggerLevel 9 | } 10 | wx: WxConfigurator 11 | } 12 | 13 | export function registerCommand(version: string, name: string, _argv?: string[]): CliConfigurator { 14 | const argv = _argv || process.argv 15 | const logLevel = new Option('-l, --log-level ', 'Set log level') 16 | .choices(['debug', 'info', 'warn', 'error']) 17 | .default('info') 18 | const cmd = new Command(name) 19 | cmd 20 | .usage('[wx] [options]') 21 | .version(version, '-v, --version') 22 | .addOption(logLevel) 23 | .addCommand(wxCommand, { isDefault: true }) 24 | .addHelpText( 25 | 'after', 26 | ` 27 | Example: 28 | $ ${name} /path/to/wxapkg/dir/ 29 | $ ${name} 1.wxapkg 2.wxapkg 3.wxapkg ... 30 | $ ${name} wx /path/to/wxapkg/dir/ Specify wx subcommand 31 | $ ${name} wx 1.wxapkg 2.wxapkg 3.wxapkg ... Specify wx subcommand 32 | $ ${name} wx -h Show wx help info 33 | `, 34 | ) 35 | .showHelpAfterError() 36 | .configureOutput(outputConfig) 37 | .parse(argv) 38 | if (!argv.length) return cmd.help({ error: true }) 39 | return { 40 | global: cmd.opts(), 41 | wx: { 42 | ...wxCommand.opts(), 43 | packages: wxCommand.args, 44 | }, 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/cli/outputConfig.ts: -------------------------------------------------------------------------------- 1 | import { OutputConfiguration } from 'commander' 2 | import { green, red, yellow } from '@utils/colors' 3 | 4 | export const outputConfig: OutputConfiguration = { 5 | writeOut(str: string) { 6 | process.stdout.write(green(str)) 7 | }, 8 | writeErr(str: string) { 9 | process.stdout.write(yellow(str)) 10 | }, 11 | outputError(str: string, write) { 12 | write(red(str)) 13 | }, 14 | } 15 | -------------------------------------------------------------------------------- /src/core/controller/ConfigController.ts: -------------------------------------------------------------------------------- 1 | import { CliConfigurator } from '@/cli' 2 | 3 | export class ConfigController { 4 | private readonly config: CliConfigurator 5 | private constructor(config: CliConfigurator) { 6 | this.config = config 7 | } 8 | 9 | get innerConfig(): Readonly { 10 | return Object.freeze(this.config) 11 | } 12 | 13 | get logLevel() { 14 | return this.config.global.logLevel 15 | } 16 | get WXReformat() { 17 | return this.config.wx.format 18 | } 19 | get WXClearDecompile() { 20 | return this.WXParse && this.config.wx.clearDecompile 21 | } 22 | get WXClearSave() { 23 | return this.config.wx.clearSave 24 | } 25 | get WXDepth() { 26 | return this.config.wx.depth 27 | } 28 | get WXParse() { 29 | return this.config.wx.parse 30 | } 31 | get WXPackages() { 32 | return this.config.wx.packages 33 | } 34 | get WXAppId() { 35 | return this.config.wx.appid 36 | } 37 | get WXOutput() { 38 | return this.config.wx.output 39 | } 40 | 41 | static instance: ConfigController 42 | 43 | static init(config: CliConfigurator): void { 44 | if (!ConfigController.instance) { 45 | ConfigController.instance = new ConfigController(config) 46 | } 47 | } 48 | 49 | static getInstance(): ConfigController { 50 | if (!ConfigController.instance) throw ReferenceError('ConfigController is not initialized') 51 | return ConfigController.instance 52 | } 53 | } 54 | 55 | export function getConfig(key: T): ConfigController[T] { 56 | const inst = ConfigController.getInstance() 57 | if (!key) throw ReferenceError(`Config name is required`) 58 | return inst[key] 59 | } 60 | 61 | export function initializeConfig(config: CliConfigurator) { 62 | ConfigController.init(config) 63 | } 64 | 65 | export function getInnerConfig() { 66 | const inst = ConfigController.getInstance() 67 | return inst.innerConfig 68 | } 69 | -------------------------------------------------------------------------------- /src/core/controller/PathController.ts: -------------------------------------------------------------------------------- 1 | import { 2 | readFileSync, 3 | WriteFileOptions, 4 | writeFileSync, 5 | statSync, 6 | existsSync, 7 | mkdirSync, 8 | readdirSync, 9 | copyFileSync, 10 | unlinkSync, 11 | rmdirSync, 12 | rmSync, 13 | } from 'fs' 14 | import { readdir, readFile, writeFile, unlink, rm } from 'fs/promises' 15 | import { sep, dirname, extname, join, resolve, basename, relative, isAbsolute } from 'path' 16 | import { ObjectEncodingOptions, OpenMode } from 'node:fs' 17 | import { Abortable } from 'node:events' 18 | import { grey } from '@utils/colors' 19 | 20 | export type ProduciblePath = string | PathController 21 | export type Optional = T | null 22 | export type ReadDirStringOption = 23 | | (ObjectEncodingOptions & { 24 | withFileTypes?: false | undefined 25 | }) 26 | | BufferEncoding 27 | | null 28 | export type ReadBufferOption = 29 | | ({ 30 | encoding?: null | undefined 31 | flag?: OpenMode | undefined 32 | } & Abortable) 33 | | null 34 | export type ReadStringOption = 35 | | (ObjectEncodingOptions & 36 | Abortable & { 37 | flag?: OpenMode | undefined 38 | }) 39 | | BufferEncoding 40 | | null 41 | 42 | export class PathController { 43 | readonly path: string 44 | exists = false 45 | isDirectory = false 46 | isFile = false 47 | 48 | constructor(path?: string) { 49 | this.path = path || '' 50 | this.reload() 51 | } 52 | 53 | reload(): this { 54 | this.exists = existsSync(this.path) 55 | if (this.exists) { 56 | try { 57 | const stat = statSync(this.path) 58 | this.isDirectory = stat.isDirectory() 59 | this.isFile = stat.isFile() 60 | } catch (e) { 61 | if (e.errno === -4058) this.exists = false 62 | this.isDirectory = false 63 | this.isFile = false 64 | } 65 | } 66 | return this 67 | } 68 | get suffix(): string { 69 | return extname(this.path) 70 | } 71 | 72 | get suffixWithout(): string { 73 | return this.suffix.slice(1) 74 | } 75 | 76 | get abspath(): string { 77 | return resolve(this.path) 78 | } 79 | 80 | get unixpath(): string { 81 | if (sep === '/') return this.path 82 | return this.path.replace(/\\/g, '/') 83 | } 84 | 85 | get absunixpath(): string { 86 | return PathController.make(this.abspath).unixpath 87 | } 88 | 89 | get logpath(): string { 90 | const dirML = 80 91 | const s = 92 | this.abspath.length - this.basename.length <= dirML 93 | ? this.abspath 94 | : this.abspath.slice(0, dirML) + '...' + this.basename 95 | return grey(s) 96 | } 97 | 98 | get dirname(): string { 99 | if (this.isDirectory) return this.path 100 | if (this.isFile) return dirname(this.path) 101 | return dirname(this.path) 102 | } 103 | 104 | get basename(): string { 105 | return basename(this.path) 106 | } 107 | 108 | get basenameWithout(): string { 109 | return basename(this.path, this.suffix) 110 | } 111 | 112 | get isAbs() { 113 | return isAbsolute(this.path) 114 | } 115 | 116 | relative(p: ProduciblePath): PathController { 117 | return PathController.make(relative(this.path, PathController.make(p).path)) 118 | } 119 | 120 | async readdir(opt?: ReadDirStringOption, absolutePath?: boolean): Promise { 121 | if (!this.isDirectory) return null 122 | const list = await readdir(this.path, opt) 123 | return absolutePath ? list.map((v) => resolve(this.abspath, v)) : list 124 | } 125 | 126 | async read(opt?: ReadBufferOption): Promise 127 | async read(opt?: ReadStringOption): Promise 128 | async read(opt?: unknown): Promise { 129 | if (!this.isFile) return null 130 | return await readFile(this.path, opt) 131 | } 132 | 133 | readSync(opt?: ReadBufferOption): Buffer 134 | readSync(opt?: ReadStringOption): string 135 | readSync(opt?: unknown): Buffer | string { 136 | return readFileSync(this.path, opt) 137 | } 138 | 139 | async write(data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise { 140 | await writeFile(this.abspath, data, options) 141 | return this 142 | } 143 | writeSync(data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): this { 144 | writeFileSync(this.abspath, data, options) 145 | return this 146 | } 147 | 148 | async writeJSON(data: object): Promise { 149 | return this.write(JSON.stringify(data, null, 2), 'utf8') 150 | } 151 | 152 | writeJSONSync(data: object): this { 153 | return this.writeSync(JSON.stringify(data, null, 2), 'utf8') 154 | } 155 | 156 | copy(_target: ProduciblePath): PathController { 157 | // copy single path 158 | const target = PathController.make(_target) 159 | if (this.isFile) return copyFileSync(this.path, target.mkdir().abspath), this 160 | // deep copy multiple directory 161 | if (this.isDirectory) { 162 | target.mkdir(true) 163 | this.deepListDir().forEach((t) => { 164 | const _tp = PathController.make(join(target.abspath, t.replace(this.abspath, ''))) 165 | copyFileSync(t, _tp.mkdir().abspath) 166 | }) 167 | return this 168 | } 169 | return this 170 | } 171 | 172 | move(_target: ProduciblePath): PathController { 173 | this.copy(_target).abspath 174 | if (this.isFile) unlinkSync(this.abspath) 175 | else if (this.isDirectory) rmdirSync(this.abspath, { recursive: true }) 176 | return PathController.make(_target) 177 | } 178 | 179 | mkdir(self?: boolean): Optional { 180 | if (this.exists) return this 181 | const _path = self ? this.path : dirname(this.path) 182 | mkdirSync(_path, { recursive: true }) 183 | this.reload() 184 | return this 185 | } 186 | async unlink(): Promise { 187 | await unlink(this.abspath) 188 | // this.reload() 189 | } 190 | unlinkSync(): void { 191 | unlinkSync(this.abspath) 192 | this.reload() 193 | } 194 | deepListDir(depth: number): string[] 195 | deepListDir(absolute?: boolean, depth?: number): string[] 196 | deepListDir(arg1?: boolean | number, arg2?: number): string[] { 197 | if (!this.isDirectory) return [] 198 | const list: string[] = [] 199 | let absolute: boolean 200 | let depth: number 201 | const deepPath = absolute ? this.absunixpath : this.unixpath 202 | switch (arguments.length) { 203 | case 0: 204 | absolute = false 205 | depth = Number.MAX_SAFE_INTEGER 206 | break 207 | case 1: 208 | if (typeof arg1 === 'boolean') { 209 | absolute = arg1 210 | depth = Number.MAX_SAFE_INTEGER 211 | } else if (typeof arg1 === 'number') { 212 | absolute = false 213 | depth = arg1 || Number.MAX_SAFE_INTEGER 214 | } else { 215 | throw new Error('arg1 must be boolean or number') 216 | } 217 | break 218 | case 2: 219 | absolute = arg1 as boolean 220 | depth = arg2 || Number.MAX_SAFE_INTEGER 221 | } 222 | const listFile = (dir: string): void => { 223 | readdirSync(dir).forEach((item) => { 224 | const fullPath = join(dir, item) 225 | if (statSync(fullPath).isDirectory()) { 226 | if (depth !== Number.MAX_SAFE_INTEGER) { 227 | // 一层不需要往下判断了 228 | if (depth === 1) return 229 | let prevDeep 230 | if (dir === deepPath) prevDeep = 1 231 | else { 232 | const croppedPath = PathController.make(dir).crop(deepPath).unixpath 233 | prevDeep = croppedPath.split('/').length + 1 234 | } 235 | if (prevDeep >= depth) return 236 | } 237 | listFile(fullPath) 238 | } else { 239 | list.push(fullPath) 240 | } 241 | }) 242 | } 243 | listFile(deepPath) 244 | return list 245 | } 246 | 247 | join(...paths: string[]): PathController { 248 | return PathController.make(join(this.path, ...paths)) 249 | } 250 | 251 | whitout(suffix?: string): PathController { 252 | return this.join('..', this.basenameWithout + (suffix || '')) 253 | } 254 | 255 | unix(): PathController { 256 | return PathController.make(this.unixpath) 257 | } 258 | 259 | crop(path: ProduciblePath): PathController { 260 | const newPath = this.unixpath.replace(PathController.make(path).unixpath + '/', '') 261 | return PathController.make(newPath) 262 | } 263 | 264 | async rmrf() { 265 | await rm(this.abspath, { recursive: true, force: true }) 266 | } 267 | rmrfSync() { 268 | rmSync(this.abspath, { recursive: true, force: true }) 269 | } 270 | 271 | toString(): string { 272 | return this.logpath 273 | } 274 | 275 | static unix(path: ProduciblePath): PathController { 276 | return PathController.make(path).unix() 277 | } 278 | 279 | static whitout(path: ProduciblePath, suffix?: string): PathController { 280 | return PathController.make(path).whitout(suffix) 281 | } 282 | 283 | static make(path?: ProduciblePath): PathController { 284 | path = path || '' 285 | return path instanceof PathController ? path : new PathController(path) 286 | } 287 | 288 | static dir(path: ProduciblePath): PathController { 289 | return PathController.make(PathController.make(path).dirname) 290 | } 291 | } 292 | 293 | export function isProduciblePath(value: unknown): value is ProduciblePath { 294 | return typeof value === 'string' || value instanceof PathController 295 | } 296 | -------------------------------------------------------------------------------- /src/core/controller/SaveController.ts: -------------------------------------------------------------------------------- 1 | import { BaseLogger } from '@utils/logger' 2 | import { PathController, ProduciblePath } from '@core/controller/PathController' 3 | import { info } from '@utils/colors' 4 | import { WxapkgKeyFile } from '@/enum' 5 | import { checkSupport, reformat } from '@utils/reformat' 6 | 7 | export type SaveAble = string | Buffer | object 8 | export interface SaveAbleItem { 9 | key: string 10 | buffer: SaveAble 11 | } 12 | type Bucket = Map 13 | 14 | export class SaveController extends BaseLogger { 15 | static instance: SaveController 16 | static isClean = false 17 | static isSafeMode = false 18 | static isReFormat = false 19 | static readonly OVERRIDE_FILES: string[] = [WxapkgKeyFile.GAME, WxapkgKeyFile.PLUGIN] 20 | static getInstance(): SaveController { 21 | if (!SaveController.instance) { 22 | SaveController.instance = new SaveController() 23 | } 24 | return SaveController.instance 25 | } 26 | static setIsClean(isClean: boolean) { 27 | SaveController.isClean = isClean 28 | } 29 | static setIsSafeMode(isSafeMode: boolean) { 30 | SaveController.isSafeMode = isSafeMode 31 | isSafeMode && getSaveController().logger.warn(`Safe mode is enabled, Will not write files to disk`) 32 | } 33 | 34 | static setIsReFormat(isReFormat: boolean) { 35 | SaveController.isReFormat = isReFormat 36 | isReFormat && getSaveController().logger.info(`Turning on code formatting can slow down some operations`) 37 | } 38 | 39 | private readonly fileBucket: Bucket 40 | private constructor() { 41 | super('Bucket') 42 | this.fileBucket = new Map() 43 | } 44 | get keys() { 45 | return Array.from(this.fileBucket.keys()) 46 | } 47 | 48 | // 返回长度最大的数据 49 | private saveAbleMax(s1: SaveAble, s2: SaveAble): SaveAble 50 | private saveAbleMax(...args: SaveAble[]): SaveAble { 51 | const length = (s: SaveAble) => (Buffer.isBuffer(s) || typeof s === 'string' ? s.length : JSON.stringify(s).length) 52 | const map = new Map() 53 | args.forEach((_s) => map.set(length(_s), _s)) 54 | return map.get(Math.max(...map.keys())) 55 | } 56 | 57 | set(path: string, buffer: SaveAble) { 58 | if (!path) return 59 | if (!PathController.make(path).isAbs) { 60 | this.logger.warn(`Path ${path} is not absolute!`) 61 | return 62 | } 63 | if (this.fileBucket.has(path)) { 64 | // 部分文件需要被覆盖不需要比较 65 | if (!SaveController.OVERRIDE_FILES.includes(PathController.make(path).basename)) { 66 | buffer = this.saveAbleMax(this.fileBucket.get(path), buffer) 67 | } 68 | } 69 | this.fileBucket.set(path, buffer) 70 | } 71 | get(path: string): T | null { 72 | if (!path) return null 73 | const ctrl = PathController.make(path) 74 | return (this.fileBucket.get(ctrl.isAbs ? ctrl.path : ctrl.abspath) as T) || null 75 | } 76 | delete(path: string, force?: boolean): boolean { 77 | if (!force && !SaveController.isClean) return false 78 | if (!path) return false 79 | const ctrl = PathController.make(path) 80 | if (!ctrl.isAbs) return false 81 | return this.fileBucket.delete(ctrl.path) 82 | } 83 | pop(path: string, force?: boolean): T | null { 84 | const data: T = this.get(path) 85 | this.delete(path, force) 86 | return data || null 87 | } 88 | 89 | private async saveFile(path: string, buffer: SaveAble) { 90 | const ctrl = PathController.make(path) 91 | if (!buffer) { 92 | this.logger.warn(`You are trying to save a falsy data to ${ctrl.logpath}`) 93 | buffer = '' 94 | } 95 | ctrl.mkdir() 96 | let type 97 | const flush = async (key: 'write' | 'writeUtf8' | 'writeJSON') => { 98 | switch (key) { 99 | case 'write': 100 | await ctrl.write(buffer as Buffer) 101 | break 102 | case 'writeUtf8': 103 | await ctrl.write(String(buffer), 'utf8') 104 | break 105 | case 'writeJSON': 106 | await ctrl.writeJSON(buffer as object) 107 | break 108 | } 109 | } 110 | let retPromise: Promise 111 | if (typeof buffer === 'string') { 112 | retPromise = flush('writeUtf8') 113 | type = `source-${ctrl.suffixWithout}` 114 | } else if (Buffer.isBuffer(buffer)) { 115 | retPromise = flush('write') 116 | type = 'binary' 117 | } else if (typeof buffer === 'object') { 118 | retPromise = flush('writeJSON') 119 | type = 'json' 120 | } else { 121 | this.logger.warn(`Path ${ctrl.path} not allow write type: ${typeof buffer}`) 122 | retPromise = flush('writeUtf8') 123 | } 124 | type && this.logger.debug(`File ${type} save to ${ctrl.logpath}`) 125 | return retPromise 126 | } 127 | async flashDisk() { 128 | if (SaveController.isSafeMode) return 129 | this.logger.debug('Flashing disk...') 130 | const promiseAll = this.keys 131 | .map((path) => { 132 | try { 133 | let buffer = this.pop(path, true) 134 | if (SaveController.isReFormat && checkSupport(path)) { 135 | buffer = reformat(path, saveAble2String(buffer)) 136 | } 137 | return this.saveFile(path, buffer) 138 | } catch (e) { 139 | this.logger.error(`Error when saving file ${path}: ${e}`) 140 | } 141 | return null 142 | }) 143 | .filter(Boolean) 144 | await Promise.all(promiseAll) 145 | const count = promiseAll.length.toString() 146 | count && this.logger.info(`Storage has written ${info(count)} files`) 147 | } 148 | find(prefix: string): SaveAbleItem[] { 149 | const keys = this.fileBucket.keys() 150 | const result: SaveAbleItem[] = [] 151 | if (!prefix) return [] 152 | for (const key of keys) { 153 | if (!key.startsWith(prefix)) continue 154 | const buffer = this.get(key) 155 | if (!buffer) continue 156 | result.push({ key, buffer }) 157 | } 158 | return result.filter(Boolean) 159 | } 160 | } 161 | 162 | export async function flashDisk() { 163 | await getSaveController().flashDisk() 164 | } 165 | 166 | export function findBuffer(path: ProduciblePath): SaveAbleItem[] { 167 | const prefix = PathController.make(path).abspath 168 | return getSaveController().find(prefix) 169 | } 170 | 171 | export function saveAble2String(buffer: SaveAble): string { 172 | if (!buffer) return '' 173 | if (Buffer.isBuffer(buffer)) return buffer.toString() 174 | if (typeof buffer === 'string') return buffer 175 | return JSON.stringify(buffer) 176 | } 177 | 178 | export function getSaveController() { 179 | return SaveController.getInstance() 180 | } 181 | -------------------------------------------------------------------------------- /src/core/controller/TraverseController.ts: -------------------------------------------------------------------------------- 1 | import { TraverseOptions, Visitor } from '@babel/traverse' 2 | import { BabelFileResult } from '@babel/core' 3 | import { ProduciblePath } from '@core/controller/PathController' 4 | import { BuildParams, traverseAST } from '@utils/ast' 5 | 6 | export class TraverseController { 7 | visitors: Visitor 8 | private fileBuilder: BabelFileResult | ProduciblePath | BuildParams 9 | constructor(path: ProduciblePath, opt?: TraverseOptions) 10 | constructor(builder: BuildParams, opt?: TraverseOptions) 11 | constructor(file: BabelFileResult, opt?: TraverseOptions) 12 | constructor(fileBuilder: BabelFileResult | ProduciblePath | BuildParams, visitor?: Visitor) { 13 | this.setFileBuilder(fileBuilder) 14 | this.addVisitors(visitor) 15 | } 16 | 17 | addVisitors(...visitors: Visitor[]): this { 18 | this.visitors = this._mergeVisitors(...visitors) 19 | return this 20 | } 21 | 22 | async traverse(opt?: Pick): Promise { 23 | return traverseAST(this.fileBuilder as BuildParams, { ...this.visitors, ...opt }) 24 | } 25 | 26 | private _mergeVisitors(...source: Visitor[]): Visitor { 27 | const dataMap = {} 28 | ;[this.visitors, ...source].filter(Boolean).forEach((item) => { 29 | if (typeof item !== 'object') return 30 | Object.keys(item).forEach((key) => { 31 | if (Array.isArray(dataMap[key])) { 32 | dataMap[key].push(item[key]) 33 | } else { 34 | dataMap[key] = [item[key]] 35 | } 36 | }) 37 | }) 38 | Object.keys(dataMap).forEach((key) => { 39 | const fs = [...dataMap[key]] 40 | dataMap[key] = (...args) => fs.forEach((f) => f.apply(this, args)) 41 | }) 42 | return dataMap 43 | } 44 | 45 | setFileBuilder(v: BabelFileResult | ProduciblePath | BuildParams): this { 46 | this.fileBuilder = v 47 | return this 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/core/controller/WorkerController.ts: -------------------------------------------------------------------------------- 1 | import { ModuleThread, Pool, spawn, Thread, Worker } from 'threads' 2 | import { QueuedTask, TaskRunFunction } from 'threads/dist/master/pool-types' 3 | import { cpus } from 'os' 4 | import { ModuleMethods } from 'threads/dist/types/master' 5 | import { PathController } from '@core/controller/PathController' 6 | import { BaseError } from '@utils/exceptions' 7 | 8 | export type EachCallback = ( 9 | result?: R, 10 | index?: number, 11 | results?: Array, R>>, 12 | ) => void 13 | export class WorkerError extends BaseError {} 14 | export class WorkerController { 15 | results: Array, R>> 16 | private tasks: Array, R>> 17 | private readonly workerPath: string 18 | private readonly poolSize: number 19 | private pool: Pool 20 | constructor(workerPath: string | NodeModule, poolSize?: number) { 21 | this.tasks = [] 22 | this.results = [] 23 | const _relative = (p: string) => PathController.make(__dirname).relative(p).unixpath 24 | this.workerPath = typeof workerPath === 'string' ? workerPath : _relative(workerPath.id) 25 | this.poolSize = poolSize || cpus().length 26 | } 27 | 28 | async start(callback: EachCallback, terminate?: boolean): Promise 29 | async start(terminate?: boolean): Promise 30 | async start(v?: EachCallback | boolean, _terminate?: boolean): Promise { 31 | let callback, 32 | terminate = _terminate 33 | if (typeof v === 'function') { 34 | callback = v 35 | } else terminate = Boolean(v) 36 | if (!this.tasks.length) return 37 | this.pool = Pool(() => spawn(new Worker(this.workerPath)), this.poolSize) 38 | this.results = this.tasks.map((task) => this.pool.queue(task)) 39 | await this.pool.completed() 40 | this.tasks = [] 41 | callback && (await this.forEach(callback)) 42 | terminate && (await this.terminate()) 43 | } 44 | addTask(...runners: TaskRunFunction, R>[]) { 45 | runners.forEach((runner) => this.tasks.push(runner)) 46 | } 47 | 48 | async terminate() { 49 | if (!this.pool) WorkerError.throw('The worker pool has not started yet, please start it first') 50 | await this.pool.terminate() 51 | delete this.pool 52 | } 53 | 54 | async forEach(callback: EachCallback): Promise { 55 | await Promise.all( 56 | this.results.map((task, index) => { 57 | return task.then((result) => callback(result, index, this.results)) 58 | }), 59 | ) 60 | this.results = [] 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/core/controller/WxapkgController.ts: -------------------------------------------------------------------------------- 1 | import { WxapkgKeyFile, WxapkgType } from '@/enum' 2 | import { WxapkgExtractor } from '@core/extractor/WxapkgExtractor' 3 | import { BaseLogger } from '@utils/logger' 4 | import { PathController, ProduciblePath } from '@core/controller/PathController' 5 | import { WxssParser } from '@core/parser/wxapkg/WxssParser' 6 | import { WxmlParser } from '@core/parser/wxapkg/WxmlParser' 7 | import { ScriptParser } from '@core/parser/wxapkg/ScriptParser' 8 | import { AppConfigParser } from '@core/parser/wxapkg/AppConfigParser' 9 | import { matchScripts } from '@utils/matchScripts' 10 | import { ParserLike, TraverseVisitorKeys, TVSubjectType } from '@core/parser/wxapkg/types' 11 | import { createExposed, traverseModule } from '@core/workers/traverse' 12 | import { Saver } from '@utils/classes/Saver' 13 | import { WorkerController } from '@core/controller/WorkerController' 14 | import { BaseError } from '@utils/exceptions' 15 | import { getConfig, getInnerConfig } from '@core/controller/ConfigController' 16 | import { getWccVersion } from '@utils/getWccVersion' 17 | import { Observable } from 'observable-fns' 18 | import { flashDisk, getSaveController, saveAble2String } from '@core/controller/SaveController' 19 | import { info } from '@utils/colors' 20 | 21 | export class WxapkgError extends BaseError {} 22 | export type ParsersKey = TraverseVisitorKeys | 'WxmlParserV1' 23 | export type TraverseData = { 24 | source: string 25 | visitors: ParsersKey[] 26 | decompiler?: WxapkgDecompiler 27 | } 28 | export type TraverseExposed = ReturnType 29 | export interface WxapkgControllerOptions { 30 | wxapkgList: ProduciblePath[] 31 | wxAppId?: string 32 | mainSaveDir?: ProduciblePath 33 | } 34 | interface SetAppOptions { 35 | viewSource?: string 36 | appConfigSource?: string 37 | serviceSource?: string 38 | setAppConfig?: boolean 39 | } 40 | 41 | export class WxapkgDecompiler extends BaseLogger { 42 | // 包路径 43 | private readonly pathCtrl: PathController 44 | // 解包器 45 | private readonly extractor: WxapkgExtractor 46 | // 解析器 47 | readonly parsers: Record, Promise>> 48 | // 解析后使用的保存器 49 | private readonly saver: Saver 50 | // 遍历列表 51 | private readonly traverseList: TraverseData[] 52 | // 是否使用 V1 版本解析器 53 | get isParserV1() { 54 | const type = this.extractor.type 55 | // prettier-ignore 56 | return ( 57 | type === WxapkgType.APP_V1 || 58 | type === WxapkgType.APP_V2 || 59 | type === WxapkgType.APP_SUBPACKAGE_V1 60 | ) 61 | } 62 | // 是否使用 V3 版本解析器 63 | get isParserV3() { 64 | const type = this.extractor.type 65 | return ( 66 | type === WxapkgType.APP_V3 || 67 | type === WxapkgType.APP_V4 || 68 | type === WxapkgType.APP_SUBPACKAGE_V2 || 69 | type === WxapkgType.APP_PLUGIN_V1 70 | ) 71 | } 72 | // 是否是主包 73 | get isMainPackage() { 74 | return this.extractor.isMainPackage 75 | } 76 | // 是否是子包 77 | get isSubpackage() { 78 | return this.extractor.isSubpackage 79 | } 80 | get isAppPlugin() { 81 | return this.extractor.isAppPlugin 82 | } 83 | // 当前包路径 84 | get path(): PathController { 85 | return this.pathCtrl 86 | } 87 | // 源码目录 88 | get sourceDir(): PathController { 89 | return this.extractor.sourceDir 90 | } 91 | // 保存的目录 92 | get saveDir(): PathController { 93 | return this.saver.saveDirectory 94 | } 95 | set saveDir(dir: ProduciblePath) { 96 | dir = dir || this.path.whitout() 97 | this.extractor.setSaver(dir) 98 | this.saver.saveDirectory = dir 99 | } 100 | 101 | constructor(path: ProduciblePath) { 102 | super() 103 | this.pathCtrl = PathController.make(path) 104 | // 默认保存路径为 path.whitout() 105 | this.extractor = new WxapkgExtractor({ path: this.path }) 106 | this.saver = new Saver(this.extractor.saveDirectory) 107 | this.parsers = Object.create(null) 108 | this.traverseList = [] 109 | } 110 | setExtractorWxAppId(appid: string) { 111 | this.extractor.setWxAppId(appid) 112 | } 113 | extract() { 114 | this.extractor.extract() 115 | } 116 | extractorSave(): void { 117 | this.extractor.save() 118 | } 119 | async makeParserTraverse(): Promise { 120 | this.initParsers() 121 | await this.initTraverseList() 122 | const list = this.traverseList.filter((item) => item.source) 123 | if (!list.length) this.logger.warn(`File ${this.path.logpath} no data to parse`) 124 | return list.map((item) => Object.assign({ decompiler: this }, item)) 125 | } 126 | initParsers() { 127 | if (!this.extractor.extracted) return 128 | this.parsers.ScriptParser = new ScriptParser(this.saver) 129 | switch (this.extractor.type) { 130 | case WxapkgType.APP_V1: 131 | case WxapkgType.APP_V2: 132 | case WxapkgType.APP_V3: 133 | case WxapkgType.APP_V4: 134 | case WxapkgType.APP_SUBPACKAGE_V1: 135 | case WxapkgType.APP_SUBPACKAGE_V2: 136 | case WxapkgType.APP_PLUGIN_V1: 137 | { 138 | const wxss = new WxssParser(this.saver) 139 | this.parsers.WxssParser = wxss 140 | this.parsers.WxssParserCommon = wxss 141 | this.parsers.WxssParserCommon2 = wxss 142 | if (!this.isSubpackage) { 143 | this.parsers.AppConfigService = new AppConfigParser(this.saver) 144 | } 145 | if (this.isParserV1) { 146 | this.parsers.WxmlParserV1 = new WxmlParser(this.saver) 147 | } else if (this.isParserV3) { 148 | this.parsers.WxmlParserV3 = new WxmlParser(this.saver) 149 | } 150 | } 151 | break 152 | case WxapkgType.GAME: 153 | this.parsers.AppConfigService = new AppConfigParser(this.saver) 154 | break 155 | case WxapkgType.GAME_SUBPACKAGE: 156 | case WxapkgType.GAME_PLUGIN: 157 | break 158 | } 159 | } 160 | async initTraverseList() { 161 | if (!this.extractor.extracted) return 162 | // 源码路径 163 | const sourceDir = this.sourceDir 164 | const getSource = (keyFile: WxapkgKeyFile) => { 165 | const ctrl = sourceDir.join(keyFile) 166 | return saveAble2String(getSaveController().get(ctrl.abspath)) 167 | } 168 | const setApp = async (options?: SetAppOptions) => { 169 | const { 170 | serviceSource = getSource(WxapkgKeyFile.APP_SERVICE), 171 | viewSource = getSource(WxapkgKeyFile.APP_WXSS), 172 | appConfigSource, 173 | setAppConfig = true, 174 | } = options || {} 175 | const wccVersion = getWccVersion(viewSource) 176 | if (wccVersion) { 177 | this.logger.info(`The package ${this.pathCtrl.logpath} wcc version is: [${info(wccVersion)}]`) 178 | } 179 | if (setAppConfig) { 180 | const appConfigSource$1 = appConfigSource || getSource(WxapkgKeyFile.APP_CONFIG) 181 | const ACParser = this.parsers.AppConfigService as AppConfigParser 182 | ACParser.setSources(appConfigSource$1) 183 | ACParser.setServiceSource(serviceSource) 184 | this.traverseList.push({ 185 | source: serviceSource, 186 | visitors: ['AppConfigService', 'ScriptParser'], 187 | }) 188 | } else { 189 | this.traverseList.push({ 190 | source: serviceSource, 191 | visitors: ['ScriptParser'], 192 | }) 193 | } 194 | const styleResource = [viewSource, WxssParser.getHTMLStyleSource(sourceDir)].join(';\n') 195 | this.traverseList.push({ 196 | source: styleResource, 197 | visitors: ['WxssParser', 'WxssParserCommon', 'WxssParserCommon2'], 198 | }) 199 | if (this.isParserV1) { 200 | this.traverseList.push({ 201 | source: viewSource, 202 | visitors: ['WxmlParserV1'], 203 | }) 204 | const wxml = this.parsers.WxmlParserV1 as WxmlParser 205 | wxml.setSource(viewSource) 206 | } else if (this.isParserV3) { 207 | this.traverseList.push({ 208 | source: viewSource, 209 | visitors: ['WxmlParserV3'], 210 | }) 211 | } 212 | } 213 | const setOtherScript = async (name: WxapkgKeyFile) => { 214 | this.traverseList.push({ 215 | source: getSource(name), 216 | visitors: ['ScriptParser'], 217 | }) 218 | } 219 | 220 | switch (this.extractor.type) { 221 | case WxapkgType.APP_V1: 222 | case WxapkgType.APP_V4: 223 | await setApp({ viewSource: matchScripts(getSource(WxapkgKeyFile.PAGE_FRAME_HTML)) }) 224 | break 225 | case WxapkgType.APP_V2: 226 | case WxapkgType.APP_V3: 227 | await setApp() 228 | break 229 | case WxapkgType.APP_SUBPACKAGE_V1: 230 | case WxapkgType.APP_SUBPACKAGE_V2: 231 | await setApp({ 232 | viewSource: getSource(WxapkgKeyFile.PAGE_FRAME), 233 | setAppConfig: false, 234 | }) 235 | break 236 | case WxapkgType.APP_PLUGIN_V1: 237 | await setApp({ 238 | viewSource: getSource(WxapkgKeyFile.PAGEFRAME), 239 | serviceSource: getSource(WxapkgKeyFile.APPSERVICE), 240 | setAppConfig: false, 241 | }) 242 | break 243 | case WxapkgType.GAME: 244 | { 245 | const appConfigSource = getSource(WxapkgKeyFile.APP_CONFIG) 246 | const gameSource = getSource(WxapkgKeyFile.GAME) 247 | const subContext = getSource(WxapkgKeyFile.SUBCONTEXT) 248 | const source = [gameSource, subContext].filter(Boolean).join(';\n') 249 | const ACParser = this.parsers.AppConfigService as AppConfigParser 250 | ACParser.setSources(appConfigSource) 251 | ACParser.setIsGame(true) 252 | this.traverseList.push({ 253 | source: source, 254 | visitors: ['AppConfigService'], 255 | }) 256 | await setOtherScript(WxapkgKeyFile.GAME) 257 | } 258 | break 259 | case WxapkgType.GAME_SUBPACKAGE: 260 | await setOtherScript(WxapkgKeyFile.GAME) 261 | break 262 | case WxapkgType.GAME_PLUGIN: 263 | await setOtherScript(WxapkgKeyFile.PLUGIN) 264 | break 265 | } 266 | } 267 | save() { 268 | this.saver.merge() 269 | getConfig('WXClearDecompile') && this.cleanup() 270 | } 271 | cleanup() { 272 | const dirCtrl = this.sourceDir 273 | this.logger.debug(`Start cleaning ${dirCtrl.logpath}`) 274 | const unlinks = [ 275 | '.appservice.js', 276 | 'appservice.js', 277 | 'app-config.json', 278 | 'app-service.js', 279 | 'app-wxss.js', 280 | 'appservice.app.js', 281 | 'common.app.js', 282 | 'page-frame.js', 283 | 'page-frame.html', 284 | 'pageframe.js', 285 | 'webview.app.js', 286 | 'subContext.js', 287 | 'plugin.js', 288 | ] 289 | const inst = getSaveController() 290 | unlinks.forEach((p) => inst.delete(dirCtrl.join(p).abspath)) 291 | } 292 | } 293 | 294 | export class WxapkgController extends BaseLogger { 295 | private readonly decompilers: WxapkgDecompiler[] 296 | private readonly mainSaveDir: PathController 297 | // 解析结果的Promise 298 | private readonly parsersPromise: Promise[] 299 | constructor(wxapkgList: ProduciblePath[]) 300 | constructor(...wxapkgList: ProduciblePath[]) 301 | constructor(options: WxapkgControllerOptions) 302 | constructor(v: WxapkgControllerOptions | ProduciblePath[] | ProduciblePath) { 303 | super() 304 | const options: WxapkgControllerOptions = Object.create(null) 305 | if (Array.isArray(v)) options.wxapkgList = v 306 | else Object.assign(options, v) 307 | const { wxapkgList, mainSaveDir, wxAppId } = options 308 | if (mainSaveDir) this.mainSaveDir = PathController.make(mainSaveDir) 309 | if (!wxapkgList.length) WxapkgError.throw(`No wxapkg available`) 310 | // 初始化反编译器 311 | this.decompilers = wxapkgList.map((p) => { 312 | const decompiler = new WxapkgDecompiler(p) 313 | wxAppId && decompiler.setExtractorWxAppId(wxAppId) 314 | return decompiler 315 | }) 316 | this.parsersPromise = [] 317 | } 318 | 319 | extractorSave() { 320 | // 保存之前清理一下之前的结果 321 | this.clearOldResult() 322 | // 保存提取之后的结果 323 | this.decompilers.forEach((d) => d.extractorSave()) 324 | } 325 | extract(isNoParse: boolean) { 326 | // 提取文件 327 | this.decompilers.forEach((d) => d.extract()) 328 | // 不解析直接保存结果 329 | if (isNoParse) return this.extractorSave() 330 | // 检测主包 331 | let mainDecompiler: WxapkgDecompiler 332 | this.decompilers.forEach((d) => { 333 | if (d.isMainPackage) { 334 | if (mainDecompiler) WxapkgError.throw(`There can only be one main package`) 335 | mainDecompiler = d 336 | } 337 | }) 338 | // 不存在主包直接保存结果 339 | if (!mainDecompiler) return this.extractorSave() 340 | // 存在主包把其他子包的保存路径指向主包 341 | if (this.mainSaveDir) { 342 | mainDecompiler.saveDir = this.mainSaveDir 343 | mainDecompiler.saveDir.rmrfSync() 344 | } 345 | this.decompilers.forEach((d) => { 346 | if (d === mainDecompiler) return 347 | // 小程序插件暂时不能放到主包内 348 | if (d.isAppPlugin) return 349 | d.saveDir = mainDecompiler.saveDir 350 | }) 351 | this.extractorSave() 352 | } 353 | 354 | clearOldResult() { 355 | if (!getConfig('WXClearSave')) return 356 | Array.from(new Set(this.decompilers.map((d) => d.saveDir))).forEach((ctrl) => { 357 | ctrl.rmrfSync() 358 | this.logger.debug(`Cleaned old result ${ctrl.logpath}`) 359 | }) 360 | } 361 | 362 | async invokeTraverseWorker(): Promise { 363 | const forEachVisitors = (decompiler: WxapkgDecompiler, visitors: ParsersKey[], exposed: TraverseExposed) => { 364 | const seen = new Set() 365 | visitors.forEach((key) => { 366 | if (key === 'WxmlParserV1') { 367 | const wxml = decompiler.parsers.WxmlParserV1 as WxmlParser 368 | return wxml.parseV1() 369 | } 370 | if (key === 'AppConfigService') { 371 | const appConfig = decompiler.parsers.AppConfigService as AppConfigParser 372 | if (appConfig.isGame) return appConfig.parseGame() 373 | } 374 | const parserLike = decompiler.parsers[key] 375 | exposed.setVisitor(key) 376 | !seen.has(parserLike) && this.parsersPromise.push(parserLike.parse(exposed.observable())) 377 | seen.add(parserLike) 378 | }) 379 | } 380 | const results = await Promise.all(this.decompilers.map((d) => d.makeParserTraverse())) 381 | const temp: TraverseData[] = [] 382 | results.forEach((items) => { 383 | if (!items) return 384 | temp.push(...items) 385 | }) 386 | const tasks = temp.filter(Boolean) 387 | if (!tasks.length) { 388 | this.logger.warn('No task to traverse') 389 | return 390 | } 391 | if (tasks.length === 1) { 392 | const { decompiler, visitors, source } = tasks[0] 393 | const exposed = createExposed() 394 | forEachVisitors(decompiler, visitors, exposed) 395 | await exposed.startTraverse(source) 396 | } else { 397 | const wCtrl = new WorkerController(traverseModule) 398 | tasks.forEach((item) => { 399 | const { decompiler, visitors, source } = item 400 | wCtrl.addTask((exposed) => { 401 | exposed.initWorker(getInnerConfig()) 402 | forEachVisitors(decompiler, visitors, exposed) 403 | return exposed.startTraverse(source) 404 | }) 405 | }) 406 | await wCtrl.start(true) 407 | } 408 | } 409 | 410 | async saveFiles() { 411 | await Promise.all(this.parsersPromise) 412 | this.decompilers.forEach((d) => d.save()) 413 | await flashDisk() 414 | } 415 | 416 | async exploit() { 417 | const isParse = getConfig('WXParse') 418 | this.extract(!isParse) 419 | isParse && (await this.invokeTraverseWorker()) 420 | await this.saveFiles() 421 | } 422 | } 423 | -------------------------------------------------------------------------------- /src/core/decryptor/BaseDecryptor.ts: -------------------------------------------------------------------------------- 1 | import { PathController, ProduciblePath } from '@core/controller/PathController' 2 | import { Saver } from '@utils/classes/Saver' 3 | import { BaseError } from '@utils/exceptions' 4 | import { BaseLogger } from '@utils/logger' 5 | 6 | export class DecryptorError extends BaseError {} 7 | export class BaseDecryptor extends BaseLogger { 8 | readonly pathCtrl: PathController 9 | protected suffix: string 10 | readonly saver: Saver 11 | constructor(path: ProduciblePath) { 12 | super() 13 | this.pathCtrl = PathController.make(path) 14 | this.saver = new Saver(this.pathCtrl.dirname) 15 | } 16 | 17 | get decipherable() { 18 | return this.pathCtrl.isFile && this.pathCtrl.suffixWithout === this.suffix 19 | } 20 | 21 | decrypt(): void { 22 | if (!this.decipherable) { 23 | DecryptorError.throw(`File ${this.pathCtrl.logpath} cannot be decrypted!`) 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/core/decryptor/WxapkgDecryptor.ts: -------------------------------------------------------------------------------- 1 | import { BaseDecryptor, DecryptorError } from '@core/decryptor/BaseDecryptor' 2 | import { checkWxapkg } from '@utils/checkWxapkg' 3 | import { PackageSuffix } from '@/enum' 4 | import { isProduciblePath, PathController, ProduciblePath } from '@core/controller/PathController' 5 | import { decryptBuffer } from '@utils/crypto' 6 | import { info } from '@utils/colors' 7 | 8 | export interface WxapkgDecryptorOptions { 9 | path: ProduciblePath 10 | wxAppId?: string 11 | target?: ProduciblePath 12 | salt?: string 13 | iv?: string 14 | } 15 | 16 | export class WxapkgDecryptor extends BaseDecryptor { 17 | wxAppId: string 18 | readonly target: PathController 19 | readonly salt: string 20 | readonly iv: string 21 | private decryptedBuffer: Buffer 22 | 23 | constructor(options: WxapkgDecryptorOptions) 24 | constructor(path: ProduciblePath, wxAppId?: string, target?: ProduciblePath) 25 | constructor(path: WxapkgDecryptorOptions | ProduciblePath, wxAppId?: string, target?: ProduciblePath) { 26 | let options 27 | if (arguments.length === 1) { 28 | if (isProduciblePath(path)) { 29 | options = { path } as WxapkgDecryptorOptions 30 | } else { 31 | options = path as WxapkgDecryptorOptions 32 | } 33 | } else { 34 | options = { 35 | path, 36 | wxAppId, 37 | target: arguments.length === 3 ? target : void 0, 38 | } as WxapkgDecryptorOptions 39 | } 40 | super(options.path) 41 | this.suffix = PackageSuffix.WXAPKG 42 | this.wxAppId = options.wxAppId 43 | this.salt = options.salt || 'saltiest' 44 | this.iv = options.iv || 'the\x20iv:\x2016\x20bytes' 45 | this.target = options.target ? PathController.make(options.target) : void 0 46 | this._calcWxAppId() 47 | } 48 | 49 | get result(): Buffer { 50 | return this.decryptedBuffer 51 | } 52 | 53 | _calcWxAppId(): void { 54 | if (this.wxAppId) return 55 | const _result = this.pathCtrl.abspath.match(/wx[a-z\d]{16}/g) 56 | if (!_result) throw new DecryptorError('wxAppId must be required!') 57 | this.wxAppId = _result[0] 58 | this.logger.info(`From ${this.pathCtrl.logpath} detected wxAppId: ${info(this.wxAppId)}`) 59 | } 60 | 61 | checkWxAppId() { 62 | if (!this.wxAppId || !/^wx[a-z\d]{16}$/.test(this.wxAppId)) { 63 | throw new DecryptorError(`wxAppId ${this.wxAppId || ''} must be a valid wxAppId`) 64 | } 65 | } 66 | 67 | decrypt(buffer?: Buffer): void { 68 | super.decrypt() 69 | buffer = buffer || this.pathCtrl.readSync() 70 | this._decrypt(buffer) 71 | } 72 | 73 | private _decrypt(buffer: Buffer) { 74 | try { 75 | this.checkWxAppId() 76 | const wxAppId = this.wxAppId 77 | const header = buffer.subarray(6, 0x406) 78 | const contents = buffer.subarray(0x406) 79 | const oriHeader = decryptBuffer(header, wxAppId, this.salt, this.iv) 80 | const xorKey = wxAppId.length < 2 ? 0x66 : wxAppId.charCodeAt(wxAppId.length - 2) 81 | const oriContents = Buffer.from(contents.map((b) => b ^ xorKey)) 82 | this.decryptedBuffer = Buffer.concat([oriHeader.subarray(0, 0x3ff), oriContents]) 83 | if (!checkWxapkg(this.decryptedBuffer)) DecryptorError.throw('Please check if wxAppId is correct') 84 | this.logger.debug('Decryption successful!') 85 | } catch (e) { 86 | throw new DecryptorError('Decryption failed! ' + e.message) 87 | } 88 | } 89 | 90 | async save(target?: ProduciblePath) { 91 | this.saver.add(target || this.target, this.result) 92 | } 93 | 94 | static decryptResult(options: WxapkgDecryptorOptions): Buffer 95 | static decryptResult(path: ProduciblePath, wxAppId?: string, target?: ProduciblePath): Buffer 96 | static decryptResult(o: WxapkgDecryptorOptions | ProduciblePath, wxAppId?: string): Buffer { 97 | const inst = isProduciblePath(o) ? new WxapkgDecryptor(o, wxAppId) : new WxapkgDecryptor(o) 98 | inst.decrypt() 99 | return inst.result 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/core/extractor/BaseExtractor.ts: -------------------------------------------------------------------------------- 1 | import { PathController, ProduciblePath } from '@core/controller/PathController' 2 | import { BaseError } from '@utils/exceptions' 3 | import { BaseLogger } from '@utils/logger' 4 | 5 | export class ExtractorError extends BaseError {} 6 | export class BaseExtractor extends BaseLogger { 7 | readonly pathCtrl: PathController 8 | protected suffix: string 9 | constructor(path: ProduciblePath) { 10 | super() 11 | this.pathCtrl = PathController.make(path) 12 | } 13 | 14 | get extractable() { 15 | return this.pathCtrl.isFile && this.pathCtrl.suffixWithout === this.suffix 16 | } 17 | 18 | extract(): void { 19 | if (!this.extractable) { 20 | ExtractorError.throw(`File ${this.pathCtrl.logpath} cannot be extracted!`) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/core/extractor/WxapkgExtractor.ts: -------------------------------------------------------------------------------- 1 | import { BaseExtractor, ExtractorError } from './BaseExtractor' 2 | import { WxapkgDecryptor } from '@core/decryptor/WxapkgDecryptor' 3 | import { checkMacEncryption, checkWxapkg, checkWxapkgType } from '@utils/checkWxapkg' 4 | import { PackageSuffix, WxapkgKeyFile, WxapkgType } from '@/enum' 5 | import { isProduciblePath, PathController, ProduciblePath } from '@core/controller/PathController' 6 | import { Saver } from '@utils/classes/Saver' 7 | import { info, link } from '@utils/colors' 8 | 9 | export interface WxapkgFileHeader { 10 | infoLength: number 11 | dataLength: number 12 | } 13 | 14 | export interface WxapkgFileInfo { 15 | name: string 16 | start: number 17 | end: number 18 | } 19 | 20 | export interface WxapkgExtractorOptions { 21 | path: ProduciblePath 22 | wxAppId?: string 23 | saveDir?: ProduciblePath 24 | } 25 | 26 | export class WxapkgExtractor extends BaseExtractor { 27 | private wxAppId: string 28 | private saver: Saver 29 | private wxapkgType: WxapkgType 30 | private sourcePath: string 31 | private isExtracted: boolean 32 | 33 | constructor(path: ProduciblePath) 34 | constructor(options: WxapkgExtractorOptions) 35 | constructor(v: WxapkgExtractorOptions | ProduciblePath) { 36 | if (isProduciblePath(v)) { 37 | super(v) 38 | } else { 39 | const { path, saveDir, wxAppId } = v 40 | super(path) 41 | this.setSaver(saveDir) 42 | this.wxAppId = wxAppId 43 | } 44 | this.isExtracted = false 45 | this.suffix = PackageSuffix.WXAPKG 46 | } 47 | 48 | // 是否提取完成 49 | get extracted() { 50 | if (!this.isExtracted) ExtractorError.throw(`Need to extract first`) 51 | return true 52 | } 53 | 54 | // 包类型 55 | get type() { 56 | if (!this.wxapkgType) ExtractorError.throw(`WxapkgType not available, No extract or unsupported packages`) 57 | return this.wxapkgType 58 | } 59 | 60 | // 是否主包 61 | get isMainPackage() { 62 | return ( 63 | this.type === WxapkgType.APP_V1 || 64 | this.type === WxapkgType.APP_V2 || 65 | this.type === WxapkgType.APP_V3 || 66 | this.type === WxapkgType.APP_V4 || 67 | this.type === WxapkgType.GAME 68 | ) 69 | } 70 | 71 | // 是否是分包 72 | get isSubpackage() { 73 | return ( 74 | this.type === WxapkgType.APP_SUBPACKAGE_V1 || 75 | this.type === WxapkgType.APP_SUBPACKAGE_V2 || 76 | this.type === WxapkgType.GAME_SUBPACKAGE 77 | ) 78 | } 79 | 80 | // 是否是小程序插件 81 | get isAppPlugin() { 82 | return this.type === WxapkgType.APP_PLUGIN_V1 83 | } 84 | 85 | // 是否是游戏插件 86 | get isGamePlugin() { 87 | return this.type === WxapkgType.GAME_PLUGIN 88 | } 89 | 90 | // 是否是插件 91 | get isPlugin() { 92 | return this.isAppPlugin || this.isGamePlugin 93 | } 94 | 95 | // 设置保存的路径 96 | setSaver(saveDir: ProduciblePath | undefined) { 97 | saveDir = saveDir || this.pathCtrl.whitout() 98 | if (!this.saver) { 99 | this.saver = new Saver(saveDir) 100 | return 101 | } 102 | this.saver.saveDirectory = saveDir 103 | } 104 | 105 | // 设置WxAppId 106 | setWxAppId(appid: string) { 107 | this.wxAppId = appid 108 | } 109 | 110 | save() { 111 | this.saver.merge() 112 | } 113 | 114 | get saveDirectory() { 115 | return this.saver.saveDirectory 116 | } 117 | 118 | get sourceDir(): PathController { 119 | return this.saveDirectory.join(this.sourcePath) 120 | } 121 | 122 | // 获取文件头信息 123 | getFileHeader(buf: Buffer): WxapkgFileHeader { 124 | if (!checkWxapkg(buf)) ExtractorError.throw(`File ${this.pathCtrl.logpath} is an invalid package!`) 125 | const unknownInfo = buf.readUInt32BE(1) 126 | unknownInfo && this.logger.warn('UnknownInfo: ', unknownInfo) 127 | return { 128 | infoLength: buf.readUInt32BE(5), 129 | dataLength: buf.readUInt32BE(9), 130 | } 131 | } 132 | 133 | // 获取包内的文件信息 134 | getFileByRaw(buf: Buffer): WxapkgFileInfo[] { 135 | const fileCount = buf.readUInt32BE(0) 136 | this.logger.debug(`Read file count ${fileCount}`) 137 | let _offset = 4 138 | return Array(fileCount) 139 | .fill(0) 140 | .map(() => { 141 | const nameOffset = buf.readUInt32BE(_offset) 142 | _offset += 4 143 | const name = buf.toString('utf8', _offset, _offset + nameOffset) 144 | _offset += nameOffset 145 | const start = buf.readUInt32BE(_offset) 146 | _offset += 4 147 | const end = start + buf.readUInt32BE(_offset) 148 | _offset += 4 149 | return { 150 | name, 151 | start, 152 | end, 153 | } 154 | }) 155 | } 156 | 157 | extractInner(buf: Buffer): void { 158 | const isEncrypted = buf.subarray(0, 6).toString('hex') === '56314d4d5758' 159 | if (isEncrypted) { 160 | this.logger.debug(`File ${this.pathCtrl.logpath} encrypted, Starting decrypt`) 161 | const buffer = WxapkgDecryptor.decryptResult(this.pathCtrl, this.wxAppId) 162 | return this.extractInner(buffer) 163 | } 164 | this.logger.debug(`Starting extract ${this.pathCtrl.logpath}`) 165 | const { dataLength, infoLength } = this.getFileHeader(buf.subarray(0, 14)) 166 | this.logger.debug(`Header info length ${infoLength}`) 167 | this.logger.debug(`Header data length ${dataLength}`) 168 | const files = this.getFileByRaw(buf.subarray(14, infoLength + 14)) 169 | this.logger.debug(`Starting save extracted files`) 170 | const pathList = files.map((file) => { 171 | const { name, start, end } = file 172 | const path = name.startsWith('/') ? name.slice(1) : name 173 | this.saver.add(path, buf.subarray(start, end)) 174 | const basename = PathController.make(path).basename 175 | return { path, basename } 176 | }) 177 | const type = checkWxapkgType(pathList.map(({ basename }) => basename)) 178 | if (!type) this.logger.warn(`Parsed packages are not supported`) 179 | this.logger.info(`The package ${this.pathCtrl.logpath} type is: [${info(type)}]`) 180 | if (type === WxapkgType.FRAMEWORK) this.logger.warn(`Running the framework does not require unpacking`) 181 | this.wxapkgType = type 182 | const isPlugin = this.isPlugin 183 | const sp = pathList.find((item) => { 184 | const { basename } = item 185 | return ( 186 | basename === WxapkgKeyFile.APP_SERVICE || 187 | basename === WxapkgKeyFile.APPSERVICE || 188 | basename === WxapkgKeyFile.GAME || 189 | (isPlugin && basename === WxapkgKeyFile.PLUGIN_JSON) 190 | ) 191 | }) 192 | if (!sp) ExtractorError.throw(`File ${this.pathCtrl.logpath} source directory not found`) 193 | this.sourcePath = PathController.make(sp.path || '.').dirname 194 | this.isExtracted = true 195 | } 196 | 197 | extract(save?: boolean) { 198 | super.extract() 199 | const buf = this.pathCtrl.readSync() 200 | if (!checkMacEncryption(buf)) { 201 | const target = link(info('https://github.com/TinyNiko/mac_wxapkg_decrypt')) 202 | ExtractorError.throw( 203 | `Package ${this.pathCtrl.logpath} is an encrypted package for Mac 204 | please use ${target} to decrypt it before using it`, 205 | ) 206 | } 207 | this.extractInner(buf) 208 | save && this.save() 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /src/core/parser/BaseParser.ts: -------------------------------------------------------------------------------- 1 | import { Saver } from '@utils/classes/Saver' 2 | import { BaseError } from '@utils/exceptions' 3 | import { BaseLogger } from '@utils/logger' 4 | 5 | export class ParserError extends BaseError {} 6 | export abstract class BaseParser extends BaseLogger { 7 | protected saver: Saver 8 | protected constructor(saver: Saver) { 9 | super() 10 | this.saver = saver 11 | } 12 | abstract parse(...args: unknown[]): unknown 13 | } 14 | -------------------------------------------------------------------------------- /src/core/parser/wxapkg/AppConfigParser.ts: -------------------------------------------------------------------------------- 1 | import { ParserError, BaseParser } from '../BaseParser' 2 | import { WxapkgKeyFile } from '@/enum' 3 | import { PathController, ProduciblePath } from '@core/controller/PathController' 4 | import { Visitor } from '@babel/core' 5 | import { AppConfigServiceSubject, S2Observable, TVSubject } from '@core/parser/wxapkg/types' 6 | import { Saver } from '@utils/classes/Saver' 7 | import { filter } from 'observable-fns' 8 | import { md5 } from '@utils/crypto' 9 | import { findBuffer } from '@core/controller/SaveController' 10 | import { info } from '@utils/colors' 11 | 12 | interface PageInfo { 13 | [key: string]: { 14 | window: { usingComponents: { [key: string]: unknown }; [key: string]: unknown } 15 | } 16 | } 17 | interface TabBarItem { 18 | iconPath?: string 19 | iconData?: string 20 | selectedIconPath?: string 21 | selectedIconData?: string 22 | pagePath?: string 23 | } 24 | export class AppConfigParser extends BaseParser { 25 | private serviceSource: string 26 | private sources: string 27 | isGame = false 28 | 29 | constructor(saver: Saver) { 30 | super(saver) 31 | } 32 | async parse(observable: S2Observable): Promise { 33 | try { 34 | if (this.isGame) return this.parseGame() 35 | const dirCtrl = this.saver.saveDirectory 36 | const config = { 37 | ...JSON.parse(this.sources), 38 | pop(key, _default?: T): T { 39 | const result = config[key] 40 | delete config[key] 41 | return result || _default 42 | }, 43 | } 44 | // 处理入口 45 | const entryPagePath = PathController.make(config.pop('entryPagePath')) 46 | const pages: string[] = config.pop('pages') 47 | const global = config.pop('global') 48 | const epp = entryPagePath.whitout().unixpath 49 | const seenPage = new Set() 50 | const save = (path: ProduciblePath, buffer: string | object) => { 51 | const filename = PathController.make(path).unixpath 52 | if (seenPage.has(filename)) return 53 | seenPage.add(filename) 54 | this.saver.add(path, buffer) 55 | } 56 | pages.splice(pages.indexOf(epp), 1) 57 | pages.unshift(epp) 58 | // 处理分包路径 59 | const subPackages: { [key: string]: unknown }[] = config.pop('subPackages') 60 | if (subPackages) { 61 | subPackages.forEach((subPack) => { 62 | const root = subPack.root as string 63 | const _subPages = (subPack.pages as string[]) || pages.filter((p) => p.startsWith(root)) 64 | subPack.pages = _subPages.map((page) => { 65 | const _index = pages.indexOf(page) 66 | _index > 0 && pages.splice(_index, 1) 67 | return page.replace(root, '') 68 | }) 69 | }) 70 | this.logger.info(`AppConfigParser detected ${info(subPackages.length.toString())} subpackages`) 71 | } 72 | // 处理 ext.json 73 | const extAppid = config.pop('extAppid') 74 | const ext = config.pop('ext') 75 | if (extAppid && ext) { 76 | const logPath = dirCtrl.join('ext.json').writeJSONSync({ extEnable: true, extAppid, ext }).logpath 77 | this.logger.info(`Ext save to ${logPath}`) 78 | } 79 | // tabBar 80 | const tabBar = config.pop('tabBar') 81 | const ignoreSuffixes = 'wxml,wxs,wxss,html,json' 82 | if (tabBar && Array.isArray(tabBar.list)) { 83 | const hashMap: Record = Object.create(null) 84 | findBuffer(dirCtrl).forEach(({ key, buffer }) => { 85 | const pCtrl = PathController.unix(key) 86 | if (ignoreSuffixes.includes(pCtrl.suffixWithout)) return 87 | if (!Buffer.isBuffer(buffer)) return 88 | hashMap[md5(buffer)] = pCtrl.crop(dirCtrl.absunixpath).unixpath 89 | }) 90 | tabBar.list.forEach((item: TabBarItem) => { 91 | item.pagePath = PathController.make(item.pagePath).whitout().unixpath 92 | if (item.iconData) { 93 | const path = hashMap[md5(item.iconData, true)] 94 | if (path) { 95 | item.iconPath = PathController.make(path).unixpath 96 | delete item.iconData 97 | } 98 | } 99 | if (item.selectedIconData) { 100 | const path = hashMap[md5(item.selectedIconData, true)] 101 | if (path) { 102 | item.selectedIconPath = PathController.make(path).unixpath 103 | delete item.selectedIconData 104 | } 105 | } 106 | }) 107 | } 108 | // usingComponents 109 | const page: PageInfo = config.pop('page') 110 | config.pop('renderer') 111 | Object.keys(page).forEach((key) => { 112 | const usingComponents = page[key].window.usingComponents 113 | if (!usingComponents || !Object.keys(usingComponents).length) return 114 | Object.keys(usingComponents).forEach((k) => { 115 | const p = (usingComponents[k] as string).replace('plugin://', '/__plugin__/') 116 | const file = p.startsWith('/') ? p.slice(1) : PathController.make(key).join('..', p).unixpath 117 | page[file] = page[file] || Object.create(null) 118 | page[file].window = page[file].window || Object.create(null) 119 | page[file].window.component = true 120 | }) 121 | }) 122 | const result = Object.assign(config, { 123 | tabBar, 124 | subPackages, 125 | ...global, 126 | pages, 127 | }) 128 | save(WxapkgKeyFile.APP_JSON, result) 129 | // usingComponents -> json 130 | if (!this.serviceSource) ParserError.throw(`Service source not found!`) 131 | let resolve 132 | const promise = new Promise((_resolve) => (resolve = _resolve)) 133 | observable.pipe>(filter((v) => v.AppConfigService)).subscribe({ 134 | next: (value) => { 135 | Object.entries(value.AppConfigService).forEach((args) => save(...args)) 136 | }, 137 | complete() { 138 | Object.keys(page).forEach((key) => { 139 | let pCtrl = PathController.make(key) 140 | if (pCtrl.suffix !== '.json') pCtrl = pCtrl.whitout('.json') 141 | save(pCtrl, page[key]['window']) 142 | }) 143 | resolve && resolve() 144 | }, 145 | }) 146 | return promise 147 | } catch (e) { 148 | ParserError.throw('Parse failed! ' + e.message) 149 | } 150 | } 151 | parseGame() { 152 | const config = JSON.parse(this.sources) 153 | const subPackages = config['subPackages'] 154 | subPackages && this.logger.info(`AppConfigParser detected ${info(subPackages.length.toString())} subpackages`) 155 | this.saver.add(WxapkgKeyFile.GAME_JSON, this.sources) 156 | } 157 | 158 | setServiceSource(source: string) { 159 | this.serviceSource = source 160 | } 161 | setSources(sources: string) { 162 | this.sources = sources 163 | } 164 | setIsGame(isGame: boolean) { 165 | this.isGame = isGame 166 | } 167 | static visitor(subject: AppConfigServiceSubject): Visitor { 168 | return { 169 | AssignmentExpression(path) { 170 | const left = path.node.left 171 | if ( 172 | left && 173 | left.type === 'MemberExpression' && 174 | left.object.type === 'Identifier' && 175 | left.object.name === '__wxAppCode__' && 176 | left.property.type === 'StringLiteral' && 177 | left.property.value.endsWith('.json') 178 | ) { 179 | const key = left.property.value 180 | path.traverse({ 181 | ObjectExpression(p) { 182 | if (p.parentKey === 'right') { 183 | subject.next({ 184 | AppConfigService: { 185 | [key]: p.getSource(), 186 | }, 187 | }) 188 | } 189 | }, 190 | }) 191 | } 192 | }, 193 | } 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/core/parser/wxapkg/ScriptParser.ts: -------------------------------------------------------------------------------- 1 | import { BaseParser } from '../BaseParser' 2 | import { Visitor } from '@babel/core' 3 | import { S2Observable, ScriptParserSubject, TVSubject } from '@core/parser/wxapkg/types' 4 | import { Saver } from '@utils/classes/Saver' 5 | import { filter } from 'observable-fns' 6 | import { PathController } from '@core/controller/PathController' 7 | 8 | export class ScriptParser extends BaseParser { 9 | constructor(saver: Saver) { 10 | super(saver) 11 | } 12 | async parse(observable: S2Observable): Promise { 13 | let resolve 14 | const promise = new Promise((_resolve) => (resolve = _resolve)) 15 | observable.pipe>(filter((v) => v.ScriptParser)).subscribe({ 16 | next: (value) => { 17 | Object.entries(value.ScriptParser).forEach(([path, buffer]) => { 18 | // 小游戏插件以目录作为名字的define 19 | if (path.startsWith('__plugin__')) { 20 | if (!PathController.make(path).suffixWithout) { 21 | path = '__plugin__/index.js' 22 | } 23 | } 24 | this.saver.add(path, buffer) 25 | }) 26 | }, 27 | complete() { 28 | resolve && resolve() 29 | }, 30 | }) 31 | return promise 32 | } 33 | 34 | static visitor(subject: ScriptParserSubject): Visitor { 35 | return { 36 | CallExpression(path) { 37 | const callee = path.node.callee 38 | if (callee.type === 'Identifier' && callee.name === 'define') { 39 | const args = path.get('arguments') 40 | const [filenamePathNode, sourcePathNode] = args 41 | if (!filenamePathNode.isStringLiteral()) return 42 | if (sourcePathNode.node.type !== 'FunctionExpression') return 43 | const filename = filenamePathNode.node.value 44 | const body = sourcePathNode.get('body.body') 45 | const source = (Array.isArray(body) ? body : [body]).map((p) => p.getSource()).join('') 46 | subject.next({ 47 | ScriptParser: { 48 | [filename]: source, 49 | }, 50 | }) 51 | } 52 | }, 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/core/parser/wxapkg/WxmlParser.ts: -------------------------------------------------------------------------------- 1 | import { BaseParser } from '../BaseParser' 2 | import { Saver } from '@utils/classes/Saver' 3 | import { parseWxml } from '@utils/wxmlParserJs' 4 | import { S2Observable, TraverseResult, TVSubject, WxmlParserV3Subject, ZArray } from '@core/parser/wxapkg/types' 5 | import { Visitor } from '@babel/traverse' 6 | import { parseJSONFromJSCode } from '@utils/ast' 7 | import { filter } from 'observable-fns' 8 | 9 | const zArrayFunctionNameRE = /gz\$gwx\d*_[A-Za-z_0-9]+/ 10 | const scopeNameRE = /\$gwx\d*$|\$gwx\d*_[A-Za-z_0-9]+/ 11 | function getFirst(p: T | T[]) { 12 | return (Array.isArray(p) ? p : [p])[0] 13 | } 14 | function getZArrayKey(functionName: string): string { 15 | const match = functionName.match(/_\d+$/) 16 | return match ? match[0] : '' 17 | } 18 | function makeVisitor(result: TraverseResult): Visitor { 19 | const data: ZArray = { mul: Object.create(null) } 20 | const visitor = { 21 | FunctionExpression(path) { 22 | const parent = path.getFunctionParent() 23 | if (!parent) return 24 | if (!parent.isFunctionDeclaration()) return 25 | const fn = parent.get('id') 26 | if (!fn) return 27 | const functionName = fn.getSource() 28 | if (!zArrayFunctionNameRE.test(functionName)) return 29 | const zMap = {} // var a=11 30 | const zArr = [] // Z([3,'xx'])... 31 | const list = path.get('body.body') 32 | const blocks = Array.isArray(list) ? list : [list] 33 | blocks.forEach((p) => { 34 | if (p.isIfStatement() || p.isFunctionDeclaration()) return 35 | if (p.isVariableDeclaration()) { 36 | const declarations = p.get('declarations')[0] 37 | if (!declarations) return 38 | const { id, init } = declarations.node 39 | if (id.type === 'Identifier' && init.type === 'NumericLiteral') { 40 | zMap[id.name] = init.value 41 | } 42 | } else if (p.isExpressionStatement()) { 43 | const expr = p.get('expression') 44 | if (!expr.isCallExpression()) return 45 | const zArg = expr.get('arguments')[0] 46 | if (zArg.isArrayExpression() || zArg.isMemberExpression()) { 47 | zArr.push(parseJSONFromJSCode(zArg.getSource(), { ...zMap, z: zArr })) 48 | } 49 | } 50 | }) 51 | const key = getZArrayKey(functionName) 52 | if (!key) return 53 | data.mul[key] = zArr 54 | }, 55 | VariableDeclarator(path) { 56 | const id = path.get('id') 57 | const init = path.get('init') 58 | const defName = id.getSource() 59 | if (defName === 'nnm' && init.isObjectExpression()) { 60 | result.json = init.getSource() 61 | } 62 | }, 63 | } 64 | result.z = data 65 | return visitor 66 | } 67 | export class WxmlParser extends BaseParser { 68 | private sources: string 69 | constructor(saver: Saver) { 70 | super(saver) 71 | } 72 | async parse(observable: S2Observable): Promise { 73 | let resolve 74 | const promise = new Promise((_resolve) => (resolve = _resolve)) 75 | // 订阅wxml解析器 76 | observable.pipe>(filter((v) => v.WxmlParserV3)).subscribe({ 77 | next: (value) => { 78 | const data = value.WxmlParserV3 79 | if (!data) return 80 | const { code, json, z } = data 81 | const dir = this.dir 82 | parseWxml(code, dir, json, z).then((result) => { 83 | Object.entries(result).forEach((args) => this.saver.add(...args)) 84 | }) 85 | }, 86 | complete() { 87 | resolve && resolve() 88 | }, 89 | }) 90 | return promise 91 | } 92 | 93 | async parseV1() { 94 | const result = await parseWxml(this.sources, this.dir) 95 | Object.entries(result).forEach((args) => this.saver.add(...args)) 96 | } 97 | 98 | get dir() { 99 | return this.saver.saveDirectory.path 100 | } 101 | 102 | static visitorV3(subject: WxmlParserV3Subject): Visitor { 103 | return { 104 | BlockStatement(path) { 105 | const parent = path.parentPath 106 | if (!parent) return 107 | if (!parent.isFunctionExpression()) return 108 | const params = parent.get('params') 109 | if (params.length !== 2) return 110 | if (params[0].getSource() !== 'path' || params[1].getSource() !== 'global') return 111 | const fn = path.find((p) => p.isAssignmentExpression()) 112 | if (!fn) return 113 | const scopeName = getFirst(fn.get('left')).getSource() 114 | if (!scopeNameRE.test(scopeName)) return 115 | const result: TraverseResult = Object.create(null) 116 | path.traverse(makeVisitor(result)) 117 | const contents = path.get('body').filter((p) => !p.isIfStatement()) 118 | let next = 0 119 | const sourceIndex = contents.findIndex((p) => { 120 | if (p.isVariableDeclaration()) { 121 | const id = getFirst(p.get('declarations.0.id')) 122 | if (id && id.isIdentifier()) { 123 | const defineName = id.getSource() 124 | if (defineName === 'nv_require') { 125 | next = 1 126 | return true 127 | } 128 | return defineName === 'x' 129 | } 130 | } 131 | return false 132 | }) 133 | const source = contents 134 | .slice(sourceIndex + next) 135 | .map((p) => p.getSource()) 136 | .join('\n') 137 | result.scope = scopeName 138 | result.code = source 139 | subject.next({ WxmlParserV3: result }) 140 | }, 141 | } 142 | } 143 | 144 | setSource(sources: string) { 145 | this.sources = sources 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/core/parser/wxapkg/WxssParser.ts: -------------------------------------------------------------------------------- 1 | import { BaseParser } from '../BaseParser' 2 | import { PathController, ProduciblePath } from '@core/controller/PathController' 3 | import { matchScripts } from '@utils/matchScripts' 4 | import { 5 | Dict, 6 | S2Observable, 7 | TVSubject, 8 | WxssParserCommon2Subject, 9 | WxssParserCommonSubject, 10 | WxssParserSubject, 11 | } from '@core/parser/wxapkg/types' 12 | import { Visitor } from '@babel/core' 13 | import { Saver } from '@utils/classes/Saver' 14 | import { filter } from 'observable-fns' 15 | import { transformStyle } from '@utils/transformStyle' 16 | import { WxapkgKeyFile } from '@/enum' 17 | import { md5 } from '@utils/crypto' 18 | import { getLogger } from '@utils/logger' 19 | import { parseJSONFromJSCode } from '@utils/ast' 20 | import { findBuffer, getSaveController, saveAble2String } from '@core/controller/SaveController' 21 | 22 | function makeCStyleName(index: number): string { 23 | return `./@unveilr/wxss/unveilr.${md5(index.toString()).slice(-6)}.wxss` 24 | } 25 | export function styleConversion(k: string, source: string): string { 26 | const logger = getLogger('StyleConversion') 27 | const data = parseJSONFromJSCode(source) 28 | if (!Array.isArray(data)) return 29 | 30 | const handleEl = (el) => { 31 | if (!Array.isArray(el)) return el 32 | // [1] 是个分割符 33 | if (el.length === 1 && el[0] === 1) return '' 34 | switch (el[0]) { 35 | // 属性值单位 rpx 36 | case 0: 37 | return el[1] + 'rpx' 38 | // 导入 39 | case 2: { 40 | const _el = el[1] 41 | let path 42 | if (typeof _el === 'number') { 43 | path = makeCStyleName(_el) 44 | } else if (typeof _el === 'string') { 45 | path = _el 46 | } else { 47 | if (Array.isArray(_el)) return handleEl(_el) 48 | logger.warn(`Unprocessed element found: ${JSON.stringify(_el)}`) 49 | return '' 50 | } 51 | if (!path) return '' 52 | const target = PathController.make(k).relative(path).unixpath 53 | return target ? `@import "${path.replace('./', '/')}";\n` : '' 54 | } 55 | default: 56 | logger.warn(`Unprocessed data found: ${JSON.stringify(el)}`) 57 | return '' 58 | } 59 | } 60 | const newData = data.map((el) => handleEl(el)).join('') 61 | return transformStyle(newData).buffer 62 | } 63 | 64 | export class WxssParser extends BaseParser { 65 | constructor(saver: Saver) { 66 | super(saver) 67 | } 68 | 69 | static getHTMLStyleSource(findDir: ProduciblePath): string { 70 | const htmlSources: string[] = [] 71 | const findDirCtrl = PathController.make(findDir) 72 | const saveCtrl = getSaveController() 73 | const suffixes = ['.appservice.js', '.common.js', '.webview.js'] 74 | findBuffer(findDirCtrl).forEach(({ key, buffer }) => { 75 | const ctrl = PathController.make(key) 76 | if (ctrl.suffixWithout.toLowerCase() !== 'html') return 77 | if (ctrl.basename === WxapkgKeyFile.PAGE_FRAME_HTML) return 78 | const s = saveAble2String(buffer) 79 | s && htmlSources.push(matchScripts(s)) 80 | if (ctrl.suffixWithout.toLowerCase() === 'html') { 81 | suffixes.forEach((suffix) => saveCtrl.delete(ctrl.whitout(suffix).abspath)) 82 | } 83 | saveCtrl.delete(ctrl.abspath) 84 | }) 85 | return htmlSources.filter(Boolean).join(';\n') 86 | } 87 | 88 | async parse(observable: S2Observable): Promise { 89 | const addSaver = (data: Dict) => { 90 | Object.entries(data).forEach((args) => this.saver.add(...args)) 91 | } 92 | let resolve 93 | const promise = new Promise((_resolve) => (resolve = _resolve)) 94 | // 订阅公共样式 95 | observable.pipe>(filter((v) => v.WxssParserCommon)).subscribe({ 96 | next: (data) => addSaver(data.WxssParserCommon), 97 | complete() { 98 | resolve && resolve() 99 | }, 100 | }) 101 | // 订阅公共样式2 _C 102 | observable.pipe>(filter((v) => v.WxssParserCommon2)).subscribe({ 103 | next: (data) => addSaver(data.WxssParserCommon2), 104 | complete() { 105 | resolve && resolve() 106 | }, 107 | }) 108 | // 订阅非公共样式 109 | observable.pipe>(filter((v) => v.WxssParser)).subscribe({ 110 | next: (data) => addSaver(data.WxssParser), 111 | complete() { 112 | resolve && resolve() 113 | }, 114 | }) 115 | return promise 116 | } 117 | // 读取 `setCssToHead` 函数 118 | static visitorSetCssToHead(subject: WxssParserSubject): Visitor { 119 | return { 120 | CallExpression(path) { 121 | const callee = path.node.callee 122 | if (callee.type === 'Identifier' && callee.name === 'setCssToHead') { 123 | const args = path.get('arguments') 124 | if (!args.length || (args.length === 1 && args[0].getSource() === '[]')) return 125 | // 第二项是错误信息 126 | if (args.length === 3) args.splice(1, 1) 127 | const [sources, _path] = args.map((p) => { 128 | const data = parseJSONFromJSCode(p.getSource()) 129 | return data.path ? data.path : data 130 | }) 131 | subject.next({ 132 | WxssParser: { 133 | [_path]: styleConversion(_path, JSON.stringify(sources)), 134 | }, 135 | }) 136 | } 137 | }, 138 | } 139 | } 140 | // 读取 `__COMMON_STYLESHEETS__` 141 | static visitorCommonStyle(subject: WxssParserCommonSubject): Visitor { 142 | return { 143 | MemberExpression(path) { 144 | const node = path.node 145 | if ( 146 | node.object.type === 'Identifier' && 147 | node.property.type === 'StringLiteral' && 148 | node.object.name === '__COMMON_STYLESHEETS__' 149 | ) { 150 | const p = node.property.value 151 | subject.next({ 152 | WxssParserCommon: { 153 | [p]: styleConversion(p, path.getOpposite().getSource()), 154 | }, 155 | }) 156 | } 157 | }, 158 | } 159 | } 160 | // 读取 `_C` 数组 161 | static visitorCArray(subject: WxssParserCommon2Subject): Visitor { 162 | return { 163 | VariableDeclarator(path) { 164 | const id = path.get('id') 165 | const init = path.get('init') 166 | if (!(id && init)) return 167 | if (id.isIdentifier() && id.getSource() === '_C' && init.isArrayExpression()) { 168 | init.get('elements').forEach((el, index) => { 169 | const p = makeCStyleName(index) 170 | subject.next({ 171 | WxssParserCommon2: { 172 | [p]: styleConversion(p, el.getSource()), 173 | }, 174 | }) 175 | }) 176 | } 177 | }, 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/core/parser/wxapkg/types.d.ts: -------------------------------------------------------------------------------- 1 | import { Visitor } from '@babel/core' 2 | import { Observable, Subject } from 'threads/observable' 3 | 4 | export interface TraverseVisitorMap { 5 | AppConfigService: Visitor 6 | WxssParser: Visitor 7 | WxssParserCommon: Visitor 8 | WxssParserCommon2: Visitor 9 | ScriptParser: Visitor 10 | WxmlParserV3: Visitor 11 | } 12 | export type TraverseVisitorKeys = keyof TraverseVisitorMap 13 | export type Dict = { [key: string]: T } 14 | export type SubjectType = { [name in K]: V } 15 | export type TVSubjectType = SubjectType 16 | export type TVSubject = Subject 17 | export type AppConfigServiceSubject = Subject> 18 | export type WxssParserSubject = Subject> 19 | export type WxssParserCommonSubject = Subject> 20 | export type WxssParserCommon2Subject = Subject> 21 | export type ScriptParserSubject = Subject> 22 | export type WxmlParserV3Subject = Subject> 23 | export type S2Observable> = T extends Subject ? Observable : never 24 | export type ParserLike = { 25 | parse(...args: Args[]): Ret 26 | } 27 | export type ZArray = { mul: Record } 28 | export interface TraverseResult { 29 | z: ZArray 30 | json: string 31 | code: string 32 | scope: string 33 | } 34 | -------------------------------------------------------------------------------- /src/core/workers/traverse.ts: -------------------------------------------------------------------------------- 1 | import { expose } from 'threads/worker' 2 | import { isWorkerRuntime } from '@utils/isWorkerRuntime' 3 | import { Observable, Subject } from 'threads/observable' 4 | import { TraverseVisitorKeys, TraverseVisitorMap, TVSubjectType } from '@core/parser/wxapkg/types' 5 | import { AppConfigParser } from '@core/parser/wxapkg/AppConfigParser' 6 | import { Visitor } from '@babel/core' 7 | import { WxssParser } from '@core/parser/wxapkg/WxssParser' 8 | import { ScriptParser } from '@core/parser/wxapkg/ScriptParser' 9 | import { TraverseController } from '@core/controller/TraverseController' 10 | import { WxmlParser } from '@core/parser/wxapkg/WxmlParser' 11 | import { initializeConfig } from '@core/controller/ConfigController' 12 | 13 | export function createExposed() { 14 | const subject = new Subject() 15 | const visitors: Partial = {} 16 | const visitorsFn: Record Visitor> = { 17 | AppConfigService: AppConfigParser.visitor, 18 | WxssParser: WxssParser.visitorSetCssToHead, 19 | WxssParserCommon: WxssParser.visitorCommonStyle, 20 | WxssParserCommon2: WxssParser.visitorCArray, 21 | ScriptParser: ScriptParser.visitor, 22 | WxmlParserV3: WxmlParser.visitorV3, 23 | } 24 | return { 25 | // worker 运行时需要复制一份配置 26 | initWorker(config: Parameters[0]) { 27 | initializeConfig(config) 28 | }, 29 | async startTraverse(code: string) { 30 | const tCtrl = new TraverseController({ code }) 31 | tCtrl.addVisitors(...Object.values(visitors)) 32 | await tCtrl.traverse() 33 | subject.complete() 34 | }, 35 | setVisitor(...keys: Array) { 36 | keys.forEach((key) => (visitors[key] = visitorsFn[key](subject))) 37 | }, 38 | observable() { 39 | return Observable.from(subject) 40 | }, 41 | } 42 | } 43 | 44 | if (isWorkerRuntime()) { 45 | expose(createExposed()) 46 | } 47 | 48 | export const traverseModule = module 49 | -------------------------------------------------------------------------------- /src/enum/PackageSuffix.ts: -------------------------------------------------------------------------------- 1 | // 包的文件名后缀 2 | export enum PackageSuffix { 3 | WXAPKG = 'wxapkg', 4 | } 5 | -------------------------------------------------------------------------------- /src/enum/Wxapkg.ts: -------------------------------------------------------------------------------- 1 | // 微信包关键文件名 2 | export enum WxapkgKeyFile { 3 | APP_CONFIG = 'app-config.json', 4 | APP_SERVICE = 'app-service.js', 5 | PAGE_FRAME_HTML = 'page-frame.html', 6 | APP_WXSS = 'app-wxss.js', 7 | COMMON_APP = 'common.app.js', 8 | APP_JSON = 'app.json', 9 | WORKERS = 'workers.js', 10 | PAGE_FRAME = 'page-frame.js', 11 | APPSERVICE = 'appservice.js', 12 | PAGEFRAME = 'pageframe.js', 13 | 14 | GAME = 'game.js', 15 | GAME_JSON = 'game.json', 16 | SUBCONTEXT = 'subContext.js', 17 | 18 | PLUGIN = 'plugin.js', 19 | PLUGIN_JSON = 'plugin.json', 20 | } 21 | 22 | export enum WxapkgType { 23 | /** 24 | * 包含文件 {@link WxapkgKeyFile.PAGE_FRAME_HTML} 25 | * 相关数据就保存在此文件中 26 | * */ 27 | APP_V1 = 'APP_V1', 28 | APP_V2 = 'APP_V2', 29 | APP_V3 = 'APP_V3', 30 | APP_V4 = 'APP_V4', 31 | /** 对标 {@link APP_V1},{@link APP_V2}*/ 32 | APP_SUBPACKAGE_V1 = 'APP_SUBPACKAGE_V1', 33 | /** 对标 {@link APP_V3}*/ 34 | APP_SUBPACKAGE_V2 = 'APP_SUBPACKAGE_V2', 35 | // 小程序插件 36 | APP_PLUGIN_V1 = 'APP_PLUGIN_V1', 37 | // 微信小游戏主包 38 | GAME = 'GAME', 39 | // 微信小游戏分包 40 | GAME_SUBPACKAGE = 'GAME_SUBPACKAGE', 41 | // 小游戏插件 42 | GAME_PLUGIN = 'GAME_PLUGIN', 43 | // runtime framework 44 | FRAMEWORK = 'FRAMEWORK', 45 | } 46 | -------------------------------------------------------------------------------- /src/enum/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Wxapkg' 2 | export * from './PackageSuffix' 3 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { PackageSuffix } from '@/enum' 2 | import { clearConsole } from '@utils/clearConsole' 3 | import { registerGlobalException } from '@utils/exceptions' 4 | import { PathController } from '@core/controller/PathController' 5 | import { WxapkgController } from '@core/controller/WxapkgController' 6 | import { initializeConfig, getConfig } from '@core/controller/ConfigController' 7 | import { getConfigurator } from '@utils/getConfigurator' 8 | import { SaveController } from '@core/controller/SaveController' 9 | export async function main() { 10 | initializeConfig(getConfigurator()) 11 | clearConsole() 12 | registerGlobalException() 13 | SaveController.setIsClean(getConfig('WXClearDecompile')) 14 | SaveController.setIsReFormat(getConfig('WXReformat')) 15 | const packages = getConfig('WXPackages') 16 | function filterWxapkg(ctrl: PathController) { 17 | return ctrl.isFile && ctrl.suffixWithout === PackageSuffix.WXAPKG 18 | } 19 | const depth = getConfig('WXDepth') 20 | const wxapkgList: PathController[] = [] 21 | for (const pack of packages) { 22 | const ctrl = PathController.make(pack) 23 | if (ctrl.isDirectory) { 24 | const list = ctrl 25 | .deepListDir(depth) 26 | .map((p) => PathController.make(p)) 27 | .filter((p) => filterWxapkg(p)) 28 | wxapkgList.push(...list) 29 | } else { 30 | wxapkgList.push(ctrl) 31 | } 32 | } 33 | return new WxapkgController({ 34 | wxapkgList, 35 | wxAppId: getConfig('WXAppId'), 36 | mainSaveDir: getConfig('WXOutput'), 37 | }).exploit() 38 | } 39 | main().then() 40 | -------------------------------------------------------------------------------- /src/lib/wxml-parser-js/index.d.ts: -------------------------------------------------------------------------------- 1 | import { ZArray } from '@core/parser/wxapkg/types' 2 | 3 | export interface ParserResult { 4 | [filename: string]: string 5 | } 6 | 7 | export function parseWxml(code: string, dir: string): Promise 8 | export function parseWxml(code: string, dir: string, json: string, z: ZArray): Promise 9 | 10 | -------------------------------------------------------------------------------- /src/lib/wxml-parser-js/index.js: -------------------------------------------------------------------------------- 1 | "use strict";var vendor=require("./vendor-e192f276.js"),require$$1=require("path");function _0x28ba(e,r){const t=_0x52a8();return(_0x28ba=function(e,r){return e-=211,t[e]})(e,r)}function removeInvalidLineCode$1(e){return e[_0x28ba(213)](/\s*[a-z]\x20?=\x20?VM2_INTERNAL_STATE_DO_NOT_USE_OR_PROGRAM_WILL_FAIL\.handleException\([a-z]\);?/g,"")}function toDir$1(t,n){var a=_0x28ba;"."==n[0]&&(n=n[a(222)](1)),"."==t[0]&&(t=t[a(222)](1)),n=n[a(213)](/\\/g,"/"),t=t[a(213)](/\\/g,"/");let o=Math[a(215)](t[a(214)],n[a(214)]);for(let e=1,r=Math.min(t[a(214)],n.length);e<=r;e++)if(!t.startsWith(n[a(222)](0,e))){o=e-1;break}let e=n[a(222)](0,o),r=e[a(219)]("/")+1,s=n[a(222)](r),i="";for(let e=0;e=":11,"<=":11,">":11,"<":11,"<<":12,">>":12,"-":3==r?13:16};return r[e]||0}function e(e){var r=f;let t=s(o[e],!0);return t=o[e]instanceof Object&&"object"==typeof o[e][0]&&2==o[e][0][0]&&i(n[1],o[r(173)])>i(o[e][0][1],o[e][r(173)])?u(t,"("):t}switch(n[1]){case"?:":a=e(1)+"?"+e(2)+":"+e(3);break;case"!":case"~":a=n[1]+e(1);break;case"-":if(3!=o.length){a=n[1]+e(1);break}default:a=e(1)+n[1]+e(2)}break;case 4:a=s(o[1],!0);break;case 5:switch(o[f(173)]){case 2:a=u(s(o[1],!0),"[");break;case 1:a="[]";break;default:var l=s(o[1],!0);a=l[f(174)]("[")&&l[f(197)]("]")?u("[]"!=l?l[f(177)](1,-1)[f(159)]()+","+s(o[2],!0):s(o[2],!0),"["):u(f(195)+l+","+s(o[2],!0),"[")}break;case 6:var p=s(o[2],!0);if(p._type===f(202))a=s(o[1],!0)+u(p,"[");else{let e="";e=/^[A-Za-z\_][A-Za-z\d\_]*$/[f(171)](p)?"."+p:u(p,"["),a=s(o[1],!0)+e}break;case 7:switch(o[1][0]){case 11:a=u("__unTestedGetValue:"+u(c(o),"["),"{");break;case 3:(a=new String(o[1][1]))[f(169)]=f(202);break;default:throw Error(f(201))}break;case 8:a=u(o[1]+":"+s(o[2],!0),"{");break;case 9:{function x(e){var r=f;return e.startsWith(r(195))?1:e[r(174)]("{")&&e.endsWith("}")?0:2}let e=s(o[1],!0),r=s(o[2],!0),t=x(e),n=x(r);a=2==t||2==n?u(f(161)+u(e+","+r,"["),"{"):(t||(e=e.slice(1,-1)[f(159)]()),n||(r=r[f(177)](1,-1).trim()),u(e+","+r,"{"));break}case 10:a=f(195)+s(o[1],!0);break;case 12:p=s(o[2],!0);a=p[f(174)]("[")&&p.endsWith("]")?s(o[1],!0)+u(p[f(177)](1,-1)[f(159)](),"("):s(o[1],!0)+".apply"+u(f(179)+p,"(");break;default:a=u(f(180)+c(o),"{")}return r(a)}switch(n){case 3:return o[1];case 1:return r(c(o[1]));case 11:let e="";o[f(188)]();for(var a of o)e+=s(a);return e}}function restoreGroup$1(e){var r,t=_0x7127,n={};for(r in e[t(182)]){var a,o=[];for(a of e.mul[r])o[t(165)](restoreSingle(a,!1));n[r]=o}var s={};return s.mul=n,s}function _0x3f11(){const e=["(z);__WXML_GLOBAL__.ops_set.$gwx=z;","(function(z){var a=11;function Z(ops,debugLine){","GetZArray fail: ","...","1048lfexad","endsWith","2351380WcGLnI","match","join","Unknown type to get value","var","string","10251MvScoJ","1980419gjqdau","trim","(z);__WXML_GLOBAL__.ops_set.$gwx","__unkownMerge:","toString","4gQAghQ","split","push","Unknown brace type ","null","stringify","_type","})(z);","test","object","length","startsWith","541173JyMarP","run","slice","(function(z){var a=11;function Z(ops){z.push(ops)}","null,","__unkownSpecific:","indexOf","mul","1359968nDVGKm","11742950noUuTe","(z);","12vPMYOA","lastIndexOf","shift","219871LxJVdv","})(__WXML_GLOBAL__.ops_cached.$gwx","undefined"];return(_0x3f11=function(){return e})()}function restoreAll(e){var r=_0x7127;if(e[r(182)])return restoreGroup$1(e);var t,n=[];for(t of e)n[r(165)](restoreSingle(t,!1));return n}async function parserZArray$1(e){return new Promise((r,t)=>{var n=_0x7127;try{catchZ(e,e=>r(restoreAll(e)))}catch(e){t(Error(n(194)+e.message))}})}var parseZArray={parserZArray:parserZArray$1,restoreGroup:restoreGroup$1};function _0x57da(){const e=["wx:for-item","run","mul","wx:key","IfStatement","lastIndexOf","item","operator","includes","_oz","trimLeft","Unknown member expression","AssignmentExpression","})(z);d_[","resolve","trim","declarations","function","340823migwEQ","push","type","return nv_module.nv_exports;}","assign","\n}catch(","\nvar nv_require=function(){var nnm=","test","Parsing wxml failed, Unsupported file","wx:for","consequent","44OMeBJS","","324022drxflK","CallExpression","expression","parseScript","slice","tag","10357960JcwPFC","_mz","indexOf","wx:else","2220sOJwEQ","84ZZpCUu","424713jIAWTE","_ic","template","310885SSGLWN","func","Unknown expression callee name ","argument","arguments","name","son","return","VariableDeclaration",'"/>',"left","nv_module={nv_exports:{}};","\ntry{","_af","__textNode__","body","()\r\n","if(path&&e_[path]){","gen","undefined","content","_1z","repeat","index","block","_2z","Unknown callee type ","Unknown member expression declaration.","596892FuMZOm","property","Identifier","Unknown declaration init type ","FunctionExpression","wx:if","wxXCkey","MemberExpression","trimRight","BlockStatement","_gd","var x = [...new Set(Object.keys(e_))]","alternate","init","UnaryExpression","pop","Unknown type of object in _mz attrs array: ","callee","_ai","generate","\n__receive__([x,","LogicalExpression",'" src="',"()\n","toString","length","textNode","var z=gz$gwx","37602xcCSlW","Unknown if statement test callee name:","Unknown if statement.","replace","object","Unexpected fake pool","elements","ExpressionStatement","join","value","6vWBoQV","187DQyuer","Unknown type of object in _m attrs array: "];return(_0x57da=function(){return e})()}function _0x3b12(e,r){const t=_0x57da();return(_0x3b12=function(e,r){return e-=451,t[e]})(e,r)}!function(){for(var e=_0x3b12,r=_0x57da();;)try{if(901502==+parseInt(e(452))+-parseInt(e(555))/2*(-parseInt(e(521))/3)+parseInt(e(553))/4*(parseInt(e(455))/5)+-parseInt(e(451))/6*(-parseInt(e(542))/7)+-parseInt(e(561))/8+parseInt(e(511))/9*(parseInt(e(565))/10)+parseInt(e(522))/11*(-parseInt(e(483))/12))break;r.push(r.shift())}catch(e){r.push(r.shift())}}();const path=require$$1,VM=vendor.vm2Exports["VM"],esprima=vendor.esprimaExports,escodegen=vendor.escodegen,{parserZArray,restoreGroup}=parseZArray,{removeInvalidLineCode,toDir,getZArrayKey}=utils,saveMapper={};function analyze(a,o,s,i,f={},u="0"){const c=_0x3b12;function l(e,r={}){analyze(e,o,s,i,r,u)}function e(e,r){s[e]=r}function p(e,r){var t=_0x3b12;(f[e]?f:s)[e][t(461)][t(543)](r)}for(let n=0;n\n":x+">\n";var v,_=[x+=">\n"];for(v of t[o(461)])_[o(543)](s(v,n+1));return _.push(e[o(477)](n)+"\n"),i(_)}function doWxml(o,e,r,t,s,i,f,n,u){var c=_0x3b12,a=t[c(559)](t[c(529)](c(462))+6).replace(/[;}]/g,"").trim(),l=(t=t.slice(t.indexOf("\n"),t.lastIndexOf(c(462)))[c(539)](),{son:[]}),p=(analyze(esprima[c(558)](t)[c(470)],s,{[a]:l},i,{[a]:l}),[]);for(const d of l[c(461)])p.push(elemToString(d,0,u));var x,v=[p[c(519)]("")];for(x in f){let r=f[o[0]=x][c(507)](),e=r[c(559)](r.lastIndexOf(c(462))+6).replace(/[;}]/g,"")[c(539)](),t=r[c(563)](c(467)),n=r.indexOf(c(510)),a=r[c(559)](t+5,r[c(529)](c(547)))[c(539)]();if(-1!==n&&ne}}});c[a(525)](e+a(503)+t+"])");var l,p={},x={};for(const h in i){var v=path.resolve(r,("/"===h[0]?".":"")+h),_=i[h];if(typeof _==a(541)){var d=_();p[d]=h,saveMapper[v]=doWxs(f[d][a(507)](),h)}else if(typeof _==a(515)){var m=[];for(const y in _){var g,b=_[y]();b.includes(":")?(g=doWxs(f[b][a(507)]()),m.push(''+g+a(554))):(g=p[b]||b[a(559)](2),b=toDir(g,h),m[a(543)](' { 8 | console.log(JSON.stringify(result).length) 9 | JSON.stringify(result).length === 50282 && console.log('√ 改动不会影响结果') 10 | }) 11 | 12 | export {} 13 | -------------------------------------------------------------------------------- /src/utils/ast.ts: -------------------------------------------------------------------------------- 1 | import * as babel from '@babel/core' 2 | import { traverse, Visitor, BabelFileResult } from '@babel/core' 3 | import { TraverseOptions } from '@babel/traverse' 4 | import { isProduciblePath, PathController, ProduciblePath } from '@core/controller/PathController' 5 | import { error } from '@utils/colors' 6 | 7 | export async function buildAST(path: ProduciblePath): Promise 8 | export async function buildAST(code: string, filename: string): Promise 9 | 10 | export async function buildAST(v: unknown, filename?: string): Promise { 11 | let code: string = v as string 12 | if (!filename) { 13 | const pCtrl = PathController.make(v as ProduciblePath) 14 | filename = pCtrl.abspath 15 | code = await pCtrl.read('utf8') 16 | } 17 | const ast = await babel.parseAsync(code, { sourceFileName: filename }) 18 | return new babel['File']({ filename }, { ast, code }) 19 | } 20 | 21 | export type BuildParams = { code: string; filename?: string } 22 | 23 | export async function traverseAST(path: ProduciblePath, opt?: TraverseOptions): Promise 24 | export async function traverseAST(builder: BuildParams, opt?: TraverseOptions): Promise 25 | export async function traverseAST(file: BabelFileResult, opt?: TraverseOptions): Promise 26 | export async function traverseAST(v: unknown, opt: TraverseOptions): Promise { 27 | if (isProduciblePath(v)) { 28 | const file = await buildAST(v) 29 | return traverse(file.ast, opt) 30 | } 31 | if (typeof v === 'object' && v['code'] && (v['filename'] = v['filename'] || '.')) { 32 | const file = await buildAST(v['code'], v['filename']) 33 | return traverse(file.ast, opt) 34 | } 35 | return traverse((v as BabelFileResult).ast, opt) 36 | } 37 | export { Visitor } 38 | 39 | export function parseJSONFromJSCode(code: string, context?: object) { 40 | // 防止恶意代码 41 | const file = new babel['File']({ filename: '.' }, { ast: babel.parseSync(code), code }) 42 | traverse(file.ast, { 43 | CallExpression(path) { 44 | throw Error(`This code snippet is not safe: ${error(path.getSource())}`) 45 | }, 46 | AssignmentExpression(path) { 47 | throw Error(`This code snippet is not safe: ${error(path.getSource())}`) 48 | }, 49 | }) 50 | const fn = Function('context', `with(context){return JSON.stringify(${code})}`) 51 | try { 52 | return JSON.parse(fn({ JSON, ...context })) 53 | } catch (e) { 54 | console.log(fn.toString()) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/utils/checkWxapkg.ts: -------------------------------------------------------------------------------- 1 | import { WxapkgKeyFile, WxapkgType } from '@/enum' 2 | import { isProduciblePath, PathController, ProduciblePath } from '@core/controller/PathController' 3 | 4 | export function checkMacEncryption(buf: Buffer): boolean { 5 | const encryptedForMac = 'WAPkgEncryptedTagForMac' 6 | return buf.subarray(-encryptedForMac.length).toString() !== encryptedForMac 7 | } 8 | export function checkWxapkg(path: ProduciblePath): boolean 9 | export function checkWxapkg(buff: Buffer): boolean 10 | export function checkWxapkg(v: ProduciblePath | Buffer): boolean { 11 | const buf = (isProduciblePath(v) ? PathController.make(v).readSync() : v) as Buffer 12 | return buf.readUInt8(0) === 0xbe && buf.readUInt8(13) === 0xed 13 | } 14 | 15 | function _getWxapkgType(fileList: string[]): WxapkgType { 16 | if (fileList.every((filename) => filename.startsWith('WA'))) return WxapkgType.FRAMEWORK 17 | // APP_V1/APP_V4 18 | if (fileList.includes(WxapkgKeyFile.PAGE_FRAME_HTML)) { 19 | if (fileList.includes(WxapkgKeyFile.COMMON_APP)) return WxapkgType.APP_V4 20 | return WxapkgType.APP_V1 21 | } 22 | // APP_V3/APP_SUBPACKAGE_V2 23 | if (fileList.includes(WxapkgKeyFile.COMMON_APP)) 24 | return fileList.includes(WxapkgKeyFile.APP_WXSS) ? WxapkgType.APP_V3 : WxapkgType.APP_SUBPACKAGE_V2 25 | // APP_V2/APP_SUBPACKAGE_V1 26 | if (fileList.includes(WxapkgKeyFile.PAGE_FRAME)) 27 | return fileList.includes(WxapkgKeyFile.APP_WXSS) ? WxapkgType.APP_V2 : WxapkgType.APP_SUBPACKAGE_V1 28 | // GAME/GAME_SUBPACKAGE 29 | if (fileList.includes(WxapkgKeyFile.GAME)) 30 | return fileList.includes(WxapkgKeyFile.APP_CONFIG) ? WxapkgType.GAME : WxapkgType.GAME_SUBPACKAGE 31 | // APP_PLUGIN_V1/GAME_PLUGIN 32 | if (fileList.includes(WxapkgKeyFile.PLUGIN_JSON)) { 33 | if (fileList.includes(WxapkgKeyFile.APPSERVICE)) return WxapkgType.APP_PLUGIN_V1 34 | if (fileList.includes(WxapkgKeyFile.PLUGIN)) return WxapkgType.GAME_PLUGIN 35 | } 36 | // not found 37 | return null 38 | } 39 | export function checkWxapkgType(path: ProduciblePath): Promise 40 | export function checkWxapkgType(list: string[]): WxapkgType 41 | export function checkWxapkgType(v: ProduciblePath | string[]): Promise | WxapkgType { 42 | if (isProduciblePath(v)) { 43 | const pCtrl = PathController.make(v) 44 | if (!pCtrl.isDirectory) throw Error(`Path ${v} is not a directory`) 45 | return pCtrl.readdir().then((fileList) => _getWxapkgType(fileList)) 46 | } else { 47 | return _getWxapkgType(v) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/utils/classes/Saver.ts: -------------------------------------------------------------------------------- 1 | import { PathController, ProduciblePath } from '@core/controller/PathController' 2 | import { BaseLogger } from '@utils/logger' 3 | import { BaseError } from '@utils/exceptions' 4 | import { getSaveController, SaveAble, SaveController } from '@core/controller/SaveController' 5 | import { isWorkerRuntime } from '@utils/isWorkerRuntime' 6 | 7 | export class SavingError extends BaseError {} 8 | interface SaverItem { 9 | path: ProduciblePath 10 | buffer: SaveAble 11 | } 12 | export class Saver extends BaseLogger { 13 | private baseDir: PathController 14 | private saveList: SaverItem[] 15 | private readonly saveCtrl: SaveController 16 | constructor(baseDir?: ProduciblePath) { 17 | if (isWorkerRuntime()) throw Error(`Saver cannot run on Worker!`) 18 | super() 19 | this.saveList = [] 20 | this.saveDirectory = baseDir 21 | this.saveCtrl = getSaveController() 22 | } 23 | set saveDirectory(dir: ProduciblePath) { 24 | this.baseDir = PathController.make(dir) 25 | } 26 | get saveDirectory(): PathController { 27 | return this.baseDir 28 | } 29 | 30 | add(path: ProduciblePath, buffer: SaveAble, force?: boolean): this { 31 | const ctrl = PathController.make(path) 32 | if (ctrl.isAbs) { 33 | this.saveCtrl.set(ctrl.path, buffer) 34 | } else if (force) { 35 | this.saveCtrl.set(ctrl.abspath, buffer) 36 | } else { 37 | this.saveList.push({ path, buffer }) 38 | } 39 | return this 40 | } 41 | /** 42 | * @desc 合并到全局桶内 43 | * @description 为什么不直接放到桶内? 44 | * 因为 baseDir 会变化, 45 | * 需要重新计算最终路径 46 | * */ 47 | merge(): this { 48 | this.saveList.forEach((item) => { 49 | const { path, buffer } = item 50 | const pCtrl = PathController.make(path) 51 | let target = pCtrl 52 | if (!pCtrl.isAbs) { 53 | if (!this.baseDir) SavingError.throw(`BaseDir is not a directory!`) 54 | target = this.baseDir.join(pCtrl.path) 55 | } 56 | this.saveCtrl.set(target.abspath, buffer) 57 | }) 58 | return this 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/utils/clearConsole.ts: -------------------------------------------------------------------------------- 1 | export function clearConsole(toStart?: boolean): void { 2 | process.stdout.write('\u001b[2J') 3 | process.stdout.write('\u001b[1;1H') 4 | toStart && process.stdout.write('\u001b[3J') 5 | } 6 | -------------------------------------------------------------------------------- /src/utils/colors.ts: -------------------------------------------------------------------------------- 1 | import chalk from 'chalk' 2 | export const info = chalk.blue.bold 3 | export const error = chalk.white.bgRed 4 | export const grey = chalk.grey.bold 5 | export const link = chalk.underline 6 | export const bold = chalk.bold 7 | export const red = chalk.red 8 | export const yellow = chalk.yellow 9 | export const green = chalk.green 10 | -------------------------------------------------------------------------------- /src/utils/crypto.ts: -------------------------------------------------------------------------------- 1 | import * as CryptoJS from 'crypto-js' 2 | 3 | export function BufferToWordArray(buffer: Buffer): CryptoJS.lib.WordArray { 4 | return CryptoJS.lib.WordArray.create(buffer as unknown as number[], buffer.length) 5 | } 6 | 7 | export function WordArrayToBuffer(wordArray: CryptoJS.lib.WordArray): Buffer { 8 | return Buffer.from(wordArray.toString(CryptoJS.enc.Hex), 'hex') 9 | } 10 | 11 | export function encryptBuffer(buffer: Buffer, password: string, salt: string, iv: string): Buffer { 12 | if (buffer.length % 32 !== 0) throw Error('Invalid buffer Length: ' + buffer.length) 13 | const key = CryptoJS.PBKDF2(password, salt, { 14 | keySize: 256 / 32, 15 | iterations: 1000, 16 | hasher: CryptoJS.algo.SHA1, 17 | }) 18 | const cipher = CryptoJS.AES.encrypt(BufferToWordArray(buffer), key, { 19 | iv: CryptoJS.enc.Utf8.parse(iv), 20 | mode: CryptoJS.mode.CBC, 21 | padding: CryptoJS.pad.NoPadding, 22 | }) 23 | return WordArrayToBuffer(cipher.ciphertext) 24 | } 25 | 26 | export function decryptBuffer(buffer: Buffer, password: string, salt: string, iv: string): Buffer { 27 | if (buffer.length % 32 !== 0) throw Error('Invalid buffer Length: ' + buffer.length) 28 | const key = CryptoJS.PBKDF2(password, salt, { 29 | keySize: 256 / 32, 30 | iterations: 1000, 31 | hasher: CryptoJS.algo.SHA1, 32 | }) 33 | const cipher = CryptoJS.AES.decrypt(BufferToWordArray(buffer).toString(CryptoJS.enc.Base64), key, { 34 | iv: CryptoJS.enc.Utf8.parse(iv), 35 | mode: CryptoJS.mode.CBC, 36 | padding: CryptoJS.pad.NoPadding, 37 | }) 38 | return WordArrayToBuffer(cipher) 39 | } 40 | export function md5(b64Str: string, fromBase64: true): string 41 | export function md5(buffer: Buffer): string 42 | export function md5(message: string): string 43 | export function md5(_message: string | Buffer | CryptoJS.lib.WordArray, fromBase64?: boolean): string { 44 | let message: string | CryptoJS.lib.WordArray 45 | if (typeof _message === 'string' && fromBase64) { 46 | message = CryptoJS.enc.Base64.parse(_message) 47 | } else if (_message instanceof Buffer) { 48 | message = BufferToWordArray(_message) 49 | } else message = _message 50 | return CryptoJS.MD5(message).toString(CryptoJS.enc.Hex) 51 | } 52 | -------------------------------------------------------------------------------- /src/utils/exceptions.ts: -------------------------------------------------------------------------------- 1 | import { BaseLogger } from '@utils/logger' 2 | 3 | class GlobalExceptionCaught extends BaseLogger { 4 | constructor() { 5 | super('Exception') 6 | const ignores = 'exit,cancel,pass'.split(',') 7 | const handler = (e: Error | string) => (ignores.includes(String(e)) ? '' : this.logger.error(e)) 8 | process.on('uncaughtException', handler) 9 | process.on('unhandledRejection', handler) 10 | this.logger.debug('Global exception interception is enabled') 11 | } 12 | } 13 | 14 | export function registerGlobalException() { 15 | return new GlobalExceptionCaught() 16 | } 17 | 18 | export class BaseError extends Error { 19 | constructor(msg: string) { 20 | super(msg) 21 | this.name = this.constructor.name 22 | Error.captureStackTrace && Error.captureStackTrace(this, this.constructor) 23 | } 24 | 25 | static make(msg: string) { 26 | return new this(msg) 27 | } 28 | 29 | static throw(msg: string) { 30 | throw this.make(msg) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/utils/getConfigurator.ts: -------------------------------------------------------------------------------- 1 | import { isDevelopment } from '@utils/isDev' 2 | import { CliConfigurator, registerCommand } from '@/cli' 3 | import { version, name } from '../../package.json' 4 | 5 | export function getConfigurator(dev?: boolean): CliConfigurator { 6 | const IS_DEV = dev || isDevelopment() 7 | if (!IS_DEV) return registerCommand(version, name) 8 | return { 9 | global: { 10 | logLevel: 'info', 11 | }, 12 | wx: { 13 | // appid: '', 14 | format: true, 15 | clearDecompile: true, 16 | clearSave: true, 17 | parse: true, 18 | depth: 1, 19 | // output: '', 20 | packages: ['files'], 21 | }, 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/utils/getWccVersion.ts: -------------------------------------------------------------------------------- 1 | export function getWccVersion(source: string): string | null { 2 | const regex = /\/\*(v\S+?)\*\// 3 | if (!source) return null 4 | const result = source.match(regex) 5 | if (Array.isArray(result) && result[1]) return result[1] 6 | return null 7 | } 8 | -------------------------------------------------------------------------------- /src/utils/hasOwnProperty.ts: -------------------------------------------------------------------------------- 1 | export function hasOwnProperty(o: T, name: keyof T): boolean { 2 | return Object.prototype.hasOwnProperty.call(o, name) 3 | } 4 | -------------------------------------------------------------------------------- /src/utils/isDev.ts: -------------------------------------------------------------------------------- 1 | import { PathController } from '@core/controller/PathController' 2 | export function isDevelopment() { 3 | return PathController.make(process.argv[1]).suffixWithout === 'ts' 4 | } 5 | -------------------------------------------------------------------------------- /src/utils/isWorkerRuntime.ts: -------------------------------------------------------------------------------- 1 | import { isMainThread } from 'worker_threads' 2 | 3 | export function isWorkerRuntime(): boolean { 4 | return !isMainThread 5 | } 6 | -------------------------------------------------------------------------------- /src/utils/logger.ts: -------------------------------------------------------------------------------- 1 | import { bold, grey, yellow } from '@utils/colors' 2 | import { createLogger, format, Logger, transports } from 'winston' 3 | import { getConfig } from '@core/controller/ConfigController' 4 | 5 | const { combine, timestamp, printf, colorize } = format 6 | const levels = { error: 0, warn: 1, info: 2, debug: 3 } 7 | 8 | export type LoggerLevel = keyof typeof levels 9 | export function getLogger(name?: string, level?: LoggerLevel): Logger { 10 | return createLogger({ 11 | level: level || getConfig('logLevel'), 12 | levels, 13 | format: combine( 14 | timestamp({ format: 'HH:mm:ss' }), 15 | printf((info) => { 16 | const LEVEL = `[${bold(info.level.toUpperCase())}]` 17 | const TIME = grey(info.timestamp) 18 | const SCOPE = yellow(`<${info.scope}>`) 19 | const MESSAGE = ((m) => { 20 | if (m instanceof Error) return m.stack 21 | return m.message 22 | })(info) 23 | return [LEVEL, TIME, SCOPE, MESSAGE].join(' ') 24 | }), 25 | colorize({ all: true }), 26 | ), 27 | defaultMeta: { scope: name || 'Core' }, 28 | transports: [new transports.Console({ stderrLevels: ['error'] })], 29 | }) 30 | } 31 | export class BaseLogger { 32 | readonly logger: Logger 33 | constructor(name?: string, level?: LoggerLevel) { 34 | name = name || this.constructor.name 35 | this.logger = getLogger(name.length < 4 ? void 0 : name, level) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/utils/matchScripts.ts: -------------------------------------------------------------------------------- 1 | export function matchScripts(source: string): string { 2 | const matchRegex = /]*>(?[\s\S]*?)<\/script>/m 3 | const matchResult: string[] = [] 4 | const _matchAll = (str: string) => { 5 | const r = str.match(matchRegex) 6 | if (!r || !r.groups) return 7 | matchResult.push(r.groups.source.trim()) 8 | _matchAll(str.replace(matchRegex, '')) 9 | } 10 | _matchAll(source) 11 | return matchResult.filter(Boolean).join(';\n') 12 | } 13 | -------------------------------------------------------------------------------- /src/utils/reformat.ts: -------------------------------------------------------------------------------- 1 | import { BuiltInParserName, format } from 'prettier' 2 | import { PathController, ProduciblePath } from '@core/controller/PathController' 3 | 4 | export const REFORMAT_MAP: Record = { 5 | wxss: 'css', 6 | json: 'json', 7 | wxs: 'babel', 8 | js: 'babel', 9 | wxml: 'html', 10 | } 11 | export function reformat(path: ProduciblePath, source: string): string { 12 | try { 13 | const suffix = checkSupport(path) 14 | if (!suffix) return source 15 | return format(source, { parser: REFORMAT_MAP[suffix] }) 16 | } catch (e) { 17 | if (e instanceof SyntaxError) return source 18 | throw e 19 | } 20 | } 21 | 22 | export function checkSupport(path: ProduciblePath): string | false { 23 | const ctrl = PathController.make(path) 24 | const suffix = ctrl.suffixWithout 25 | return Object.keys(REFORMAT_MAP).includes(suffix) ? suffix : false 26 | } 27 | -------------------------------------------------------------------------------- /src/utils/transformStyle.ts: -------------------------------------------------------------------------------- 1 | import { parse, generate, walk, CssNode, Raw, TypeSelector, List, ListItem, Declaration, Value } from 'css-tree' 2 | export type TransformStyleResult = { 3 | buffer: string 4 | path?: string 5 | } 6 | export function transformStyle(style: string, path?: string): TransformStyleResult { 7 | const ast = parse(style) 8 | walk(ast, function (node) { 9 | switch (node.type) { 10 | case 'Comment': 11 | { 12 | const _node = node as unknown as Raw 13 | _node.type = 'Raw' 14 | _node.value = '\n/*' + node.value + '*/\n' 15 | } 16 | break 17 | case 'TypeSelector': 18 | { 19 | const name = node.name 20 | const _node = node as TypeSelector 21 | if (name.startsWith('wx')) { 22 | _node.name = name.slice(3) 23 | } else if (name === 'body') { 24 | _node.name = 'page' 25 | } 26 | } 27 | break 28 | } 29 | if ('children' in node && node.children) { 30 | const removeType = ['webkit', 'moz', 'ms', 'o'] 31 | const temp: { [key: string]: ListItem } = {} 32 | const retNodeChildren = node.children as List 33 | retNodeChildren.forEach((item, nodeItem) => { 34 | if (item.type === 'Declaration') { 35 | if (temp[item.property]) { 36 | const tempNode = temp[item.property] 37 | const tempNodeData = tempNode.data 38 | let result: ListItem 39 | const itemValue = item.value 40 | const tempNodeValue = (tempNodeData as Declaration).value 41 | if (itemValue.type == 'Raw' && itemValue.value.startsWith('progid:DXImageTransform')) { 42 | retNodeChildren.remove(nodeItem) 43 | result = tempNode 44 | } else if (tempNodeValue.type == 'Raw' && tempNodeValue.value.startsWith('progid:DXImageTransform')) { 45 | retNodeChildren.remove(tempNode) 46 | result = nodeItem 47 | } else { 48 | const _itemValue = itemValue as Value 49 | const _tempNodeData = tempNodeData as Value 50 | let xValue = 51 | _itemValue.children && 52 | _itemValue.children.first && 53 | 'name' in _itemValue.children.first && 54 | (_itemValue.children.first.name as string | undefined) 55 | let yValue = 56 | _tempNodeData.children && 57 | _tempNodeData.children.first && 58 | 'name' in _tempNodeData.children.first && 59 | (_tempNodeData.children.first.name as string | undefined) 60 | 61 | if (xValue && yValue) { 62 | for (const type of removeType) { 63 | if (xValue === `-${type}-${yValue}`) { 64 | retNodeChildren.remove(nodeItem) 65 | result = tempNode 66 | break 67 | } else if (yValue === `-${type}-${xValue}`) { 68 | retNodeChildren.remove(tempNode) 69 | result = nodeItem 70 | break 71 | } else { 72 | const prefix = `-${type}-` 73 | if (xValue.startsWith(prefix)) { 74 | xValue = xValue.slice(prefix.length) 75 | } 76 | if (yValue.startsWith(prefix)) { 77 | yValue = yValue.slice(prefix.length) 78 | } 79 | } 80 | } 81 | } 82 | } 83 | temp[item.property] = result || tempNode 84 | } else { 85 | temp[item.property] = nodeItem 86 | } 87 | } 88 | }) 89 | for (const name in temp) { 90 | if (!name.startsWith('-')) { 91 | for (const type of removeType) { 92 | const fullName = `-${type}-${name}` 93 | if (temp[fullName]) { 94 | retNodeChildren.remove(temp[fullName]) 95 | delete temp[fullName] 96 | } 97 | } 98 | } 99 | } 100 | } 101 | }) 102 | return { 103 | buffer: generate(ast), 104 | path, 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/utils/unlink.ts: -------------------------------------------------------------------------------- 1 | import { PathController, ProduciblePath } from '@core/controller/PathController' 2 | 3 | export function unlinkSync(path: ProduciblePath) { 4 | return _unlink(path, true) 5 | } 6 | 7 | function _unlink(path: ProduciblePath, sync?: boolean) { 8 | const ctrl = PathController.make(path) 9 | 10 | if (!ctrl.isFile) return 11 | if (ctrl.suffixWithout.toLowerCase() === 'html') { 12 | const suffixes = ['.appservice.js', '.common.js', '.webview.js'] 13 | suffixes.forEach((suffix) => _unlink(ctrl.whitout(suffix))) 14 | } 15 | return sync ? ctrl.unlinkSync() : ctrl.unlink() 16 | } 17 | 18 | export function unlink(path: ProduciblePath, wait: true): Promise 19 | export function unlink(path: ProduciblePath, wait?: false): void 20 | export function unlink(path: ProduciblePath, wait?: boolean): void | Promise { 21 | const ret = _unlink(path) 22 | return wait ? ret : void 0 23 | } 24 | -------------------------------------------------------------------------------- /src/utils/wxmlParserJs.ts: -------------------------------------------------------------------------------- 1 | export * from '../lib/wxml-parser-js' 2 | // export * from '../lib/wxml-parser/src' 3 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": true, 3 | "compilerOptions": { 4 | "target": "ES2018", 5 | "module": "commonjs", 6 | "moduleResolution": "node", 7 | "experimentalDecorators": true, 8 | "emitDecoratorMetadata": true, 9 | "esModuleInterop": true, 10 | "inlineSourceMap": true, 11 | "noImplicitThis": true, 12 | "noUnusedLocals": true, 13 | "stripInternal": true, 14 | "pretty": true, 15 | "declaration": true, 16 | "outDir": "dist", 17 | "resolveJsonModule": true, 18 | "baseUrl": "./src", 19 | "paths": { 20 | "@/*": ["./*"], 21 | "@utils/*": ["utils/*"], 22 | "@core/*": ["core/*"], 23 | "@enum/*": ["enum/*"] 24 | } 25 | }, 26 | "exclude": ["node_modules", "/**/*.d.ts"], 27 | "ts-node": { 28 | "transpileOnly": true, 29 | "require": ["tsconfig-paths/register"] 30 | } 31 | } 32 | --------------------------------------------------------------------------------