├── .eslintrc.json ├── .gitattributes ├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── components ├── authenticator.js ├── handler.js └── launcher.js ├── index.d.ts ├── index.js ├── package-lock.json └── package.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "commonjs": true, 5 | "es6": true 6 | }, 7 | "extends": [ 8 | "standard" 9 | ], 10 | "globals": { 11 | "Atomics": "readonly", 12 | "SharedArrayBuffer": "readonly" 13 | }, 14 | "parserOptions": { 15 | "ecmaVersion": 2018 16 | }, 17 | "rules": { 18 | "camelcase": "off", 19 | "no-template-curly-in-string": "off" 20 | } 21 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: Pierce01 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: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # configs 2 | config.json 3 | 4 | # Logs 5 | logs 6 | *.log 7 | npm-debug.log* 8 | yarn-debug.log* 9 | yarn-error.log* 10 | 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | 17 | # Directory for instrumented libs generated by jscoverage/JSCover 18 | lib-cov 19 | 20 | # Coverage directory used by tools like istanbul 21 | coverage 22 | 23 | # nyc test coverage 24 | .nyc_output 25 | 26 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 27 | .grunt 28 | 29 | # Bower dependency directory (https://bower.io/) 30 | bower_components 31 | 32 | # node-waf configuration 33 | .lock-wscript 34 | 35 | # Compiled binary addons (http://nodejs.org/api/addons.html) 36 | build/Release 37 | 38 | # Dependency directories 39 | node_modules/ 40 | jspm_packages/ 41 | 42 | # Typescript v1 declaration files 43 | typings/ 44 | 45 | # Optional npm cache directory 46 | .npm 47 | 48 | # Optional eslint cache 49 | .eslintcache 50 | 51 | # Optional REPL history 52 | .node_repl_history 53 | 54 | # Output of 'npm pack' 55 | *.tgz 56 | 57 | # Yarn Integrity file 58 | .yarn-integrity 59 | 60 | # dotenv environment variables file 61 | .env 62 | 63 | # VSCode Files (https://code.visualstudio.com) 64 | .vscode/ 65 | 66 | # IntelliJ Files 67 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Pierce Harriz 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |  2 | ##### Project rewrite coming soon™ 3 | [](https://opensource.org/licenses/MIT) 4 |  5 | 6 | MCLC (Minecraft Launcher Core) is a NodeJS solution for launching modded and vanilla Minecraft without having to download and format everything yourself. 7 | Basically a core for your Electron or script based launchers. 8 | 9 | ### Getting support 10 | I've created a Discord server for anyone who needs to get in contact with me or get help! 11 |
12 |
13 |
15 |
16 |
17 | ### Installing
18 |
19 | `npm i minecraft-launcher-core`
20 |
21 | ### Standard Example
22 | ```javascript
23 | const { Client, Authenticator } = require('minecraft-launcher-core');
24 | const launcher = new Client();
25 |
26 | let opts = {
27 | // For production launchers, I recommend not passing
28 | // the getAuth function through the authorization field and instead
29 | // handling authentication outside before you initialize
30 | // MCLC so you can handle auth based errors and validation!
31 | authorization: Authenticator.getAuth("username", "password"),
32 | root: "./minecraft",
33 | version: {
34 | number: "1.14",
35 | type: "release"
36 | },
37 | memory: {
38 | max: "6G",
39 | min: "4G"
40 | }
41 | }
42 |
43 | launcher.launch(opts);
44 |
45 | launcher.on('debug', (e) => console.log(e));
46 | launcher.on('data', (e) => console.log(e));
47 | ```
48 | ### Documentation
49 |
50 | #### Client Functions
51 |
52 | | Function | Type | Description |
53 | |----------|---------|-----------------------------------------------------------------------------------------|
54 | | `launch` | Promise | Launches the client with the specified `options` as a parameter. Returns child the process |
55 |
56 | ##### launch
57 |
58 | | Parameter | Type | Description | Required |
59 | |--------------------------|----------|-------------------------------------------------------------------------------------------|----------|
60 | | `options.clientPackage` | String | Path or URL to a zip file, which will be extracted to the root directory. (Not recommended for production use)| False |
61 | | `options.removePackage` | Boolean | Option to remove the client package zip file after its finished extracting. | False |
62 | | `options.root` | String | Path where you want the launcher to work in. `C:/Users/user/AppData/Roaming/.mc` | True |
63 | | `options.cache` | String | Path where launcher files will be cached in. `C:/Users/user/AppData/Roaming/.mc/cache` | False |
64 | | `options.os` | String | windows, osx or linux. MCLC will auto determine the OS if this field isn't provided. | False |
65 | | `options.customLaunchArgs`| Array | Array of custom Minecraft arguments you want to add. | False |
66 | | `options.customArgs` | Array | Array of custom Java arguments you want to add. | False |
67 | | `options.features` | Array | Array of game argument feature flags. ex: `is_demo_user` or `has_custom_resolution` | False |
68 | | `options.version.number` | String | Minecraft version that is going to be launched. | True |
69 | | `options.version.type` | String | Any string. The actual Minecraft launcher uses `release` and `snapshot`. | True |
70 | | `options.version.custom` | String | The name of the folder, jar file, and version json in the version folder. | False |
71 | | `options.memory.max` | String | Max amount of memory being used by Minecraft. | True |
72 | | `options.memory.min` | String | Min amount of memory being used by Minecraft. | True |
73 | | `options.forge` | String | Path to Forge Jar. (Versions below 1.12.2 should be the "universal" jar while versions above 1.13 should be the "installer" jar) | False |
74 | | `options.javaPath` | String | Path to the JRE executable file, will default to `java` if not entered. | False |
75 | | `options.quickPlay.type` | String | The type of the quickPlay session. `singleplayer`, `multiplayer`, `realms`, `legacy` | False |
76 | | `options.quickPlay.identifier` | String | The folder name, server address, or realm ID, relating to the specified type. `legacy` follows `multiplayer` format. | False |
77 | | `options.quickPlay.path` | String | The specified path for logging (relative to the run directory) | False |
78 | | `options.proxy.host` | String | Host url to the proxy, don't include the port. | False |
79 | | `options.proxy.port` | String | Port of the host proxy, will default to `8080` if not entered. | False |
80 | | `options.proxy.username` | String | Username for the proxy. | False |
81 | | `options.proxy.password` | String | Password for the proxy. | False |
82 | | `options.timeout` | Integer | Timeout on download requests. | False |
83 | | `options.window.width` | String | Width of the Minecraft Client. | False |
84 | | `options.window.height` | String | Height of the Minecraft Client. | False |
85 | | `options.window.fullscreen`| Boolean| Fullscreen the Minecraft Client. | False |
86 | | `options.overrides` | Object | Json object redefining paths for better customization. Example below. | False |
87 | #### IF YOU'RE NEW TO MCLC, LET IT HANDLE EVERYTHING! DO NOT USE OVERRIDES!
88 | ```js
89 | let opts = {
90 | otherOps...,
91 | overrides: {
92 | gameDirectory: '', // where the game process generates folders like saves and resource packs.
93 | minecraftJar: '',
94 | versionName: '', // replaces the value after the version flag.
95 | versionJson: '',
96 | directory: '', // where the Minecraft jar and version json are located.
97 | natives: '', // native directory path.
98 | assetRoot: '',
99 | assetIndex: '',
100 | libraryRoot: '',
101 | cwd: '', // working directory of the java process.
102 | detached: true, // whether or not the client is detached from the parent / launcher.
103 | classes: [], // all class paths are required if you use this.
104 | minArgs: 11, // The amount of launch arguments specified in the version file before it adds the default again
105 | maxSockets: 2, // max sockets for downloadAsync.
106 | // The following is for launcher developers located in countries that have the Minecraft and Forge resource servers
107 | // blocked for what ever reason. They obviously need to mirror the formatting of the original JSONs / file structures.
108 | url: {
109 | meta: 'https://launchermeta.mojang.com', // List of versions.
110 | resource: 'https://resources.download.minecraft.net', // Minecraft resources.
111 | mavenForge: 'http://files.minecraftforge.net/maven/', // Forge resources.
112 | defaultRepoForge: 'https://libraries.minecraft.net/', // for Forge only, you need to redefine the library url
113 | // in the version json.
114 | fallbackMaven: 'https://search.maven.org/remotecontent?filepath='
115 | },
116 | // The following is options for which version of ForgeWrapper MCLC uses. This allows us to launch modern Forge.
117 | fw: {
118 | baseUrl: 'https://github.com/ZekerZhayard/ForgeWrapper/releases/download/',
119 | version: '1.5.1',
120 | sh1: '90104e9aaa8fbedf6c3d1f6d0b90cabce080b5a9',
121 | size: 29892,
122 | },
123 | logj4ConfigurationFile: ''
124 | }
125 | }
126 | ```
127 |
128 | #### Notes
129 | ##### Custom
130 | If you are loading up a client outside of vanilla Minecraft or Forge (Optifine and for an example), you'll need to download the needed files yourself if you don't provide downloads url downloads like Forge and Fabric. If no version jar is specified, MCLC will default back to the normal MC jar so mods like Fabric work.
131 |
132 | #### Authentication (Deprecated)
133 | MCLC's authenticator module does not support Microsoft authentication. You will need to use a library like [MSMC](https://github.com/Hanro50/MSMC). If you want to create your own solution, the following is the authorization JSON object format.
134 | ```js
135 | {
136 | access_token: '',
137 | client_token: '',
138 | uuid: '',
139 | name: '',
140 | user_properties: '{}',
141 | meta: {
142 | type: 'mojang' || 'msa',
143 | demo: true || false, // Demo can also be specified by adding 'is_demo_user' to the options.feature array
144 | // properties only exists for specific Minecraft versions.
145 | xuid: '',
146 | clientId: ''
147 | }
148 | }
149 | ```
150 |
151 | #### Authenticator Functions
152 |
153 | ##### getAuth
154 |
155 | | Parameter | Type | Description | Required |
156 | |-----------|--------|--------------------------------------------------------------|----------|
157 | | `username`| String | Email or username | True |
158 | | `password`| String | Password for the Mojang account being used if online mode. | False |
159 | | `client_token`| String | Client token that will be used. If one is not specified, one will be generated | False |
160 |
161 | ##### validate
162 |
163 | | Parameter | Type | Description | Required |
164 | |--------------|--------|-------------------------------------------------------------------|----------|
165 | | `access_token` | String | Token being checked if it can be used to login with (online mode). | True |
166 | | `client_token` | String | Client token being checked to see if there was a change of client (online mode). | True |
167 |
168 | ##### refreshAuth
169 |
170 | | Parameter | Type | Description | Required |
171 | |--------------------|--------|-------------------------------------------------------------------------------------|----------|
172 | | `access_token` | String | Token being checked if it can be used to login with (online mode). | True |
173 | | `client_token` | String | Token being checked if it's the same client that the access_token was created from. | True |
174 |
175 | ##### invalidate
176 |
177 | | Parameter | Type | Description | Required |
178 | |--------------|--------|-------------------------------------------------------------------|----------|
179 | | `access_token` | String | Token being checked if it can be used to login with (online mode). | True |
180 | | `client_token` | String | Token being checked if it's the same client that the access_token was created from. | True |
181 |
182 | ##### signOut
183 |
184 | | Parameter | Type | Description | Required |
185 | |--------------|--------|--------------------------------------|----------|
186 | | `username` | String | Username used to login with | True |
187 | | `password` | String | Password used to login with | True |
188 |
189 | ##### changeApiUrl
190 |
191 | | Parameter | Type | Description | Required |
192 | |-----------|--------|--------------------------------------------------------------|----------|
193 | | `url` | String | New URL that MCLC will make calls to authenticate the login. | True |
194 |
195 | #### Events
196 |
197 | | Event Name | Type | Description |
198 | |-------------------|---------|---------------------------------------------------------------------------------------|
199 | | `arguments` | Object | Emitted when launch arguments are set for the Minecraft Jar. |
200 | | `data` | String | Emitted when information is returned from the Minecraft Process |
201 | | `close` | Integer | Code number that is returned by the Minecraft Process |
202 | | `package-extract` | null | Emitted when `clientPackage` finishes being extracted |
203 | | `download` | String | Emitted when a file successfully downloads |
204 | | `download-status` | Object | Emitted when data is received while downloading |
205 | | `debug` | String | Emitted when functions occur, made to help debug if errors occur |
206 | | `progress` | Object | Emitted when files are being downloaded in order. (Assets, Forge, Natives, Classes) |
207 |
208 |
209 | #### What should it look like running from console?
210 | The `pid` is printed in console after the process is launched.
211 | 
212 |
213 | ## Contributors
214 | These are the people that helped out that aren't listed [here](https://github.com/Pierce01/MinecraftLauncher-core/graphs/contributors)!
215 | * [Pyker](https://github.com/Pyker) - Forge dependency parsing.
216 | * [Khionu](https://github.com/khionu) - Research on how Minecraft's`natives` are handled.
217 | * [Coding-Kiwi](https://github.com/Coding-Kiwi) - Pointed out I didn't pass `clientToken` in initial authentication function.
218 | * maxbsoft - Pointed out that a certain JVM option causes OSX Minecraft to bug out.
219 | * [Noé](https://github.com/NoXeDev) - Pointed out launch args weren't being passed for Forge 1.13+.
220 |
--------------------------------------------------------------------------------
/components/authenticator.js:
--------------------------------------------------------------------------------
1 | const request = require('request')
2 | const { v3 } = require('uuid')
3 |
4 | let uuid
5 | let api_url = 'https://authserver.mojang.com'
6 |
7 | module.exports.getAuth = function (username, password, client_token = null) {
8 | return new Promise((resolve, reject) => {
9 | getUUID(username)
10 | if (!password) {
11 | const user = {
12 | access_token: uuid,
13 | client_token: client_token || uuid,
14 | uuid,
15 | name: username,
16 | user_properties: '{}'
17 | }
18 |
19 | return resolve(user)
20 | }
21 |
22 | const requestObject = {
23 | url: api_url + '/authenticate',
24 | json: {
25 | agent: {
26 | name: 'Minecraft',
27 | version: 1
28 | },
29 | username,
30 | password,
31 | clientToken: uuid,
32 | requestUser: true
33 | }
34 | }
35 |
36 | request.post(requestObject, function (error, response, body) {
37 | if (error) return reject(error)
38 | if (!body || !body.selectedProfile) {
39 | return reject(new Error('Validation error: ' + response.statusMessage))
40 | }
41 |
42 | const userProfile = {
43 | access_token: body.accessToken,
44 | client_token: body.clientToken,
45 | uuid: body.selectedProfile.id,
46 | name: body.selectedProfile.name,
47 | selected_profile: body.selectedProfile,
48 | user_properties: parsePropts(body.user.properties)
49 | }
50 |
51 | resolve(userProfile)
52 | })
53 | })
54 | }
55 |
56 | module.exports.validate = function (accessToken, clientToken) {
57 | return new Promise((resolve, reject) => {
58 | const requestObject = {
59 | url: api_url + '/validate',
60 | json: {
61 | accessToken,
62 | clientToken
63 | }
64 | }
65 |
66 | request.post(requestObject, async function (error, response, body) {
67 | if (error) return reject(error)
68 |
69 | if (!body) resolve(true)
70 | else reject(body)
71 | })
72 | })
73 | }
74 |
75 | module.exports.refreshAuth = function (accessToken, clientToken) {
76 | return new Promise((resolve, reject) => {
77 | const requestObject = {
78 | url: api_url + '/refresh',
79 | json: {
80 | accessToken,
81 | clientToken,
82 | requestUser: true
83 | }
84 | }
85 |
86 | request.post(requestObject, function (error, response, body) {
87 | if (error) return reject(error)
88 | if (!body || !body.selectedProfile) {
89 | return reject(new Error('Validation error: ' + response.statusMessage))
90 | }
91 |
92 | const userProfile = {
93 | access_token: body.accessToken,
94 | client_token: getUUID(body.selectedProfile.name),
95 | uuid: body.selectedProfile.id,
96 | name: body.selectedProfile.name,
97 | user_properties: parsePropts(body.user.properties)
98 | }
99 |
100 | return resolve(userProfile)
101 | })
102 | })
103 | }
104 |
105 | module.exports.invalidate = function (accessToken, clientToken) {
106 | return new Promise((resolve, reject) => {
107 | const requestObject = {
108 | url: api_url + '/invalidate',
109 | json: {
110 | accessToken,
111 | clientToken
112 | }
113 | }
114 |
115 | request.post(requestObject, function (error, response, body) {
116 | if (error) return reject(error)
117 |
118 | if (!body) return resolve(true)
119 | else return reject(body)
120 | })
121 | })
122 | }
123 |
124 | module.exports.signOut = function (username, password) {
125 | return new Promise((resolve, reject) => {
126 | const requestObject = {
127 | url: api_url + '/signout',
128 | json: {
129 | username,
130 | password
131 | }
132 | }
133 |
134 | request.post(requestObject, function (error, response, body) {
135 | if (error) return reject(error)
136 |
137 | if (!body) return resolve(true)
138 | else return reject(body)
139 | })
140 | })
141 | }
142 |
143 | module.exports.changeApiUrl = function (url) {
144 | api_url = url
145 | }
146 |
147 | function parsePropts (array) {
148 | if (array) {
149 | const newObj = {}
150 | for (const entry of array) {
151 | if (newObj[entry.name]) {
152 | newObj[entry.name].push(entry.value)
153 | } else {
154 | newObj[entry.name] = [entry.value]
155 | }
156 | }
157 | return JSON.stringify(newObj)
158 | } else {
159 | return '{}'
160 | }
161 | }
162 |
163 | function getUUID (value) {
164 | if (!uuid) {
165 | uuid = v3(value, v3.DNS)
166 | }
167 | return uuid
168 | }
169 |
--------------------------------------------------------------------------------
/components/handler.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | const path = require('path')
3 | const request = require('request')
4 | const checksum = require('checksum')
5 | const Zip = require('adm-zip')
6 | const child = require('child_process')
7 | let counter = 0
8 |
9 | class Handler {
10 | constructor (client) {
11 | this.client = client
12 | this.options = client.options
13 | this.baseRequest = request.defaults({
14 | pool: { maxSockets: this.options.overrides.maxSockets || 2 },
15 | timeout: this.options.timeout || 50000
16 | })
17 | }
18 |
19 | checkJava (java) {
20 | return new Promise(resolve => {
21 | child.exec(`"${java}" -version`, (error, stdout, stderr) => {
22 | if (error) {
23 | resolve({
24 | run: false,
25 | message: error
26 | })
27 | } else {
28 | this.client.emit('debug', `[MCLC]: Using Java version ${stderr.match(/"(.*?)"/).pop()} ${stderr.includes('64-Bit') ? '64-bit' : '32-Bit'}`)
29 | resolve({
30 | run: true
31 | })
32 | }
33 | })
34 | })
35 | }
36 |
37 | downloadAsync (url, directory, name, retry, type) {
38 | return new Promise(resolve => {
39 | fs.mkdirSync(directory, { recursive: true })
40 |
41 | const _request = this.baseRequest(url)
42 |
43 | let receivedBytes = 0
44 | let totalBytes = 0
45 |
46 | _request.on('response', (data) => {
47 | if (data.statusCode === 404) {
48 | this.client.emit('debug', `[MCLC]: Failed to download ${url} due to: File not found...`)
49 | return resolve(false)
50 | }
51 |
52 | totalBytes = parseInt(data.headers['content-length'])
53 | })
54 |
55 | _request.on('error', async (error) => {
56 | this.client.emit('debug', `[MCLC]: Failed to download asset to ${path.join(directory, name)} due to\n${error}.` +
57 | ` Retrying... ${retry}`)
58 | if (retry) await this.downloadAsync(url, directory, name, false, type)
59 | resolve()
60 | })
61 |
62 | _request.on('data', (data) => {
63 | receivedBytes += data.length
64 | this.client.emit('download-status', {
65 | name: name,
66 | type: type,
67 | current: receivedBytes,
68 | total: totalBytes
69 | })
70 | })
71 |
72 | const file = fs.createWriteStream(path.join(directory, name))
73 | _request.pipe(file)
74 |
75 | file.once('finish', () => {
76 | this.client.emit('download', name)
77 | resolve({
78 | failed: false,
79 | asset: null
80 | })
81 | })
82 |
83 | file.on('error', async (e) => {
84 | this.client.emit('debug', `[MCLC]: Failed to download asset to ${path.join(directory, name)} due to\n${e}.` +
85 | ` Retrying... ${retry}`)
86 | if (fs.existsSync(path.join(directory, name))) fs.unlinkSync(path.join(directory, name))
87 | if (retry) await this.downloadAsync(url, directory, name, false, type)
88 | resolve()
89 | })
90 | })
91 | }
92 |
93 | checkSum (hash, file) {
94 | return new Promise((resolve, reject) => {
95 | checksum.file(file, (err, sum) => {
96 | if (err) {
97 | this.client.emit('debug', `[MCLC]: Failed to check file hash due to ${err}`)
98 | return resolve(false)
99 | }
100 | return resolve(hash === sum)
101 | })
102 | })
103 | }
104 |
105 | getVersion () {
106 | return new Promise(resolve => {
107 | const versionJsonPath = this.options.overrides.versionJson || path.join(this.options.directory, `${this.options.version.number}.json`)
108 | if (fs.existsSync(versionJsonPath)) {
109 | this.version = JSON.parse(fs.readFileSync(versionJsonPath))
110 | return resolve(this.version)
111 | }
112 |
113 | const manifest = `${this.options.overrides.url.meta}/mc/game/version_manifest.json`
114 | const cache = this.options.cache ? `${this.options.cache}/json` : `${this.options.root}/cache/json`
115 | request.get(manifest, (error, response, body) => {
116 | if (error && error.code !== 'ENOTFOUND') return resolve(error)
117 | if (!error) {
118 | if (!fs.existsSync(cache)) {
119 | fs.mkdirSync(cache, { recursive: true })
120 | this.client.emit('debug', '[MCLC]: Cache directory created.')
121 | }
122 | fs.writeFile(path.join(`${cache}/version_manifest.json`), body, (err) => {
123 | if (err) return resolve(err)
124 | this.client.emit('debug', '[MCLC]: Cached version_manifest.json')
125 | })
126 | }
127 | const parsed = (error && error.code === 'ENOTFOUND')
128 | ? JSON.parse(fs.readFileSync(`${cache}/version_manifest.json`))
129 | : JSON.parse(body)
130 | const desiredVersion = Object.values(parsed.versions).find(version => version.id === this.options.version.number)
131 | if (desiredVersion) {
132 | request.get(desiredVersion.url, (error, response, body) => {
133 | if (error && error.code !== 'ENOTFOUND') throw Error(error)
134 | if (!error) {
135 | fs.writeFile(path.join(`${cache}/${this.options.version.number}.json`), body, (err) => {
136 | if (err) throw Error(err)
137 | this.client.emit('debug', `[MCLC]: Cached ${this.options.version.number}.json`)
138 | })
139 | }
140 |
141 | this.client.emit('debug', '[MCLC]: Parsed version from version manifest')
142 | this.version = error && error.code === 'ENOTFOUND'
143 | ? JSON.parse(fs.readFileSync(`${cache}/${this.options.version.number}.json`))
144 | : JSON.parse(body)
145 | return resolve(this.version)
146 | })
147 | } else {
148 | throw Error(`Failed to find version ${this.options.version.number} in version_manifest.json`)
149 | }
150 | })
151 | })
152 | }
153 |
154 | async getJar () {
155 | await this.downloadAsync(this.version.downloads.client.url, this.options.directory, `${this.options.version.custom ? this.options.version.custom : this.options.version.number}.jar`, true, 'version-jar')
156 | fs.writeFileSync(path.join(this.options.directory, `${this.options.version.number}.json`), JSON.stringify(this.version, null, 4))
157 | return this.client.emit('debug', '[MCLC]: Downloaded version jar and wrote version json')
158 | }
159 |
160 | async getAssets () {
161 | const assetDirectory = path.resolve(this.options.overrides.assetRoot || path.join(this.options.root, 'assets'))
162 | const assetId = this.options.version.custom || this.options.version.number
163 | if (!fs.existsSync(path.join(assetDirectory, 'indexes', `${assetId}.json`))) {
164 | await this.downloadAsync(this.version.assetIndex.url, path.join(assetDirectory, 'indexes'), `${assetId}.json`, true, 'asset-json')
165 | }
166 |
167 | const index = JSON.parse(fs.readFileSync(path.join(assetDirectory, 'indexes', `${assetId}.json`), { encoding: 'utf8' }))
168 |
169 | this.client.emit('progress', {
170 | type: 'assets',
171 | task: 0,
172 | total: Object.keys(index.objects).length
173 | })
174 |
175 | await Promise.all(Object.keys(index.objects).map(async asset => {
176 | const hash = index.objects[asset].hash
177 | const subhash = hash.substring(0, 2)
178 | const subAsset = path.join(assetDirectory, 'objects', subhash)
179 |
180 | if (!fs.existsSync(path.join(subAsset, hash)) || !await this.checkSum(hash, path.join(subAsset, hash))) {
181 | await this.downloadAsync(`${this.options.overrides.url.resource}/${subhash}/${hash}`, subAsset, hash, true, 'assets')
182 | }
183 | counter++
184 | this.client.emit('progress', {
185 | type: 'assets',
186 | task: counter,
187 | total: Object.keys(index.objects).length
188 | })
189 | }))
190 | counter = 0
191 |
192 | // Copy assets to legacy if it's an older Minecraft version.
193 | if (this.isLegacy()) {
194 | if (fs.existsSync(path.join(assetDirectory, 'legacy'))) {
195 | this.client.emit('debug', '[MCLC]: The \'legacy\' directory is no longer used as Minecraft looks ' +
196 | 'for the resouces folder regardless of what is passed in the assetDirecotry launch option. I\'d ' +
197 | `recommend removing the directory (${path.join(assetDirectory, 'legacy')})`)
198 | }
199 |
200 | const legacyDirectory = path.join(this.options.root, 'resources')
201 | this.client.emit('debug', `[MCLC]: Copying assets over to ${legacyDirectory}`)
202 |
203 | this.client.emit('progress', {
204 | type: 'assets-copy',
205 | task: 0,
206 | total: Object.keys(index.objects).length
207 | })
208 |
209 | await Promise.all(Object.keys(index.objects).map(async asset => {
210 | const hash = index.objects[asset].hash
211 | const subhash = hash.substring(0, 2)
212 | const subAsset = path.join(assetDirectory, 'objects', subhash)
213 |
214 | const legacyAsset = asset.split('/')
215 | legacyAsset.pop()
216 |
217 | if (!fs.existsSync(path.join(legacyDirectory, legacyAsset.join('/')))) {
218 | fs.mkdirSync(path.join(legacyDirectory, legacyAsset.join('/')), { recursive: true })
219 | }
220 |
221 | if (!fs.existsSync(path.join(legacyDirectory, asset))) {
222 | fs.copyFileSync(path.join(subAsset, hash), path.join(legacyDirectory, asset))
223 | }
224 | counter++
225 | this.client.emit('progress', {
226 | type: 'assets-copy',
227 | task: counter,
228 | total: Object.keys(index.objects).length
229 | })
230 | }))
231 | }
232 | counter = 0
233 |
234 | this.client.emit('debug', '[MCLC]: Downloaded assets')
235 | }
236 |
237 | parseRule (lib) {
238 | if (lib.rules) {
239 | if (lib.rules.length > 1) {
240 | if (lib.rules[0].action === 'allow' && lib.rules[1].action === 'disallow' && lib.rules[1].os.name === 'osx') {
241 | return this.getOS() === 'osx'
242 | }
243 | return true
244 | } else {
245 | if (lib.rules[0].action === 'allow' && lib.rules[0].os) return lib.rules[0].os.name !== this.getOS()
246 | }
247 | } else {
248 | return false
249 | }
250 | }
251 |
252 | async getNatives () {
253 | const nativeDirectory = path.resolve(this.options.overrides.natives || path.join(this.options.root, 'natives', this.version.id))
254 |
255 | if (parseInt(this.version.id.split('.')[1]) >= 19) return this.options.overrides.cwd || this.options.root
256 |
257 | if (!fs.existsSync(nativeDirectory) || !fs.readdirSync(nativeDirectory).length) {
258 | fs.mkdirSync(nativeDirectory, { recursive: true })
259 |
260 | const natives = async () => {
261 | const natives = []
262 | await Promise.all(this.version.libraries.map(async (lib) => {
263 | if (!lib.downloads || !lib.downloads.classifiers) return
264 | if (this.parseRule(lib)) return
265 |
266 | const native = this.getOS() === 'osx'
267 | ? lib.downloads.classifiers['natives-osx'] || lib.downloads.classifiers['natives-macos']
268 | : lib.downloads.classifiers[`natives-${this.getOS()}`]
269 |
270 | natives.push(native)
271 | }))
272 | return natives
273 | }
274 | const stat = await natives()
275 |
276 | this.client.emit('progress', {
277 | type: 'natives',
278 | task: 0,
279 | total: stat.length
280 | })
281 |
282 | await Promise.all(stat.map(async (native) => {
283 | if (!native) return
284 | const name = native.path.split('/').pop()
285 | await this.downloadAsync(native.url, nativeDirectory, name, true, 'natives')
286 | if (!await this.checkSum(native.sha1, path.join(nativeDirectory, name))) {
287 | await this.downloadAsync(native.url, nativeDirectory, name, true, 'natives')
288 | }
289 | try {
290 | new Zip(path.join(nativeDirectory, name)).extractAllTo(nativeDirectory, true)
291 | } catch (e) {
292 | // Only doing a console.warn since a stupid error happens. You can basically ignore this.
293 | // if it says Invalid file name, just means two files were downloaded and both were deleted.
294 | // All is well.
295 | console.warn(e)
296 | }
297 | fs.unlinkSync(path.join(nativeDirectory, name))
298 | counter++
299 | this.client.emit('progress', {
300 | type: 'natives',
301 | task: counter,
302 | total: stat.length
303 | })
304 | }))
305 | this.client.emit('debug', '[MCLC]: Downloaded and extracted natives')
306 | }
307 |
308 | counter = 0
309 | this.client.emit('debug', `[MCLC]: Set native path to ${nativeDirectory}`)
310 |
311 | return nativeDirectory
312 | }
313 |
314 | fwAddArgs () {
315 | const forgeWrapperAgrs = [
316 | `-Dforgewrapper.librariesDir=${path.resolve(this.options.overrides.libraryRoot || path.join(this.options.root, 'libraries'))}`,
317 | `-Dforgewrapper.installer=${this.options.forge}`,
318 | `-Dforgewrapper.minecraft=${this.options.mcPath}`
319 | ]
320 | this.options.customArgs
321 | ? this.options.customArgs = this.options.customArgs.concat(forgeWrapperAgrs)
322 | : this.options.customArgs = forgeWrapperAgrs
323 | }
324 |
325 | isModernForge (json) {
326 | return json.inheritsFrom && json.inheritsFrom.split('.')[1] >= 12 && !(json.inheritsFrom === '1.12.2' && (json.id.split('.')[json.id.split('.').length - 1]) === '2847')
327 | }
328 |
329 | async getForgedWrapped () {
330 | let json = null
331 | let installerJson = null
332 | const versionPath = path.join(this.options.root, 'forge', `${this.version.id}`, 'version.json')
333 | // Since we're building a proper "custom" JSON that will work nativly with MCLC, the version JSON will not
334 | // be re-generated on the next run.
335 | if (fs.existsSync(versionPath)) {
336 | try {
337 | json = JSON.parse(fs.readFileSync(versionPath))
338 | if (!json.forgeWrapperVersion || !(json.forgeWrapperVersion === this.options.overrides.fw.version)) {
339 | this.client.emit('debug', '[MCLC]: Old ForgeWrapper has generated this version JSON, re-generating')
340 | } else {
341 | // If forge is modern, add ForgeWrappers launch arguments and set forge to null so MCLC treats it as a custom json.
342 | if (this.isModernForge(json)) {
343 | this.fwAddArgs()
344 | this.options.forge = null
345 | }
346 | return json
347 | }
348 | } catch (e) {
349 | console.warn(e)
350 | this.client.emit('debug', '[MCLC]: Failed to parse Forge version JSON, re-generating')
351 | }
352 | }
353 |
354 | this.client.emit('debug', '[MCLC]: Generating Forge version json, this might take a bit')
355 | const zipFile = new Zip(this.options.forge)
356 | json = zipFile.readAsText('version.json')
357 | if (zipFile.getEntry('install_profile.json')) installerJson = zipFile.readAsText('install_profile.json')
358 |
359 | try {
360 | json = JSON.parse(json)
361 | if (installerJson) installerJson = JSON.parse(installerJson)
362 | } catch (e) {
363 | this.client.emit('debug', '[MCLC]: Failed to load json files for ForgeWrapper, using Vanilla instead')
364 | return null
365 | }
366 | // Adding the installer libraries as mavenFiles so MCLC downloads them but doesn't add them to the class paths.
367 | if (installerJson) {
368 | json.mavenFiles
369 | ? json.mavenFiles = json.mavenFiles.concat(installerJson.libraries)
370 | : json.mavenFiles = installerJson.libraries
371 | }
372 |
373 | // Holder for the specifc jar ending which depends on the specifc forge version.
374 | let jarEnding = 'universal'
375 | // We need to handle modern forge differently than legacy.
376 | if (this.isModernForge(json)) {
377 | // If forge is modern and above 1.12.2, we add ForgeWrapper to the libraries so MCLC includes it in the classpaths.
378 | if (json.inheritsFrom !== '1.12.2') {
379 | this.fwAddArgs()
380 | const fwName = `ForgeWrapper-${this.options.overrides.fw.version}.jar`
381 | const fwPathArr = ['io', 'github', 'zekerzhayard', 'ForgeWrapper', this.options.overrides.fw.version]
382 | json.libraries.push({
383 | name: fwPathArr.join(':'),
384 | downloads: {
385 | artifact: {
386 | path: [...fwPathArr, fwName].join('/'),
387 | url: `${this.options.overrides.fw.baseUrl}${this.options.overrides.fw.version}/${fwName}`,
388 | sha1: this.options.overrides.fw.sh1,
389 | size: this.options.overrides.fw.size
390 | }
391 | }
392 | })
393 | json.mainClass = 'io.github.zekerzhayard.forgewrapper.installer.Main'
394 | jarEnding = 'launcher'
395 |
396 | // Providing a download URL to the universal jar mavenFile so it can be downloaded properly.
397 | for (const library of json.mavenFiles) {
398 | const lib = library.name.split(':')
399 | if (lib[0] === 'net.minecraftforge' && lib[1].includes('forge')) {
400 | library.downloads.artifact.url = this.options.overrides.url.mavenForge + library.downloads.artifact.path
401 | break
402 | }
403 | }
404 | } else {
405 | // Remove the forge dependent since we're going to overwrite the first entry anyways.
406 | for (const library in json.mavenFiles) {
407 | const lib = json.mavenFiles[library].name.split(':')
408 | if (lib[0] === 'net.minecraftforge' && lib[1].includes('forge')) {
409 | delete json.mavenFiles[library]
410 | break
411 | }
412 | }
413 | }
414 | } else {
415 | // Modifying legacy library format to play nice with MCLC's downloadToDirectory function.
416 | await Promise.all(json.libraries.map(async library => {
417 | const lib = library.name.split(':')
418 | if (lib[0] === 'net.minecraftforge' && lib[1].includes('forge')) return
419 |
420 | let url = this.options.overrides.url.mavenForge
421 | const name = `${lib[1]}-${lib[2]}.jar`
422 |
423 | if (!library.url) {
424 | if (library.serverreq || library.clientreq) {
425 | url = this.options.overrides.url.defaultRepoForge
426 | } else {
427 | return
428 | }
429 | }
430 | library.url = url
431 | const downloadLink = `${url}${lib[0].replace(/\./g, '/')}/${lib[1]}/${lib[2]}/${name}`
432 | // Checking if the file still exists on Forge's server, if not, replace it with the fallback.
433 | // Not checking for sucess, only if it 404s.
434 | this.baseRequest(downloadLink, (error, response, body) => {
435 | if (error) {
436 | this.client.emit('debug', `[MCLC]: Failed checking request for ${downloadLink}`)
437 | } else {
438 | if (response.statusCode === 404) library.url = this.options.overrides.url.fallbackMaven
439 | }
440 | })
441 | }))
442 | }
443 | // If a downloads property exists, we modify the inital forge entry to include ${jarEnding} so ForgeWrapper can work properly.
444 | // If it doesn't, we simply remove it since we're already providing the universal jar.
445 | if (json.libraries[0].downloads) {
446 | const name = json.libraries[0].name
447 | if (name.includes('minecraftforge:forge') && !name.includes('universal')) {
448 | json.libraries[0].name = name + `:${jarEnding}`
449 | json.libraries[0].downloads.artifact.path = json.libraries[0].downloads.artifact.path.replace('.jar', `-${jarEnding}.jar`)
450 | json.libraries[0].downloads.artifact.url = this.options.overrides.url.mavenForge + json.libraries[0].downloads.artifact.path
451 | }
452 | } else {
453 | delete json.libraries[0]
454 | }
455 |
456 | // Removing duplicates and null types
457 | json.libraries = this.cleanUp(json.libraries)
458 | if (json.mavenFiles) json.mavenFiles = this.cleanUp(json.mavenFiles)
459 |
460 | json.forgeWrapperVersion = this.options.overrides.fw.version
461 |
462 | // Saving file for next run!
463 | if (!fs.existsSync(path.join(this.options.root, 'forge', this.version.id))) {
464 | fs.mkdirSync(path.join(this.options.root, 'forge', this.version.id), { recursive: true })
465 | }
466 | fs.writeFileSync(versionPath, JSON.stringify(json, null, 4))
467 |
468 | // Make MCLC treat modern forge as a custom version json rather then legacy forge.
469 | if (this.isModernForge(json)) this.options.forge = null
470 |
471 | return json
472 | }
473 |
474 | async downloadToDirectory (directory, libraries, eventName) {
475 | const libs = []
476 |
477 | await Promise.all(libraries.map(async library => {
478 | if (!library) return
479 | if (this.parseRule(library)) return
480 | const lib = library.name.split(':')
481 |
482 | let jarPath
483 | let name
484 | if (library.downloads && library.downloads.artifact && library.downloads.artifact.path) {
485 | name = library.downloads.artifact.path.split('/')[library.downloads.artifact.path.split('/').length - 1]
486 | jarPath = path.join(directory, this.popString(library.downloads.artifact.path))
487 | } else {
488 | name = `${lib[1]}-${lib[2]}${lib[3] ? '-' + lib[3] : ''}.jar`
489 | jarPath = path.join(directory, `${lib[0].replace(/\./g, '/')}/${lib[1]}/${lib[2]}`)
490 | }
491 |
492 | const downloadLibrary = async library => {
493 | if (library.url) {
494 | const url = `${library.url}${lib[0].replace(/\./g, '/')}/${lib[1]}/${lib[2]}/${name}`
495 | await this.downloadAsync(url, jarPath, name, true, eventName)
496 | } else if (library.downloads && library.downloads.artifact && library.downloads.artifact.url) {
497 | // Only download if there's a URL provided. If not, we're assuming it's going a generated dependency.
498 | await this.downloadAsync(library.downloads.artifact.url, jarPath, name, true, eventName)
499 | }
500 | }
501 |
502 | if (!fs.existsSync(path.join(jarPath, name))) await downloadLibrary(library)
503 | if (library.downloads && library.downloads.artifact) {
504 | if (!this.checkSum(library.downloads.artifact.sha1, path.join(jarPath, name))) await downloadLibrary(library)
505 | }
506 |
507 | counter++
508 | this.client.emit('progress', {
509 | type: eventName,
510 | task: counter,
511 | total: libraries.length
512 | })
513 | libs.push(`${jarPath}${path.sep}${name}`)
514 | }))
515 | counter = 0
516 |
517 | return libs
518 | }
519 |
520 | async getClasses (classJson) {
521 | let libs = []
522 |
523 | const libraryDirectory = path.resolve(this.options.overrides.libraryRoot || path.join(this.options.root, 'libraries'))
524 |
525 | if (classJson) {
526 | if (classJson.mavenFiles) {
527 | await this.downloadToDirectory(libraryDirectory, classJson.mavenFiles, 'classes-maven-custom')
528 | }
529 | libs = await this.downloadToDirectory(libraryDirectory, classJson.libraries, 'classes-custom')
530 | }
531 |
532 | const parsed = this.version.libraries.filter(lib => {
533 | if (lib.downloads && lib.downloads.artifact && !this.parseRule(lib)) {
534 | if (!classJson || !classJson.libraries.some(l => l.name.split(':')[1] === lib.name.split(':')[1])) {
535 | return true
536 | }
537 | }
538 | return false
539 | })
540 |
541 | libs = libs.concat((await this.downloadToDirectory(libraryDirectory, parsed, 'classes')))
542 | counter = 0
543 |
544 | this.client.emit('debug', '[MCLC]: Collected class paths')
545 | return libs
546 | }
547 |
548 | popString (path) {
549 | return path.split('/').slice(0, -1).join('/')
550 | }
551 |
552 | cleanUp (array) {
553 | return [...new Set(Object.values(array).filter(value => value !== null))]
554 | }
555 |
556 | formatQuickPlay () {
557 | const types = {
558 | singleplayer: '--quickPlaySingleplayer',
559 | multiplayer: '--quickPlayMultiplayer',
560 | realms: '--quickPlayRealms',
561 | legacy: null
562 | }
563 | const { type, identifier, path } = this.options.quickPlay
564 | const keys = Object.keys(types)
565 | if (!keys.includes(type)) {
566 | this.client.emit('debug', `[MCLC]: quickPlay type is not valid. Valid types are: ${keys.join(', ')}`)
567 | return null
568 | }
569 | const returnArgs = type === 'legacy'
570 | ? ['--server', identifier.split(':')[0], '--port', identifier.split(':')[1] || '25565']
571 | : [types[type], identifier]
572 | if (path) returnArgs.push('--quickPlayPath', path)
573 | return returnArgs
574 | }
575 |
576 | async getLaunchOptions (modification) {
577 | const type = Object.assign({}, this.version, modification)
578 |
579 | let args = type.minecraftArguments
580 | ? type.minecraftArguments.split(' ')
581 | : type.arguments.game
582 | const assetRoot = path.resolve(this.options.overrides.assetRoot || path.join(this.options.root, 'assets'))
583 | const assetPath = this.isLegacy()
584 | ? path.join(this.options.root, 'resources')
585 | : path.join(assetRoot)
586 |
587 | const minArgs = this.options.overrides.minArgs || this.isLegacy() ? 5 : 11
588 | if (args.length < minArgs) args = args.concat(this.version.minecraftArguments ? this.version.minecraftArguments.split(' ') : this.version.arguments.game)
589 | if (this.options.customLaunchArgs) args = args.concat(this.options.customLaunchArgs)
590 |
591 | this.options.authorization = await Promise.resolve(this.options.authorization)
592 | this.options.authorization.meta = this.options.authorization.meta ? this.options.authorization.meta : { type: 'mojang' }
593 | const fields = {
594 | '${auth_access_token}': this.options.authorization.access_token,
595 | '${auth_session}': this.options.authorization.access_token,
596 | '${auth_player_name}': this.options.authorization.name,
597 | '${auth_uuid}': this.options.authorization.uuid,
598 | '${auth_xuid}': this.options.authorization.meta.xuid || this.options.authorization.access_token,
599 | '${user_properties}': this.options.authorization.user_properties,
600 | '${user_type}': this.options.authorization.meta.type,
601 | '${version_name}': this.options.version.number || this.options.overrides.versionName,
602 | '${assets_index_name}': this.options.overrides.assetIndex || this.options.version.custom || this.options.version.number,
603 | '${game_directory}': this.options.overrides.gameDirectory || this.options.root,
604 | '${assets_root}': assetPath,
605 | '${game_assets}': assetPath,
606 | '${version_type}': this.options.version.type,
607 | '${clientid}': this.options.authorization.meta.clientId || (this.options.authorization.client_token || this.options.authorization.access_token),
608 | '${resolution_width}': this.options.window ? this.options.window.width : 856,
609 | '${resolution_height}': this.options.window ? this.options.window.height : 482
610 | }
611 |
612 | if (this.options.authorization.meta.demo && (this.options.features ? !this.options.features.includes('is_demo_user') : true)) {
613 | args.push('--demo')
614 | }
615 |
616 | const replaceArg = (obj, index) => {
617 | if (Array.isArray(obj.value)) {
618 | for (const arg of obj.value) {
619 | args.push(arg)
620 | }
621 | } else {
622 | args.push(obj.value)
623 | }
624 | delete args[index]
625 | }
626 |
627 | for (let index = 0; index < args.length; index++) {
628 | if (typeof args[index] === 'object') {
629 | if (args[index].rules) {
630 | if (!this.options.features) continue
631 | const featureFlags = []
632 | for (const rule of args[index].rules) {
633 | featureFlags.push(...Object.keys(rule.features))
634 | }
635 | let hasAllRules = true
636 | for (const feature of this.options.features) {
637 | if (!featureFlags.includes(feature)) {
638 | hasAllRules = false
639 | }
640 | }
641 | if (hasAllRules) replaceArg(args[index], index)
642 | } else {
643 | replaceArg(args[index], index)
644 | }
645 | } else {
646 | if (Object.keys(fields).includes(args[index])) {
647 | args[index] = fields[args[index]]
648 | }
649 | }
650 | }
651 | if (this.options.window) {
652 | if (this.options.window.fullscreen) {
653 | args.push('--fullscreen')
654 | } else {
655 | if (this.options.window.width) args.push('--width', this.options.window.width)
656 | if (this.options.window.height) args.push('--height', this.options.window.height)
657 | }
658 | }
659 | if (this.options.server) this.client.emit('debug', '[MCLC]: server and port are deprecated launch flags. Use the quickPlay field.')
660 | if (this.options.quickPlay) args = args.concat(this.formatQuickPlay())
661 | if (this.options.proxy) {
662 | args.push(
663 | '--proxyHost',
664 | this.options.proxy.host,
665 | '--proxyPort',
666 | this.options.proxy.port || '8080',
667 | '--proxyUser',
668 | this.options.proxy.username,
669 | '--proxyPass',
670 | this.options.proxy.password
671 | )
672 | }
673 | args = args.filter(value => typeof value === 'string' || typeof value === 'number')
674 | this.client.emit('debug', '[MCLC]: Set launch options')
675 | return args
676 | }
677 |
678 | async getJVM () {
679 | const opts = {
680 | windows: '-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump',
681 | osx: '-XstartOnFirstThread',
682 | linux: '-Xss1M'
683 | }
684 | return opts[this.getOS()]
685 | }
686 |
687 | isLegacy () {
688 | return this.version.assets === 'legacy' || this.version.assets === 'pre-1.6'
689 | }
690 |
691 | getOS () {
692 | if (this.options.os) {
693 | return this.options.os
694 | } else {
695 | switch (process.platform) {
696 | case 'win32': return 'windows'
697 | case 'darwin': return 'osx'
698 | default: return 'linux'
699 | }
700 | }
701 | }
702 |
703 | // To prevent launchers from breaking when they update. Will be reworked with rewrite.
704 | getMemory () {
705 | if (!this.options.memory) {
706 | this.client.emit('debug', '[MCLC]: Memory not set! Setting 1GB as MAX!')
707 | this.options.memory = {
708 | min: 512,
709 | max: 1023
710 | }
711 | }
712 | if (!isNaN(this.options.memory.max) && !isNaN(this.options.memory.min)) {
713 | if (this.options.memory.max < this.options.memory.min) {
714 | this.client.emit('debug', '[MCLC]: MIN memory is higher then MAX! Resetting!')
715 | this.options.memory.max = 1023
716 | this.options.memory.min = 512
717 | }
718 | return [`${this.options.memory.max}M`, `${this.options.memory.min}M`]
719 | } else { return [`${this.options.memory.max}`, `${this.options.memory.min}`] }
720 | }
721 |
722 | async extractPackage (options = this.options) {
723 | if (options.clientPackage.startsWith('http')) {
724 | await this.downloadAsync(options.clientPackage, options.root, 'clientPackage.zip', true, 'client-package')
725 | options.clientPackage = path.join(options.root, 'clientPackage.zip')
726 | }
727 | new Zip(options.clientPackage).extractAllTo(options.root, true)
728 | if (options.removePackage) fs.unlinkSync(options.clientPackage)
729 |
730 | return this.client.emit('package-extract', true)
731 | }
732 | }
733 |
734 | module.exports = Handler
735 |
--------------------------------------------------------------------------------
/components/launcher.js:
--------------------------------------------------------------------------------
1 | const child = require('child_process')
2 | const path = require('path')
3 | const Handler = require('./handler')
4 | const fs = require('fs')
5 | const EventEmitter = require('events').EventEmitter
6 |
7 | class MCLCore extends EventEmitter {
8 | async launch (options) {
9 | try {
10 | this.options = { ...options }
11 | this.options.root = path.resolve(this.options.root)
12 | this.options.overrides = {
13 | detached: true,
14 | ...this.options.overrides,
15 | url: {
16 | meta: 'https://launchermeta.mojang.com',
17 | resource: 'https://resources.download.minecraft.net',
18 | mavenForge: 'https://files.minecraftforge.net/maven/',
19 | defaultRepoForge: 'https://libraries.minecraft.net/',
20 | fallbackMaven: 'https://search.maven.org/remotecontent?filepath=',
21 | ...this.options.overrides
22 | ? this.options.overrides.url
23 | : undefined
24 | },
25 | fw: {
26 | baseUrl: 'https://github.com/ZekerZhayard/ForgeWrapper/releases/download/',
27 | version: '1.6.0',
28 | sh1: '035a51fe6439792a61507630d89382f621da0f1f',
29 | size: 28679,
30 | ...this.options.overrides
31 | ? this.options.overrides.fw
32 | : undefined
33 | }
34 | }
35 |
36 | this.handler = new Handler(this)
37 |
38 | this.printVersion()
39 |
40 | const java = await this.handler.checkJava(this.options.javaPath || 'java')
41 | if (!java.run) {
42 | this.emit('debug', `[MCLC]: Couldn't start Minecraft due to: ${java.message}`)
43 | this.emit('close', 1)
44 | return null
45 | }
46 |
47 | this.createRootDirectory()
48 | this.createGameDirectory()
49 |
50 | await this.extractPackage()
51 |
52 | const directory = this.options.overrides.directory || path.join(this.options.root, 'versions', this.options.version.custom ? this.options.version.custom : this.options.version.number)
53 | this.options.directory = directory
54 |
55 | const versionFile = await this.handler.getVersion()
56 | const mcPath = this.options.overrides.minecraftJar || (this.options.version.custom
57 | ? path.join(this.options.root, 'versions', this.options.version.custom, `${this.options.version.custom}.jar`)
58 | : path.join(directory, `${this.options.version.number}.jar`))
59 | this.options.mcPath = mcPath
60 | const nativePath = await this.handler.getNatives()
61 |
62 | if (!fs.existsSync(mcPath)) {
63 | this.emit('debug', '[MCLC]: Attempting to download Minecraft version jar')
64 | await this.handler.getJar()
65 | }
66 |
67 | const modifyJson = await this.getModifyJson()
68 |
69 | const args = []
70 |
71 | let jvm = [
72 | '-XX:-UseAdaptiveSizePolicy',
73 | '-XX:-OmitStackTraceInFastThrow',
74 | '-Dfml.ignorePatchDiscrepancies=true',
75 | '-Dfml.ignoreInvalidMinecraftCertificates=true',
76 | `-Djava.library.path=${nativePath}`,
77 | `-Xmx${this.handler.getMemory()[0]}`,
78 | `-Xms${this.handler.getMemory()[1]}`
79 | ]
80 | if (this.handler.getOS() === 'osx') {
81 | if (parseInt(versionFile.id.split('.')[1]) > 12) jvm.push(await this.handler.getJVM())
82 | } else jvm.push(await this.handler.getJVM())
83 |
84 | if (this.options.customArgs) jvm = jvm.concat(this.options.customArgs)
85 | if (this.options.overrides.logj4ConfigurationFile) {
86 | jvm.push(`-Dlog4j.configurationFile=${path.resolve(this.options.overrides.logj4ConfigurationFile)}`)
87 | }
88 | // https://help.minecraft.net/hc/en-us/articles/4416199399693-Security-Vulnerability-in-Minecraft-Java-Edition
89 | if (parseInt(versionFile.id.split('.')[1]) === 18 && !parseInt(versionFile.id.split('.')[2])) jvm.push('-Dlog4j2.formatMsgNoLookups=true')
90 | if (parseInt(versionFile.id.split('.')[1]) === 17) jvm.push('-Dlog4j2.formatMsgNoLookups=true')
91 | if (parseInt(versionFile.id.split('.')[1]) < 17) {
92 | if (!jvm.find(arg => arg.includes('Dlog4j.configurationFile'))) {
93 | const configPath = path.resolve(this.options.overrides.cwd || this.options.root)
94 | const intVersion = parseInt(versionFile.id.split('.')[1])
95 | if (intVersion >= 12) {
96 | await this.handler.downloadAsync('https://launcher.mojang.com/v1/objects/02937d122c86ce73319ef9975b58896fc1b491d1/log4j2_112-116.xml',
97 | configPath, 'log4j2_112-116.xml', true, 'log4j')
98 | jvm.push('-Dlog4j.configurationFile=log4j2_112-116.xml')
99 | } else if (intVersion >= 7) {
100 | await this.handler.downloadAsync('https://launcher.mojang.com/v1/objects/dd2b723346a8dcd48e7f4d245f6bf09e98db9696/log4j2_17-111.xml',
101 | configPath, 'log4j2_17-111.xml', true, 'log4j')
102 | jvm.push('-Dlog4j.configurationFile=log4j2_17-111.xml')
103 | }
104 | }
105 | }
106 |
107 | const classes = this.options.overrides.classes || this.handler.cleanUp(await this.handler.getClasses(modifyJson))
108 | const classPaths = ['-cp']
109 | const separator = this.handler.getOS() === 'windows' ? ';' : ':'
110 | this.emit('debug', `[MCLC]: Using ${separator} to separate class paths`)
111 | // Handling launch arguments.
112 | const file = modifyJson || versionFile
113 | // So mods like fabric work.
114 | const jar = fs.existsSync(mcPath)
115 | ? `${separator}${mcPath}`
116 | : `${separator}${path.join(directory, `${this.options.version.number}.jar`)}`
117 | classPaths.push(`${this.options.forge ? this.options.forge + separator : ''}${classes.join(separator)}${jar}`)
118 | classPaths.push(file.mainClass)
119 |
120 | this.emit('debug', '[MCLC]: Attempting to download assets')
121 | await this.handler.getAssets()
122 |
123 | // Forge -> Custom -> Vanilla
124 | const launchOptions = await this.handler.getLaunchOptions(modifyJson)
125 |
126 | const launchArguments = args.concat(jvm, classPaths, launchOptions)
127 | this.emit('arguments', launchArguments)
128 | this.emit('debug', `[MCLC]: Launching with arguments ${launchArguments.join(' ')}`)
129 |
130 | return this.startMinecraft(launchArguments)
131 | } catch (e) {
132 | this.emit('debug', `[MCLC]: Failed to start due to ${e}, closing...`)
133 | return null
134 | }
135 | }
136 |
137 | printVersion () {
138 | if (fs.existsSync(path.join(__dirname, '..', 'package.json'))) {
139 | const { version } = require('../package.json')
140 | this.emit('debug', `[MCLC]: MCLC version ${version}`)
141 | } else { this.emit('debug', '[MCLC]: Package JSON not found, skipping MCLC version check.') }
142 | }
143 |
144 | createRootDirectory () {
145 | if (!fs.existsSync(this.options.root)) {
146 | this.emit('debug', '[MCLC]: Attempting to create root folder')
147 | fs.mkdirSync(this.options.root)
148 | }
149 | }
150 |
151 | createGameDirectory () {
152 | if (this.options.overrides.gameDirectory) {
153 | this.options.overrides.gameDirectory = path.resolve(this.options.overrides.gameDirectory)
154 | if (!fs.existsSync(this.options.overrides.gameDirectory)) {
155 | fs.mkdirSync(this.options.overrides.gameDirectory, { recursive: true })
156 | }
157 | }
158 | }
159 |
160 | async extractPackage () {
161 | if (this.options.clientPackage) {
162 | this.emit('debug', `[MCLC]: Extracting client package to ${this.options.root}`)
163 | await this.handler.extractPackage()
164 | }
165 | }
166 |
167 | async getModifyJson () {
168 | let modifyJson = null
169 |
170 | if (this.options.forge) {
171 | this.options.forge = path.resolve(this.options.forge)
172 | this.emit('debug', '[MCLC]: Detected Forge in options, getting dependencies')
173 | modifyJson = await this.handler.getForgedWrapped()
174 | } else if (this.options.version.custom) {
175 | this.emit('debug', '[MCLC]: Detected custom in options, setting custom version file')
176 | modifyJson = modifyJson || JSON.parse(fs.readFileSync(path.join(this.options.root, 'versions', this.options.version.custom, `${this.options.version.custom}.json`), { encoding: 'utf8' }))
177 | }
178 |
179 | return modifyJson
180 | }
181 |
182 | startMinecraft (launchArguments) {
183 | const minecraft = child.spawn(this.options.javaPath ? this.options.javaPath : 'java', launchArguments,
184 | { cwd: this.options.overrides.cwd || this.options.root, detached: this.options.overrides.detached })
185 | minecraft.stdout.on('data', (data) => this.emit('data', data.toString('utf-8')))
186 | minecraft.stderr.on('data', (data) => this.emit('data', data.toString('utf-8')))
187 | minecraft.on('close', (code) => this.emit('close', code))
188 | return minecraft
189 | }
190 | }
191 |
192 | module.exports = MCLCore
193 |
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 | ///