-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
98 lines (93 loc) · 2.86 KB
/
index.ts
File metadata and controls
98 lines (93 loc) · 2.86 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
import type { Plugin } from "vite";
import axios from "axios";
import fs from "fs";
import path from "path";
import FormData from "form-data";
import chalk from "chalk";
import { DAO3_API_BASE, type IUploadBundleOptions } from "./config";
import { loadGlobalConfig } from "./env";
export type { IDao3Config } from "./config";
/**
* 将构建产物脚本上传到神岛 Arena 编辑器
*/
export function ArenaUpdateScript(options: IUploadBundleOptions): Plugin {
const { outDir, target, env } = options;
const mapId = Number(env.VITE_DAO3_MAP_ID);
let ua: string;
let auth: string;
if (env.VITE_DAO3_UA && env.VITE_DAO3_AUTH) {
ua = env.VITE_DAO3_UA;
auth = env.VITE_DAO3_AUTH;
} else {
const config = loadGlobalConfig();
ua = config.userAgent ?? "";
auth = config.authToken ?? "";
}
return {
name: "arenapro-update-script",
apply: "build",
async closeBundle() {
if (!fs.existsSync(outDir)) {
return;
}
const files = fs
.readdirSync(outDir)
.filter((f) => /\.(?:js|cjs|mjs)$/.test(f));
for (const file of files) {
const filePath = path.join(outDir, file);
const content = fs.readFileSync(filePath);
let uploadFileName = file.replace(/\.(?:js|cjs|mjs)$/, ".js");
if (env.VITE_VERSION) {
uploadFileName = uploadFileName.replace(
/\.js$/,
"." + env.VITE_VERSION + ".js"
);
}
if (env.VITE_CI) {
uploadFileName = uploadFileName.replace(/\.js$/, ".ci.js");
}
const scriptType = target === "server" ? "0" : "1";
const formData = new FormData();
if (mapId) {
formData.append("mapId", mapId.toString());
}
formData.append("name", uploadFileName);
formData.append("type", scriptType);
formData.append("file", content, {
filename: uploadFileName,
contentType: "application/javascript",
});
const res = await axios.post(
`${DAO3_API_BASE}/open/script/save-or-update`,
formData,
{
headers: {
...formData.getHeaders(),
Authorization: auth,
"X-Dao-Ua": ua,
"user-agent": ua,
},
params: {
file: uploadFileName,
target,
},
}
);
const data = res.data ?? {};
if (!res || res.status !== 200 || data.code !== 200) {
console.log(
chalk.red(
`[${target}] 同步Arena脚本「${uploadFileName}」错误:${data.code},原因:${data.msg}`
)
);
} else {
console.log(
chalk.green(
`[${target}] 同步Arena脚本「${uploadFileName}」成功:${data.code},信息:${data.msg}`
)
);
}
}
},
};
}