-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsquash.ts
More file actions
336 lines (283 loc) · 11.6 KB
/
Copy pathsquash.ts
File metadata and controls
336 lines (283 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { join, resolve, dirname, basename, relative } from "std/path/mod.ts";
import { existsSync, copySync, emptyDirSync } from "std/fs/mod.ts";
import * as fflate from "fflate";
import { XMLParser } from "fast-xml-parser";
const parser = new XMLParser({ parseTagValue: false });
// Parse arguments to get debug flag and jar path
const args = Deno.args;
const DEBUG = args.includes('--debug');
const JAR_PATH = args.find(arg => arg.endsWith('.jar'));
if (!JAR_PATH) {
console.error('Usage: deno run --allow-all squash.ts [--debug] <path-to-hytale-server.jar>');
Deno.exit(1);
}
if (!existsSync(JAR_PATH)) {
console.error(`Error: File not found: ${JAR_PATH}`);
Deno.exit(1);
}
const OUTPUT_DIR = resolve(args.find(arg => !arg.startsWith('-') && !arg.endsWith('.jar')) || './out');
if (!existsSync(OUTPUT_DIR)) {
Deno.mkdirSync(OUTPUT_DIR, { recursive: true });
}
// Setup temp directories for extraction and building
const TEMP_DIR = DEBUG
? join(OUTPUT_DIR, 'debug_extract')
: Deno.makeTempDirSync({ prefix: 'hytale-squash-' });
const BUILD_DIR = DEBUG
? join(OUTPUT_DIR, 'debug_build')
: join(TEMP_DIR, 'build');
if (DEBUG) {
emptyDirSync(TEMP_DIR);
emptyDirSync(BUILD_DIR);
}
// Unzip the provided JAR file
console.log(`Extracting ${JAR_PATH} to ${TEMP_DIR}...`);
const jarData = Deno.readFileSync(JAR_PATH);
const unzipped = fflate.unzipSync(jarData) as Record<string, Uint8Array>;
for (const [filePath, fileData] of Object.entries(unzipped)) {
const fullPath = join(TEMP_DIR, filePath);
if (filePath.endsWith('/')) {
Deno.mkdirSync(fullPath, { recursive: true });
} else {
Deno.mkdirSync(dirname(fullPath), { recursive: true });
Deno.writeFileSync(fullPath, fileData);
}
}
const UNZIPPED_DIR = TEMP_DIR;
// Recursively walk through a directory
function walk(dir: string, callback: (path: string) => void) {
if (!existsSync(dir)) return;
for (const entry of Deno.readDirSync(dir)) {
const entryPath = join(dir, entry.name);
if (entry.isDirectory) {
walk(entryPath, callback);
} else {
callback(entryPath);
}
}
}
// Parse standard java properties file
function parsePomProperties(filePath: string) {
const content = Deno.readTextFileSync(filePath);
const lines = content.split('\n');
const properties: Record<string, string> = {};
lines.forEach(line => {
if (line && !line.startsWith('#')) {
const parts = line.split('=');
if (parts.length === 2) {
properties[parts[0].trim()] = parts[1].trim();
}
}
});
return properties;
}
interface Dependency {
groupId: string;
artifactId: string;
version?: string;
scope?: string;
}
interface MavenPom {
project?: {
dependencies?: {
dependency?: Dependency | Dependency[];
};
properties?: Record<string, unknown>;
};
}
// Parse maven pom.xml to get dependencies
function extractDependenciesFromXml(content: string) {
const parsed = parser.parse(content) as MavenPom;
const rawDeps = parsed.project?.dependencies?.dependency;
if (!rawDeps) return [];
const list = Array.isArray(rawDeps) ? rawDeps : [rawDeps];
return list.map((d: { groupId?: string; artifactId?: string; version?: string; scope?: string }) => ({
groupId: d.groupId || "",
artifactId: d.artifactId || "",
version: d.version,
scope: d.scope
})).filter((d: Dependency) => d.groupId && d.artifactId);
}
console.log('Scanning for all available poms...');
// Store versions of libraries that are already shaded in the jar
const shadedLibVersions = new Map<string, string>();
const internalPoms: string[] = [];
const mavenDir = join(UNZIPPED_DIR, 'META-INF/maven');
walk(mavenDir, (filePath) => {
if (filePath.endsWith('pom.properties')) {
const properties = parsePomProperties(filePath);
if (properties.groupId && properties.artifactId && properties.version) {
shadedLibVersions.set(`${properties.groupId}:${properties.artifactId}`, properties.version);
}
}
if (filePath.endsWith('pom.xml')) {
if (filePath.includes('com.hypixel')) {
internalPoms.push(filePath);
}
}
});
console.log(`Found ${shadedLibVersions.size} shaded artifacts.`);
// Read server version from the main manifest
const manifestPath = join(UNZIPPED_DIR, 'META-INF/MANIFEST.MF');
if (!existsSync(manifestPath)) {
throw new Error(`MANIFEST.MF not found at ${manifestPath}`);
}
const manifestContent = Deno.readTextFileSync(manifestPath);
const versionMatch = manifestContent.match(/Implementation-Version:\s*(.*)/);
if (!versionMatch || !versionMatch[1]) {
throw new Error('Could not detect server version from Implementation-Version in MANIFEST.MF');
}
const serverVersion = versionMatch[1].trim();
console.log(`Detected server version from MANIFEST.MF: ${serverVersion}`);
// Detect zstd version from native library file
let zstdVersion: string | undefined;
for (const path of Object.keys(unzipped)) {
const match = path.match(/linux\/amd64\/libzstd-jni-(.+)\.so/);
if (match) {
zstdVersion = match[1];
console.log(`Detected zstd version from ${path}: ${zstdVersion}`);
break;
}
}
if (!zstdVersion) {
throw new Error('Could not detect zstd version from linux/amd64/libzstd-jni-*.so');
}
const globalProperties: Record<string, string> = {
'revision': serverVersion,
'zstd.version': zstdVersion,
'bson.version': '4.2.3',
};
console.log('Extracting properties from poms...');
// Collect all properties defined in internal poms
internalPoms.forEach(pomPath => {
const content = Deno.readTextFileSync(pomPath);
const parsed = parser.parse(content) as MavenPom;
const props = parsed.project?.properties;
if (props) {
for (const [key, value] of Object.entries(props)) {
if (!globalProperties[key]) {
globalProperties[key] = String(value).trim();
}
}
}
});
// Replace property placeholders like ${revision} with actual values
function resolveValue(value: string | undefined): string {
if (typeof value !== 'string') return value || "";
return value.replace(/\${([^}]+)}/g, (match, property) => {
if (globalProperties[property]) return globalProperties[property];
if (property === 'project.groupId') return 'com.hypixel.hytale';
return match;
});
}
const externalDependenciesMap = new Map<string, Dependency>();
internalPoms.forEach(pomPath => {
const content = Deno.readTextFileSync(pomPath);
const dependencies = extractDependenciesFromXml(content);
// Filter out internal dependencies and keep only external ones
dependencies.forEach(dependency => {
const groupId = resolveValue(dependency.groupId);
const artifactId = resolveValue(dependency.artifactId);
if (!groupId.startsWith('com.hypixel') && groupId !== 'com.hypixel.hytale' && dependency.scope !== 'test' && dependency.scope !== 'system') {
const key = `${groupId}:${artifactId}`;
let version = resolveValue(dependency.version);
if ((!version || version.startsWith('${')) && shadedLibVersions.has(key)) {
version = shadedLibVersions.get(key)!;
}
if (version && !version.startsWith('${')) {
if (!externalDependenciesMap.has(key)) {
externalDependenciesMap.set(key, { ...dependency, groupId, artifactId, version });
}
}
}
});
});
console.log(`Final direct external dependency count: ${externalDependenciesMap.size}`);
const OUTPUT_JAR = join(OUTPUT_DIR, basename(JAR_PATH).replace('.jar', '-squashed.jar'));
if (existsSync(OUTPUT_JAR)) {
Deno.removeSync(OUTPUT_JAR);
}
const sourceHypixel = join(UNZIPPED_DIR, 'com/hypixel');
const targetHypixel = join(BUILD_DIR, 'com/hypixel');
// Copy main server classes
console.log(`Copying com.hypixel to build buffer...`);
if (existsSync(sourceHypixel)) {
if (DEBUG && existsSync(targetHypixel)) {
Deno.removeSync(targetHypixel, { recursive: true });
}
Deno.mkdirSync(dirname(targetHypixel), { recursive: true });
copySync(sourceHypixel, targetHypixel, { overwrite: true });
}
const hytaleResources = ['manifests.json', 'migration'];
hytaleResources.forEach(resource => {
const source = join(UNZIPPED_DIR, resource);
const destination = join(BUILD_DIR, resource);
if (existsSync(source)) {
console.log(`Copying Hytale resource: ${resource}`);
if (Deno.statSync(source).isDirectory) {
if (DEBUG && existsSync(destination)) {
Deno.removeSync(destination, { recursive: true });
}
Deno.mkdirSync(dirname(destination), { recursive: true });
copySync(source, destination, { overwrite: true });
} else {
Deno.mkdirSync(dirname(destination), { recursive: true });
Deno.copyFileSync(source, destination);
}
}
});
// Copy the manifest file
const targetManifest = join(BUILD_DIR, 'META-INF/MANIFEST.MF');
Deno.mkdirSync(dirname(targetManifest), { recursive: true });
Deno.copyFileSync(manifestPath, targetManifest);
const ARTIFACT_ID = 'Server-squashed';
const mavenMetaDir = join(BUILD_DIR, `META-INF/maven/com.hypixel.hytale/${ARTIFACT_ID}`);
Deno.mkdirSync(mavenMetaDir, { recursive: true });
// Create a new pom.xml for the squashed jar
const dependenciesList = Array.from(externalDependenciesMap.values());
const pomContent = `<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hypixel.hytale</groupId>
<artifactId>${ARTIFACT_ID}</artifactId>
<version>${serverVersion}</version>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
${dependenciesList.map((dependency: Dependency) => ` <dependency>
<groupId>${dependency.groupId}</groupId>
<artifactId>${dependency.artifactId}</artifactId>
<version>${dependency.version}</version>${dependency.scope && dependency.scope !== 'compile' ? `\n <scope>${dependency.scope}</scope>` : ''}
</dependency>`).join('\n')}
</dependencies>
</project>
`;
const pomPropertiesContent = `groupId=com.hypixel.hytale
artifactId=${ARTIFACT_ID}
version=${serverVersion}
`;
Deno.writeTextFileSync(join(mavenMetaDir, 'pom.xml'), pomContent);
Deno.writeTextFileSync(join(mavenMetaDir, 'pom.properties'), pomPropertiesContent);
Deno.writeTextFileSync(join(OUTPUT_DIR, 'pom.xml'), pomContent);
console.log(`Packaging into ${OUTPUT_JAR}...`);
// Zip everything back into a jar
const filesToZip: Record<string, Uint8Array> = {};
walk(BUILD_DIR, (filePath) => {
const relativePath = relative(BUILD_DIR, filePath);
filesToZip[relativePath] = Deno.readFileSync(filePath);
});
const zippedData = fflate.zipSync(filesToZip);
Deno.writeFileSync(OUTPUT_JAR, zippedData);
console.log(`Successfully created squashed JAR: ${OUTPUT_JAR}`);
console.log(`Found ${dependenciesList.length} external dependencies.`);
if (!DEBUG) {
console.log(`Cleaning up ${TEMP_DIR}...`);
Deno.removeSync(TEMP_DIR, { recursive: true });
} else {
console.log(`Debug folders preserved: \n - ${TEMP_DIR}\n - ${BUILD_DIR}`);
}