@dtinsight/dt-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of @dtinsight/dt-cli might be problematic. Click here for more details.
- package/README.md +207 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4425 -0
- package/package.json +45 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,4425 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { readFileSync } from "fs";
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
|
|
7
|
+
// src/commands/bug.ts
|
|
8
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
9
|
+
import { z as z2 } from "zod";
|
|
10
|
+
|
|
11
|
+
// src/adapters/zentao/client.ts
|
|
12
|
+
import { randomUUID } from "crypto";
|
|
13
|
+
|
|
14
|
+
// src/core/errors.ts
|
|
15
|
+
var CliError = class extends Error {
|
|
16
|
+
constructor(code, message, options = {}) {
|
|
17
|
+
super(message, { cause: options.cause });
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.options = options;
|
|
20
|
+
this.name = "CliError";
|
|
21
|
+
}
|
|
22
|
+
code;
|
|
23
|
+
options;
|
|
24
|
+
};
|
|
25
|
+
function toCliErrorFor(error, serviceName) {
|
|
26
|
+
if (error instanceof CliError) return error;
|
|
27
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
28
|
+
return new CliError("timeout", `\u8BF7\u6C42${serviceName}\u670D\u52A1\u8D85\u65F6`, { retryable: true, cause: error });
|
|
29
|
+
}
|
|
30
|
+
if (error instanceof TypeError) {
|
|
31
|
+
return new CliError("network_error", `\u65E0\u6CD5\u8FDE\u63A5${serviceName}\u670D\u52A1\uFF1A${error.message}`, {
|
|
32
|
+
retryable: true,
|
|
33
|
+
cause: error
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return new CliError(
|
|
37
|
+
"internal_error",
|
|
38
|
+
error instanceof Error ? error.message : "\u53D1\u751F\u672A\u77E5\u9519\u8BEF",
|
|
39
|
+
{ cause: error }
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
function toCliError(error) {
|
|
43
|
+
return toCliErrorFor(error, "\u7985\u9053");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/adapters/zentao/types.ts
|
|
47
|
+
import { z } from "zod";
|
|
48
|
+
var BugSchema = z.object({
|
|
49
|
+
bugId: z.union([z.number(), z.string()]).optional(),
|
|
50
|
+
bugTitle: z.string().optional(),
|
|
51
|
+
bugDesc: z.string().optional(),
|
|
52
|
+
bugDealSteps: z.string().optional(),
|
|
53
|
+
bugStatus: z.string().optional(),
|
|
54
|
+
bugType: z.string().optional(),
|
|
55
|
+
bugUrl: z.string().optional(),
|
|
56
|
+
bugEnv: z.string().nullable().optional(),
|
|
57
|
+
bugCustomer: z.string().nullable().optional(),
|
|
58
|
+
bugFounded: z.string().nullable().optional(),
|
|
59
|
+
bugModule: z.string().nullable().optional(),
|
|
60
|
+
bugPriority: z.union([z.number(), z.string()]).optional(),
|
|
61
|
+
productName: z.string().optional(),
|
|
62
|
+
assignedTo: z.string().optional(),
|
|
63
|
+
openedBy: z.string().optional()
|
|
64
|
+
}).passthrough();
|
|
65
|
+
|
|
66
|
+
// src/adapters/zentao/client.ts
|
|
67
|
+
function unwrapPayload(payload) {
|
|
68
|
+
if (payload && typeof payload === "object" && "data" in payload) {
|
|
69
|
+
return payload.data;
|
|
70
|
+
}
|
|
71
|
+
return payload;
|
|
72
|
+
}
|
|
73
|
+
function extractItems(payload) {
|
|
74
|
+
const value = unwrapPayload(payload);
|
|
75
|
+
if (Array.isArray(value)) return value;
|
|
76
|
+
if (value && typeof value === "object") {
|
|
77
|
+
for (const key of ["items", "list", "bugs", "records", "rows"]) {
|
|
78
|
+
const candidate = value[key];
|
|
79
|
+
if (Array.isArray(candidate)) return candidate;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
throw new CliError("invalid_response", "\u7985\u9053\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u6570\u636E\u7ED3\u6784", {
|
|
83
|
+
details: payload
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
var ZentaoClient = class {
|
|
87
|
+
constructor(options) {
|
|
88
|
+
this.options = options;
|
|
89
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
90
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
91
|
+
this.timeoutMs = options.timeoutMs ?? 15e3;
|
|
92
|
+
}
|
|
93
|
+
options;
|
|
94
|
+
fetchImpl;
|
|
95
|
+
timeoutMs;
|
|
96
|
+
baseUrl;
|
|
97
|
+
async getBugDetails(bugIds) {
|
|
98
|
+
if (!Array.isArray(bugIds) || bugIds.length === 0 || bugIds.some((bugId) => !Number.isSafeInteger(bugId) || bugId <= 0)) {
|
|
99
|
+
throw new CliError("invalid_argument", "bugIds \u5FC5\u987B\u662F\u975E\u7A7A\u7684\u6B63\u6574\u6570\u6570\u7EC4");
|
|
100
|
+
}
|
|
101
|
+
return this.postBugs("/bugs/details", { bugIds });
|
|
102
|
+
}
|
|
103
|
+
async searchBugs(query, limit) {
|
|
104
|
+
return this.postBugs("/bugs/search", { q: query, limit });
|
|
105
|
+
}
|
|
106
|
+
async preciseBugs(query) {
|
|
107
|
+
const body = Object.fromEntries(
|
|
108
|
+
Object.entries(query).filter(([, value]) => value !== void 0 && value !== "")
|
|
109
|
+
);
|
|
110
|
+
return this.postBugs("/bugs/precise", body);
|
|
111
|
+
}
|
|
112
|
+
async postBugs(path, body) {
|
|
113
|
+
const requestId = randomUUID();
|
|
114
|
+
const headers = {
|
|
115
|
+
"content-type": "application/json",
|
|
116
|
+
accept: "application/json",
|
|
117
|
+
"x-request-id": requestId
|
|
118
|
+
};
|
|
119
|
+
try {
|
|
120
|
+
const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
121
|
+
method: "POST",
|
|
122
|
+
headers,
|
|
123
|
+
body: JSON.stringify(body),
|
|
124
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
125
|
+
});
|
|
126
|
+
const text = await response.text();
|
|
127
|
+
let payload;
|
|
128
|
+
try {
|
|
129
|
+
payload = text ? JSON.parse(text) : null;
|
|
130
|
+
} catch {
|
|
131
|
+
throw new CliError("invalid_response", "\u7985\u9053\u670D\u52A1\u8FD4\u56DE\u4E86\u975E JSON \u5185\u5BB9", {
|
|
132
|
+
details: text.slice(0, 500)
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
if (!response.ok) {
|
|
136
|
+
throw new CliError("upstream_error", `\u7985\u9053\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${response.status}\uFF09`, {
|
|
137
|
+
retryable: response.status === 429 || response.status >= 500,
|
|
138
|
+
details: { status: response.status, requestId, response: payload }
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const parsed = BugSchema.array().safeParse(extractItems(payload));
|
|
142
|
+
if (!parsed.success) {
|
|
143
|
+
throw new CliError("invalid_response", "Bug \u6570\u636E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26\u5408\u9884\u671F", {
|
|
144
|
+
details: parsed.error.issues
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return parsed.data;
|
|
148
|
+
} catch (error) {
|
|
149
|
+
throw toCliError(error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// src/adapters/zentao/bug-reference.ts
|
|
155
|
+
var BUG_URL_PATTERN = /bug-view-(\d+)\.html(?:$|[?#])/i;
|
|
156
|
+
function parseBugId(reference) {
|
|
157
|
+
const value = reference.trim();
|
|
158
|
+
const matched = value.match(BUG_URL_PATTERN);
|
|
159
|
+
const idText = matched?.[1] ?? (/^\d+$/.test(value) ? value : void 0);
|
|
160
|
+
const id = idText ? Number(idText) : Number.NaN;
|
|
161
|
+
if (!Number.isSafeInteger(id) || id <= 0) {
|
|
162
|
+
throw new CliError(
|
|
163
|
+
"invalid_argument",
|
|
164
|
+
`\u65E0\u6548\u7684 Bug \u5F15\u7528\uFF1A${reference}\u3002\u8BF7\u4F20\u5165\u6570\u5B57 ID \u6216 bug-view-{id}.html \u94FE\u63A5`
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
return id;
|
|
168
|
+
}
|
|
169
|
+
function parseBugIds(references) {
|
|
170
|
+
const values = references.flatMap((item) => item.split(",")).filter(Boolean);
|
|
171
|
+
if (values.length === 0) throw new CliError("invalid_argument", "\u81F3\u5C11\u9700\u8981\u4E00\u4E2A Bug ID");
|
|
172
|
+
return [...new Set(values.map(parseBugId))];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/core/config.ts
|
|
176
|
+
var DEFAULT_ZENTAO_API_URL = "http://172.16.85.194:6789";
|
|
177
|
+
function resolveZentaoBaseUrl(explicit, env) {
|
|
178
|
+
return (explicit ?? env.DTSTACK_ZENTAO_BASE_URL ?? DEFAULT_ZENTAO_API_URL).replace(/\/$/, "");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// src/core/output.ts
|
|
182
|
+
function resolveOutputMode(requested, writer) {
|
|
183
|
+
if (requested !== "auto") return requested;
|
|
184
|
+
return writer.isTTY() ? "human" : "json";
|
|
185
|
+
}
|
|
186
|
+
function printResult(result, mode, renderHuman2, writer) {
|
|
187
|
+
if (resolveOutputMode(mode, writer) === "json") {
|
|
188
|
+
writer.stdout(JSON.stringify(result, null, 2));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (result.ok) writer.stdout(renderHuman2(result.data));
|
|
192
|
+
else writer.stderr(`\u2717 ${result.error.message} (${result.error.code})`);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/core/result.ts
|
|
196
|
+
var SCHEMA_VERSION = "1";
|
|
197
|
+
function meta(command, startedAt, requestId) {
|
|
198
|
+
return { command, durationMs: Date.now() - startedAt, requestId };
|
|
199
|
+
}
|
|
200
|
+
function success(data, command, startedAt, requestId) {
|
|
201
|
+
return { ok: true, schemaVersion: SCHEMA_VERSION, data, meta: meta(command, startedAt, requestId) };
|
|
202
|
+
}
|
|
203
|
+
function failure(error, command, startedAt, requestId) {
|
|
204
|
+
const payload = {
|
|
205
|
+
ok: false,
|
|
206
|
+
schemaVersion: SCHEMA_VERSION,
|
|
207
|
+
error: {
|
|
208
|
+
code: error.code,
|
|
209
|
+
message: error.message,
|
|
210
|
+
retryable: error.options.retryable ?? false
|
|
211
|
+
},
|
|
212
|
+
meta: meta(command, startedAt, requestId)
|
|
213
|
+
};
|
|
214
|
+
if (error.options.details !== void 0) payload.error.details = error.options.details;
|
|
215
|
+
return payload;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/commands/bug.ts
|
|
219
|
+
var defaultDependencies = {
|
|
220
|
+
writer: {
|
|
221
|
+
stdout: (value) => process.stdout.write(`${value}
|
|
222
|
+
`),
|
|
223
|
+
stderr: (value) => process.stderr.write(`${value}
|
|
224
|
+
`),
|
|
225
|
+
isTTY: () => Boolean(process.stdout.isTTY)
|
|
226
|
+
},
|
|
227
|
+
createClient: (options) => new ZentaoClient(options),
|
|
228
|
+
env: process.env
|
|
229
|
+
};
|
|
230
|
+
function cleanText(value) {
|
|
231
|
+
return String(value ?? "").replace(/<[^>]+>/g, " ").replace(/ /gi, " ").replace(/\s+/g, " ").trim();
|
|
232
|
+
}
|
|
233
|
+
function renderBugList(bugs) {
|
|
234
|
+
if (bugs.length === 0) return "\u672A\u627E\u5230 Bug";
|
|
235
|
+
const blocks = bugs.map((bug) => {
|
|
236
|
+
const lines = [
|
|
237
|
+
`\u3010${cleanText(bug.bugId) || "-"}\u3011${cleanText(bug.bugTitle) || "-"}`,
|
|
238
|
+
`\u72B6\u6001: ${cleanText(bug.bugStatus) || "-"} \u7C7B\u578B: ${cleanText(bug.bugType) || "-"} \u4EA7\u54C1: ${cleanText(bug.productName) || "-"}`,
|
|
239
|
+
`\u63CF\u8FF0: ${cleanText(bug.bugDesc) || "-"}`
|
|
240
|
+
];
|
|
241
|
+
return lines.join("\n");
|
|
242
|
+
});
|
|
243
|
+
return blocks.join("\n\n");
|
|
244
|
+
}
|
|
245
|
+
function readGlobalOptions(command, dependencies) {
|
|
246
|
+
const opts = command.optsWithGlobals();
|
|
247
|
+
const baseUrl = resolveZentaoBaseUrl(opts.baseUrl, dependencies.env);
|
|
248
|
+
const envOutput = dependencies.env.DTSTACK_OUTPUT;
|
|
249
|
+
const output = opts.json ? "json" : opts.output ?? envOutput ?? "auto";
|
|
250
|
+
if (!["auto", "human", "json"].includes(output)) {
|
|
251
|
+
throw new CliError("invalid_argument", `\u4E0D\u652F\u6301\u7684\u8F93\u51FA\u6A21\u5F0F\uFF1A${output}`);
|
|
252
|
+
}
|
|
253
|
+
return { baseUrl, output };
|
|
254
|
+
}
|
|
255
|
+
async function run(commandName, command, action, render, dependencies) {
|
|
256
|
+
const startedAt = Date.now();
|
|
257
|
+
const requestId = randomUUID2();
|
|
258
|
+
let output = "auto";
|
|
259
|
+
try {
|
|
260
|
+
const globals = readGlobalOptions(command, dependencies);
|
|
261
|
+
output = globals.output;
|
|
262
|
+
const data = await action(dependencies.createClient({ baseUrl: globals.baseUrl }));
|
|
263
|
+
printResult(success(data, commandName, startedAt, requestId), output, render, dependencies.writer);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
const result = failure(toCliError(error), commandName, startedAt, requestId);
|
|
266
|
+
printResult(result, output, render, dependencies.writer);
|
|
267
|
+
process.exitCode = 1;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
function positiveInteger(name, value, max = Number.MAX_SAFE_INTEGER) {
|
|
271
|
+
const parsed = z2.coerce.number().int().positive().max(max).safeParse(value);
|
|
272
|
+
if (!parsed.success) throw new CliError("invalid_argument", `${name} \u5FC5\u987B\u662F\u6B63\u6574\u6570`);
|
|
273
|
+
return parsed.data;
|
|
274
|
+
}
|
|
275
|
+
function preciseOptions(options) {
|
|
276
|
+
const query = {
|
|
277
|
+
pageNum: positiveInteger("page", options.page ?? "1"),
|
|
278
|
+
pageSize: positiveInteger("page-size", options.pageSize ?? "20", 1e3)
|
|
279
|
+
};
|
|
280
|
+
if (options.assignedTo) query.assignedTo = options.assignedTo;
|
|
281
|
+
if (options.openedBy) query.openedBy = options.openedBy;
|
|
282
|
+
if (options.status) query.status = options.status;
|
|
283
|
+
if (options.product) query.productName = options.product;
|
|
284
|
+
if (options.assignedFrom) query.assignedDateStart = options.assignedFrom;
|
|
285
|
+
if (options.assignedToDate) query.assignedDateEnd = options.assignedToDate;
|
|
286
|
+
return query;
|
|
287
|
+
}
|
|
288
|
+
function registerBugCommands(program, dependencies = defaultDependencies) {
|
|
289
|
+
const bug = program.command("bug").description("\u67E5\u8BE2\u548C\u68C0\u7D22\u7985\u9053 Bug");
|
|
290
|
+
bug.command("view").description("\u6839\u636E ID \u6216\u7985\u9053\u94FE\u63A5\u67E5\u770B Bug\uFF0C\u652F\u6301\u7A7A\u683C\u6216\u9017\u53F7\u5206\u9694\u7684\u6279\u91CF\u8F93\u5165").argument("<references...>", "Bug ID\u3001ID \u5217\u8868\u6216 bug-view-{id}.html \u94FE\u63A5").action(async (references, _options, command) => {
|
|
291
|
+
await run("bug.view", command, (client) => client.getBugDetails(parseBugIds(references)), renderBugList, dependencies);
|
|
292
|
+
});
|
|
293
|
+
bug.command("search").description("\u6309\u5173\u952E\u8BCD\u641C\u7D22 Bug").argument("<query>", "\u641C\u7D22\u5173\u952E\u8BCD").option("-l, --limit <number>", "\u6700\u5927\u7ED3\u679C\u6570", "20").action(async (query, options, command) => {
|
|
294
|
+
await run(
|
|
295
|
+
"bug.search",
|
|
296
|
+
command,
|
|
297
|
+
(client) => client.searchBugs(query, positiveInteger("limit", options.limit, 100)),
|
|
298
|
+
renderBugList,
|
|
299
|
+
dependencies
|
|
300
|
+
);
|
|
301
|
+
});
|
|
302
|
+
bug.command("list").description("\u6309\u5904\u7406\u4EBA\u3001\u72B6\u6001\u3001\u4EA7\u54C1\u548C\u65E5\u671F\u7CBE\u786E\u7B5B\u9009 Bug").option("-a, --assigned-to <users>", "\u5904\u7406\u4EBA\uFF0C\u591A\u4E2A\u8D26\u53F7\u7528\u82F1\u6587\u9017\u53F7\u5206\u9694").option("--opened-by <users>", "\u521B\u5EFA\u4EBA\uFF0C\u591A\u4E2A\u8D26\u53F7\u7528\u82F1\u6587\u9017\u53F7\u5206\u9694").option("-s, --status <statuses>", "\u72B6\u6001\uFF0C\u591A\u4E2A\u72B6\u6001\u7528\u82F1\u6587\u9017\u53F7\u5206\u9694").option("-p, --product <name>", "\u4EA7\u54C1\u540D\u79F0").option("--assigned-from <date>", "\u6307\u6D3E\u5F00\u59CB\u65E5\u671F YYYY-MM-DD").option("--assigned-to-date <date>", "\u6307\u6D3E\u7ED3\u675F\u65E5\u671F YYYY-MM-DD").option("--page <number>", "\u9875\u7801", "1").option("--page-size <number>", "\u6BCF\u9875\u6570\u91CF\uFF0C\u6700\u5927 1000", "20").action(async (options, command) => {
|
|
303
|
+
await run("bug.list", command, (client) => client.preciseBugs(preciseOptions(options)), renderBugList, dependencies);
|
|
304
|
+
});
|
|
305
|
+
bug.command("assigned").description("\u67E5\u770B\u6307\u6D3E\u7ED9\u6307\u5B9A\u7528\u6237\u7684 Bug\uFF1B\u7701\u7565\u7528\u6237\u65F6\u8BFB\u53D6 DTSTACK_USER").argument("[user]", "\u7985\u9053\u8D26\u53F7").option("-s, --status <statuses>", "\u72B6\u6001", "active").option("--page <number>", "\u9875\u7801", "1").option("--page-size <number>", "\u6BCF\u9875\u6570\u91CF\uFF0C\u6700\u5927 1000", "20").action(async (user, options, command) => {
|
|
306
|
+
await run(
|
|
307
|
+
"bug.assigned",
|
|
308
|
+
command,
|
|
309
|
+
(client) => {
|
|
310
|
+
const assignedTo = user ?? dependencies.env.DTSTACK_USER;
|
|
311
|
+
if (!assignedTo) {
|
|
312
|
+
throw new CliError("invalid_argument", "\u8BF7\u4F20\u5165\u7985\u9053\u8D26\u53F7\uFF0C\u6216\u8BBE\u7F6E DTSTACK_USER");
|
|
313
|
+
}
|
|
314
|
+
return client.preciseBugs({ ...preciseOptions(options), assignedTo });
|
|
315
|
+
},
|
|
316
|
+
renderBugList,
|
|
317
|
+
dependencies
|
|
318
|
+
);
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// src/commands/auth.ts
|
|
323
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
324
|
+
import { emitKeypressEvents } from "readline";
|
|
325
|
+
import { createInterface } from "readline/promises";
|
|
326
|
+
import { input, password } from "@inquirer/prompts";
|
|
327
|
+
|
|
328
|
+
// src/adapters/gitlab/glab.ts
|
|
329
|
+
import { execFile, spawnSync } from "child_process";
|
|
330
|
+
import { promisify } from "util";
|
|
331
|
+
var execFileAsync = promisify(execFile);
|
|
332
|
+
var DEFAULT_GITLAB_HOST = "gitlab.prod.dtstack.cn";
|
|
333
|
+
function mapGlabError(error) {
|
|
334
|
+
const detail = error;
|
|
335
|
+
const message = `${detail.stderr ?? ""}
|
|
336
|
+
${detail.message ?? ""}`.trim();
|
|
337
|
+
if (/not logged|authenticate|unauthorized|401|token.*invalid/i.test(message)) {
|
|
338
|
+
return new CliError("not_authenticated", "GitLab \u672A\u767B\u5F55\u6216\u51ED\u636E\u5DF2\u5931\u6548\uFF0C\u8BF7\u6267\u884C glab auth login", {
|
|
339
|
+
details: message,
|
|
340
|
+
cause: error
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
if (/not a git repository|no remotes|repository.*required|could not determine/i.test(message)) {
|
|
344
|
+
return new CliError("invalid_argument", "\u65E0\u6CD5\u8BC6\u522B GitLab \u4ED3\u5E93\uFF0C\u8BF7\u5728 Git \u4ED3\u5E93\u4E2D\u6267\u884C\u6216\u4F20\u5165 --repo group/project", {
|
|
345
|
+
details: message,
|
|
346
|
+
cause: error
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
if (/timeout|connection|network|dial tcp|no such host/i.test(message)) {
|
|
350
|
+
return new CliError("network_error", "\u65E0\u6CD5\u8FDE\u63A5 GitLab\uFF0C\u8BF7\u68C0\u67E5\u516C\u53F8\u7F51\u7EDC\u6216 VPN", {
|
|
351
|
+
retryable: true,
|
|
352
|
+
details: message,
|
|
353
|
+
cause: error
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
if (detail.code === "ENOENT") {
|
|
357
|
+
return new CliError("invalid_argument", "\u672A\u627E\u5230 glab\uFF0C\u8BF7\u5148\u5B89\u88C5 GitLab CLI", { cause: error });
|
|
358
|
+
}
|
|
359
|
+
return new CliError("upstream_error", "GitLab CLI \u6267\u884C\u5931\u8D25", { details: message, cause: error });
|
|
360
|
+
}
|
|
361
|
+
var defaultGlabRunner = async (args, options = {}) => {
|
|
362
|
+
try {
|
|
363
|
+
const { stdout, stderr } = await execFileAsync("glab", args, {
|
|
364
|
+
cwd: options.cwd,
|
|
365
|
+
env: { ...process.env, GLAB_CHECK_UPDATE: "false", ...options.env },
|
|
366
|
+
encoding: "utf8",
|
|
367
|
+
maxBuffer: 20 * 1024 * 1024
|
|
368
|
+
});
|
|
369
|
+
return { stdout, stderr };
|
|
370
|
+
} catch (error) {
|
|
371
|
+
throw mapGlabError(error);
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
function runGlabInteractive(args, options = {}) {
|
|
375
|
+
const result = spawnSync("glab", args, {
|
|
376
|
+
cwd: options.cwd,
|
|
377
|
+
env: { ...process.env, GLAB_CHECK_UPDATE: "false", ...options.env },
|
|
378
|
+
stdio: "inherit"
|
|
379
|
+
});
|
|
380
|
+
if (result.error) throw mapGlabError(result.error);
|
|
381
|
+
if (result.status !== 0) {
|
|
382
|
+
throw mapGlabError({ message: `glab exited with status ${String(result.status)}`, code: result.status });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
function parseJson(stdout, command) {
|
|
386
|
+
try {
|
|
387
|
+
return JSON.parse(stdout);
|
|
388
|
+
} catch (error) {
|
|
389
|
+
throw new CliError("invalid_response", `glab ${command} \u8FD4\u56DE\u4E86\u975E JSON \u5185\u5BB9`, {
|
|
390
|
+
details: stdout.slice(0, 500),
|
|
391
|
+
cause: error
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
var GlabClient = class {
|
|
396
|
+
constructor(runner = defaultGlabRunner, options = {}) {
|
|
397
|
+
this.runner = runner;
|
|
398
|
+
this.options = options;
|
|
399
|
+
}
|
|
400
|
+
runner;
|
|
401
|
+
options;
|
|
402
|
+
repoArgs(repo) {
|
|
403
|
+
return repo ? ["--repo", repo] : [];
|
|
404
|
+
}
|
|
405
|
+
projectApiPath(repo) {
|
|
406
|
+
if (!repo) return "projects/:fullpath";
|
|
407
|
+
let path = repo.trim();
|
|
408
|
+
if (/^https?:\/\//.test(path)) path = new URL(path).pathname;
|
|
409
|
+
else if (/^[^@]+@[^:]+:/.test(path)) path = path.slice(path.indexOf(":") + 1);
|
|
410
|
+
path = path.replace(/^\//, "").replace(/\.git$/, "");
|
|
411
|
+
if (!path.includes("/")) {
|
|
412
|
+
throw new CliError("invalid_argument", "--repo \u5FC5\u987B\u662F group/project\u3001Git URL \u6216\u9879\u76EE URL");
|
|
413
|
+
}
|
|
414
|
+
return `projects/${encodeURIComponent(path)}`;
|
|
415
|
+
}
|
|
416
|
+
async viewMergeRequest(iid, repo) {
|
|
417
|
+
const result = await this.runner(
|
|
418
|
+
["mr", "view", String(iid), "--output", "json", ...this.repoArgs(repo)],
|
|
419
|
+
this.options
|
|
420
|
+
);
|
|
421
|
+
return parseJson(result.stdout, "mr view");
|
|
422
|
+
}
|
|
423
|
+
async listMergeRequests(options) {
|
|
424
|
+
const args = [
|
|
425
|
+
"mr",
|
|
426
|
+
"list",
|
|
427
|
+
"--output",
|
|
428
|
+
"json",
|
|
429
|
+
"--page",
|
|
430
|
+
String(options.page),
|
|
431
|
+
"--per-page",
|
|
432
|
+
String(options.perPage),
|
|
433
|
+
...this.repoArgs(options.repo)
|
|
434
|
+
];
|
|
435
|
+
if (options.state === "closed") args.push("--closed");
|
|
436
|
+
if (options.state === "merged") args.push("--merged");
|
|
437
|
+
if (options.state === "all") args.push("--all");
|
|
438
|
+
if (options.mine) args.push("--author", "@me");
|
|
439
|
+
if (options.author) args.push("--author", options.author);
|
|
440
|
+
if (options.assignee) args.push("--assignee", options.assignee);
|
|
441
|
+
if (options.search) args.push("--search", options.search);
|
|
442
|
+
const result = await this.runner(args, this.options);
|
|
443
|
+
return parseJson(result.stdout, "mr list");
|
|
444
|
+
}
|
|
445
|
+
async diffMergeRequest(iid, repo) {
|
|
446
|
+
const result = await this.runner(
|
|
447
|
+
["mr", "diff", String(iid), "--raw", "--color=never", ...this.repoArgs(repo)],
|
|
448
|
+
this.options
|
|
449
|
+
);
|
|
450
|
+
return { diff: result.stdout };
|
|
451
|
+
}
|
|
452
|
+
async mergeRequestPipeline(iid, repo) {
|
|
453
|
+
const mergeRequest = await this.viewMergeRequest(iid, repo);
|
|
454
|
+
const sourceBranch = mergeRequest.source_branch ?? mergeRequest.sourceBranch;
|
|
455
|
+
if (typeof sourceBranch !== "string" || !sourceBranch) {
|
|
456
|
+
throw new CliError("invalid_response", "MR \u6570\u636E\u4E2D\u7F3A\u5C11 source branch\uFF0C\u65E0\u6CD5\u67E5\u8BE2 Pipeline");
|
|
457
|
+
}
|
|
458
|
+
const host = this.options.env?.GITLAB_HOST ?? DEFAULT_GITLAB_HOST;
|
|
459
|
+
const endpoint = `${this.projectApiPath(repo)}/merge_requests/${String(iid)}/pipelines`;
|
|
460
|
+
const result = await this.runner(
|
|
461
|
+
["api", endpoint, "--hostname", host, "--output", "json"],
|
|
462
|
+
this.options
|
|
463
|
+
);
|
|
464
|
+
return {
|
|
465
|
+
mergeRequest: { iid, sourceBranch, repo: repo ?? null },
|
|
466
|
+
pipeline: parseJson(result.stdout, "ci status")
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
async resolveUserId(username) {
|
|
470
|
+
const host = this.options.env?.GITLAB_HOST ?? DEFAULT_GITLAB_HOST;
|
|
471
|
+
const result = await this.runner(
|
|
472
|
+
["api", `users?username=${encodeURIComponent(username)}`, "--hostname", host, "--output", "json"],
|
|
473
|
+
this.options
|
|
474
|
+
);
|
|
475
|
+
const users = parseJson(result.stdout, "api users");
|
|
476
|
+
if (!Array.isArray(users)) throw new CliError("invalid_response", "GitLab \u7528\u6237\u67E5\u8BE2\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u6570\u636E\u7ED3\u6784");
|
|
477
|
+
const matched = users.find(
|
|
478
|
+
(user) => user && typeof user === "object" && user.username === username
|
|
479
|
+
);
|
|
480
|
+
const id = matched?.id;
|
|
481
|
+
if (typeof id !== "number") {
|
|
482
|
+
throw new CliError("invalid_argument", `\u627E\u4E0D\u5230 GitLab \u7528\u6237\uFF1A${username}`);
|
|
483
|
+
}
|
|
484
|
+
return id;
|
|
485
|
+
}
|
|
486
|
+
async createMergeRequest(options) {
|
|
487
|
+
if (options.description.includes("\\n")) {
|
|
488
|
+
throw new CliError("invalid_argument", "MR \u63CF\u8FF0\u5305\u542B\u5B57\u9762\u91CF \\n\uFF0C\u8BF7\u6539\u7528\u771F\u5B9E\u6362\u884C");
|
|
489
|
+
}
|
|
490
|
+
const host = this.options.env?.GITLAB_HOST ?? DEFAULT_GITLAB_HOST;
|
|
491
|
+
const endpoint = `${this.projectApiPath(options.repo)}/merge_requests`;
|
|
492
|
+
const args = [
|
|
493
|
+
"api",
|
|
494
|
+
endpoint,
|
|
495
|
+
"--method",
|
|
496
|
+
"POST",
|
|
497
|
+
"--hostname",
|
|
498
|
+
host,
|
|
499
|
+
"--output",
|
|
500
|
+
"json",
|
|
501
|
+
"--field",
|
|
502
|
+
`source_branch=${options.sourceBranch}`,
|
|
503
|
+
"--field",
|
|
504
|
+
`target_branch=${options.targetBranch}`,
|
|
505
|
+
"--field",
|
|
506
|
+
`title=${options.title}`,
|
|
507
|
+
"--field",
|
|
508
|
+
`description=${options.description}`
|
|
509
|
+
];
|
|
510
|
+
if (options.removeSourceBranch !== void 0) {
|
|
511
|
+
args.push("--field", `remove_source_branch=${String(options.removeSourceBranch)}`);
|
|
512
|
+
}
|
|
513
|
+
if (options.assigneeId !== void 0) {
|
|
514
|
+
args.push("--field", `assignee_ids[]=${String(options.assigneeId)}`);
|
|
515
|
+
}
|
|
516
|
+
const createdResult = await this.runner(args, this.options);
|
|
517
|
+
const created = parseJson(createdResult.stdout, "api create merge request");
|
|
518
|
+
const iid = created.iid;
|
|
519
|
+
if (typeof iid !== "number") throw new CliError("invalid_response", "GitLab \u521B\u5EFA MR \u7684\u54CD\u5E94\u4E2D\u7F3A\u5C11 iid");
|
|
520
|
+
const verifiedResult = await this.runner(
|
|
521
|
+
["api", `${endpoint}/${String(iid)}`, "--hostname", host, "--output", "json"],
|
|
522
|
+
this.options
|
|
523
|
+
);
|
|
524
|
+
const verified = parseJson(verifiedResult.stdout, "api verify merge request");
|
|
525
|
+
if (verified.title !== options.title || verified.description !== options.description) {
|
|
526
|
+
throw new CliError("invalid_response", "MR \u521B\u5EFA\u540E\u590D\u67E5\u53D1\u73B0\u6807\u9898\u6216\u63CF\u8FF0\u4E0D\u4E00\u81F4", {
|
|
527
|
+
details: { iid, expectedTitle: options.title }
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
if (options.removeSourceBranch === true && verified.force_remove_source_branch !== true) {
|
|
531
|
+
throw new CliError("invalid_response", "MR \u521B\u5EFA\u540E\u672A\u786E\u8BA4\u5220\u9664\u6E90\u5206\u652F\u9009\u9879", {
|
|
532
|
+
details: { iid, forceRemoveSourceBranch: verified.force_remove_source_branch }
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
return verified;
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
function gitlabEnvironment(env) {
|
|
539
|
+
return {
|
|
540
|
+
...env,
|
|
541
|
+
GITLAB_HOST: env.DTSTACK_GITLAB_HOST ?? env.GITLAB_HOST ?? DEFAULT_GITLAB_HOST
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// src/adapters/lanhu/auth/errors.ts
|
|
546
|
+
var LanhuError = class extends Error {
|
|
547
|
+
code;
|
|
548
|
+
hint;
|
|
549
|
+
constructor(code, message, hint) {
|
|
550
|
+
super(message);
|
|
551
|
+
this.name = "LanhuError";
|
|
552
|
+
this.code = code;
|
|
553
|
+
if (hint !== void 0) {
|
|
554
|
+
this.hint = hint;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
var CORE_ERROR_CODES = {
|
|
559
|
+
AUTH_REQUIRED: "not_authenticated",
|
|
560
|
+
INVALID_CREDENTIALS: "not_authenticated",
|
|
561
|
+
VERIFICATION_REQUIRED: "not_authenticated",
|
|
562
|
+
PUBLIC_KEY_NOT_FOUND: "upstream_error",
|
|
563
|
+
ENCRYPTION_FAILED: "internal_error",
|
|
564
|
+
LOGIN_REJECTED: "upstream_error",
|
|
565
|
+
BROWSER_NOT_FOUND: "invalid_argument",
|
|
566
|
+
BROWSER_PERMISSION_DENIED: "internal_error",
|
|
567
|
+
BROWSER_TIMEOUT: "timeout",
|
|
568
|
+
NETWORK_ERROR: "network_error",
|
|
569
|
+
STORAGE_ERROR: "internal_error",
|
|
570
|
+
USAGE_ERROR: "invalid_argument",
|
|
571
|
+
PROTOCOL_ERROR: "invalid_response",
|
|
572
|
+
PRD_EXTRACTOR_NOT_FOUND: "invalid_argument"
|
|
573
|
+
};
|
|
574
|
+
function lanhuToCliError(error) {
|
|
575
|
+
if (error instanceof CliError) return error;
|
|
576
|
+
if (error instanceof LanhuError) {
|
|
577
|
+
const hint = error.hint === void 0 ? void 0 : redact(error.hint);
|
|
578
|
+
const message2 = hint === void 0 ? redact(error.message) : `${redact(error.message)}
|
|
579
|
+
\u4E0B\u4E00\u6B65\uFF1A${hint}`;
|
|
580
|
+
const retryable = error.code === "NETWORK_ERROR" || error.code === "BROWSER_TIMEOUT";
|
|
581
|
+
return new CliError(CORE_ERROR_CODES[error.code], message2, {
|
|
582
|
+
retryable,
|
|
583
|
+
details: {
|
|
584
|
+
lanhuCode: error.code,
|
|
585
|
+
...hint !== void 0 ? { hint } : {}
|
|
586
|
+
},
|
|
587
|
+
cause: error
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
const message = error instanceof Error ? redact(error.message) : "\u53D1\u751F\u672A\u77E5\u9519\u8BEF";
|
|
591
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
592
|
+
return new CliError("timeout", "\u8BF7\u6C42\u84DD\u6E56\u670D\u52A1\u8D85\u65F6", { retryable: true, cause: error });
|
|
593
|
+
}
|
|
594
|
+
if (error instanceof TypeError) {
|
|
595
|
+
return new CliError("network_error", `\u65E0\u6CD5\u8FDE\u63A5\u84DD\u6E56\u670D\u52A1\uFF1A${message}`, {
|
|
596
|
+
retryable: true,
|
|
597
|
+
cause: error
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
return new CliError("internal_error", message, { cause: error });
|
|
601
|
+
}
|
|
602
|
+
function redact(input2) {
|
|
603
|
+
return input2.replace(
|
|
604
|
+
/\b(?:password|sso_ticket|ticket|cookie|set-cookie|authorization)[ \t]*=[ \t]*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s&]+)/gi,
|
|
605
|
+
"[REDACTED]"
|
|
606
|
+
).replace(
|
|
607
|
+
/(["']?)(password|sso_ticket|ticket|cookie|set-cookie|authorization)\1([ \t]*:[ \t]*)(["'])((?:\\.|[^\\\r\n])*?)\4/gi,
|
|
608
|
+
(_match, keyQuote, key, separator, valueQuote) => `${keyQuote}${key}${keyQuote}${separator}${valueQuote}[REDACTED]${valueQuote}`
|
|
609
|
+
).replace(
|
|
610
|
+
/(["']?)(password|sso_ticket|ticket)\1([ \t]*:[ \t]*)(?!["'])([^\s,}\]]+)/gi,
|
|
611
|
+
(_match, keyQuote, key, separator) => `${keyQuote}${key}${keyQuote}${separator}[REDACTED]`
|
|
612
|
+
).replace(
|
|
613
|
+
/(["']?)(cookie|set-cookie|authorization)\1([ \t]*:[ \t]*)(?!["'])([^\r\n]*)/gi,
|
|
614
|
+
(_match, keyQuote, key, separator) => `${keyQuote}${key}${keyQuote}${separator}[REDACTED]`
|
|
615
|
+
).replace(
|
|
616
|
+
/-----BEGIN RSA PRIVATE KEY-----[\s\S]*?-----END RSA PRIVATE KEY-----/gi,
|
|
617
|
+
"-----BEGIN RSA PRIVATE KEY-----[REDACTED]-----END RSA PRIVATE KEY-----"
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// src/adapters/lanhu/factory.ts
|
|
622
|
+
import { CookieJar as CookieJar3 } from "tough-cookie";
|
|
623
|
+
|
|
624
|
+
// src/adapters/lanhu/auth/auth-service.ts
|
|
625
|
+
import { rm } from "fs/promises";
|
|
626
|
+
import { basename } from "path";
|
|
627
|
+
|
|
628
|
+
// src/adapters/lanhu/http/request-with-cookies.ts
|
|
629
|
+
var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
630
|
+
function protocolError(message) {
|
|
631
|
+
return new LanhuError("PROTOCOL_ERROR", message);
|
|
632
|
+
}
|
|
633
|
+
async function cancelResponseBody(response) {
|
|
634
|
+
try {
|
|
635
|
+
await response.body?.cancel();
|
|
636
|
+
} catch {
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
async function requestWithCookies(initialUrl, init, jar, options = {}) {
|
|
640
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
641
|
+
const maxRedirects = options.maxRedirects ?? 10;
|
|
642
|
+
const neverSignal = new AbortController().signal;
|
|
643
|
+
const signal = AbortSignal.any([
|
|
644
|
+
init.signal ?? neverSignal,
|
|
645
|
+
AbortSignal.timeout(timeoutMs)
|
|
646
|
+
]);
|
|
647
|
+
const headers = new Headers(init.headers);
|
|
648
|
+
const initial = new URL(initialUrl);
|
|
649
|
+
const initialOrigin = initial.origin;
|
|
650
|
+
let currentUrl = initial.href;
|
|
651
|
+
let method = init.method ?? "GET";
|
|
652
|
+
let body = init.body ?? null;
|
|
653
|
+
let redirectCount = 0;
|
|
654
|
+
for (; ; ) {
|
|
655
|
+
const cookie = await jar.getCookieString(currentUrl);
|
|
656
|
+
if (cookie !== "") {
|
|
657
|
+
headers.set("Cookie", cookie);
|
|
658
|
+
} else {
|
|
659
|
+
headers.delete("Cookie");
|
|
660
|
+
}
|
|
661
|
+
const response = await fetch(currentUrl, {
|
|
662
|
+
...init,
|
|
663
|
+
method,
|
|
664
|
+
headers,
|
|
665
|
+
body,
|
|
666
|
+
redirect: "manual",
|
|
667
|
+
signal
|
|
668
|
+
});
|
|
669
|
+
const isRedirect = REDIRECT_STATUSES.has(response.status);
|
|
670
|
+
if (isRedirect) {
|
|
671
|
+
await cancelResponseBody(response);
|
|
672
|
+
}
|
|
673
|
+
try {
|
|
674
|
+
for (const value of response.headers.getSetCookie()) {
|
|
675
|
+
await jar.setCookie(value, currentUrl);
|
|
676
|
+
}
|
|
677
|
+
} catch (error) {
|
|
678
|
+
if (!isRedirect) {
|
|
679
|
+
await cancelResponseBody(response);
|
|
680
|
+
}
|
|
681
|
+
throw error;
|
|
682
|
+
}
|
|
683
|
+
if (!isRedirect) {
|
|
684
|
+
return response;
|
|
685
|
+
}
|
|
686
|
+
const location = response.headers.get("location");
|
|
687
|
+
if (location === null || location === "") {
|
|
688
|
+
throw protocolError("Redirect response is missing a Location header");
|
|
689
|
+
}
|
|
690
|
+
const nextUrl = new URL(location, currentUrl).href;
|
|
691
|
+
const nextOrigin = new URL(nextUrl).origin;
|
|
692
|
+
if (options.sameOriginRedirects === true && nextOrigin !== initialOrigin) {
|
|
693
|
+
throw protocolError("Cross-origin redirect is not allowed");
|
|
694
|
+
}
|
|
695
|
+
if (redirectCount >= maxRedirects) {
|
|
696
|
+
throw protocolError("Maximum redirect count exceeded");
|
|
697
|
+
}
|
|
698
|
+
redirectCount += 1;
|
|
699
|
+
if (nextOrigin !== new URL(currentUrl).origin) {
|
|
700
|
+
headers.delete("Authorization");
|
|
701
|
+
}
|
|
702
|
+
const normalizedMethod = method.toUpperCase();
|
|
703
|
+
if (response.status === 303 && normalizedMethod !== "GET" && normalizedMethod !== "HEAD" || (response.status === 301 || response.status === 302) && normalizedMethod === "POST") {
|
|
704
|
+
method = "GET";
|
|
705
|
+
body = null;
|
|
706
|
+
headers.delete("Content-Type");
|
|
707
|
+
}
|
|
708
|
+
currentUrl = nextUrl;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// src/adapters/lanhu/http/authenticated-client.ts
|
|
713
|
+
var AuthenticatedHttpClient = class {
|
|
714
|
+
constructor(ensureJar) {
|
|
715
|
+
this.ensureJar = ensureJar;
|
|
716
|
+
}
|
|
717
|
+
ensureJar;
|
|
718
|
+
async request(url, init = {}) {
|
|
719
|
+
return requestWithCookies(url, init, await this.ensureJar());
|
|
720
|
+
}
|
|
721
|
+
async get(url, init = {}) {
|
|
722
|
+
return this.request(url, { ...init, method: "GET" });
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
|
|
726
|
+
// src/adapters/lanhu/auth/auth-service.ts
|
|
727
|
+
var BROWSER_RELOGIN_TIMEOUT_MS = 3e5;
|
|
728
|
+
var CREDENTIAL_SAVE_HINT = "The current session is valid, but silent re-login may be unavailable until the password is stored again";
|
|
729
|
+
function authRequiredError(message, hint) {
|
|
730
|
+
return new LanhuError("AUTH_REQUIRED", message, hint);
|
|
731
|
+
}
|
|
732
|
+
function networkError(message) {
|
|
733
|
+
return new LanhuError("NETWORK_ERROR", message);
|
|
734
|
+
}
|
|
735
|
+
function storageConfigError(message) {
|
|
736
|
+
return new LanhuError("STORAGE_ERROR", message);
|
|
737
|
+
}
|
|
738
|
+
function isDedicatedBrowserProfile(path) {
|
|
739
|
+
return path !== "" && basename(path) === "browser-profile";
|
|
740
|
+
}
|
|
741
|
+
function isEmptyJar(jar) {
|
|
742
|
+
const serialized = jar.toJSON();
|
|
743
|
+
return serialized === void 0 || serialized.cookies.length === 0;
|
|
744
|
+
}
|
|
745
|
+
var AuthService = class {
|
|
746
|
+
constructor(flows, validator, cookies, metadata, credentials, browserProfile) {
|
|
747
|
+
this.flows = flows;
|
|
748
|
+
this.validator = validator;
|
|
749
|
+
this.cookies = cookies;
|
|
750
|
+
this.metadata = metadata;
|
|
751
|
+
this.credentials = credentials;
|
|
752
|
+
this.browserProfile = browserProfile;
|
|
753
|
+
}
|
|
754
|
+
flows;
|
|
755
|
+
validator;
|
|
756
|
+
cookies;
|
|
757
|
+
metadata;
|
|
758
|
+
credentials;
|
|
759
|
+
browserProfile;
|
|
760
|
+
/** A single in-flight recovery promise shared by concurrent callers. */
|
|
761
|
+
recovery;
|
|
762
|
+
/**
|
|
763
|
+
* Monotonic generation used to invalidate in-flight session recovery after
|
|
764
|
+
* logout, so a delayed persist can never resurrect a cleared session.
|
|
765
|
+
*/
|
|
766
|
+
generation = 0;
|
|
767
|
+
authenticatedClient() {
|
|
768
|
+
return new AuthenticatedHttpClient(() => this.ensureJar());
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Resolve the current authenticated session jar. Shares the same recovery
|
|
772
|
+
* logic the authenticated HTTP client uses, so downstream modules (for
|
|
773
|
+
* example PRD download) reuse the persisted session instead of any manual
|
|
774
|
+
* cookie or token.
|
|
775
|
+
*/
|
|
776
|
+
authenticatedJar() {
|
|
777
|
+
return this.ensureJar();
|
|
778
|
+
}
|
|
779
|
+
async loginBrowser(options) {
|
|
780
|
+
return this.persist(await this.flows.browser(options));
|
|
781
|
+
}
|
|
782
|
+
async loginPassword(options) {
|
|
783
|
+
const result = await this.flows.password(options);
|
|
784
|
+
if (result.validation.state === "valid") {
|
|
785
|
+
try {
|
|
786
|
+
await this.credentials.save(options.account, options.password);
|
|
787
|
+
} catch {
|
|
788
|
+
throw new LanhuError(
|
|
789
|
+
"STORAGE_ERROR",
|
|
790
|
+
"Unable to store the password in the system credential store",
|
|
791
|
+
CREDENTIAL_SAVE_HINT
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
return this.persist(result);
|
|
796
|
+
}
|
|
797
|
+
async status() {
|
|
798
|
+
const jar = await this.cookies.load();
|
|
799
|
+
const metadata = await this.metadata.load();
|
|
800
|
+
if (metadata === void 0) {
|
|
801
|
+
return {
|
|
802
|
+
metadata,
|
|
803
|
+
validation: { state: "invalid", reason: "No auth method is configured yet" }
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
if (isEmptyJar(jar)) {
|
|
807
|
+
return {
|
|
808
|
+
metadata,
|
|
809
|
+
validation: { state: "invalid", reason: "No local session cookies are present" }
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
return { metadata, validation: await this.validator.validate(jar) };
|
|
813
|
+
}
|
|
814
|
+
async refresh(interactive) {
|
|
815
|
+
await this.recover(interactive);
|
|
816
|
+
}
|
|
817
|
+
async logout() {
|
|
818
|
+
await this.awaitInFlightRecovery();
|
|
819
|
+
await this.cookies.clear();
|
|
820
|
+
await this.metadata.clear();
|
|
821
|
+
await this.credentials.clear();
|
|
822
|
+
this.generation += 1;
|
|
823
|
+
await this.removeBrowserProfile();
|
|
824
|
+
}
|
|
825
|
+
async awaitInFlightRecovery() {
|
|
826
|
+
const current = this.recovery;
|
|
827
|
+
if (current === void 0) return;
|
|
828
|
+
try {
|
|
829
|
+
await current;
|
|
830
|
+
} catch {
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
async removeBrowserProfile() {
|
|
834
|
+
if (!isDedicatedBrowserProfile(this.browserProfile)) {
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
await rm(this.browserProfile, { recursive: true, force: true });
|
|
838
|
+
}
|
|
839
|
+
ensureJar() {
|
|
840
|
+
this.recovery ??= this.recover(false).finally(() => {
|
|
841
|
+
this.recovery = void 0;
|
|
842
|
+
});
|
|
843
|
+
return this.recovery;
|
|
844
|
+
}
|
|
845
|
+
async recover(interactive) {
|
|
846
|
+
const generation = this.generation;
|
|
847
|
+
const jar = await this.cookies.load();
|
|
848
|
+
const metadata = await this.metadata.load();
|
|
849
|
+
if (!isEmptyJar(jar)) {
|
|
850
|
+
const validation = await this.validator.validate(jar);
|
|
851
|
+
if (validation.state === "valid") return jar;
|
|
852
|
+
if (validation.state === "unreachable") {
|
|
853
|
+
throw networkError("Unable to reach Lanhu; the existing login data was kept intact");
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
if (metadata === void 0) {
|
|
857
|
+
throw authRequiredError(
|
|
858
|
+
"Not logged in to Lanhu yet",
|
|
859
|
+
"Run `dt auth login lanhu` to authenticate first"
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
let result;
|
|
863
|
+
if (metadata.method === "password") {
|
|
864
|
+
if (metadata.account === void 0) {
|
|
865
|
+
throw storageConfigError("Password login metadata is missing the account");
|
|
866
|
+
}
|
|
867
|
+
const password2 = await this.credentials.load(metadata.account);
|
|
868
|
+
if (password2 === void 0) {
|
|
869
|
+
throw authRequiredError(
|
|
870
|
+
"No stored password is available for silent re-login",
|
|
871
|
+
"Run `dt auth login lanhu --method password` to store the password"
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
result = await this.flows.password({ account: metadata.account, password: password2 });
|
|
875
|
+
} else {
|
|
876
|
+
if (metadata.browser === void 0) {
|
|
877
|
+
throw storageConfigError("Browser login metadata is missing the browser source");
|
|
878
|
+
}
|
|
879
|
+
const options = {
|
|
880
|
+
browser: metadata.browser,
|
|
881
|
+
forceLogin: false,
|
|
882
|
+
timeoutMs: BROWSER_RELOGIN_TIMEOUT_MS,
|
|
883
|
+
interactive
|
|
884
|
+
};
|
|
885
|
+
if (metadata.profile !== void 0) {
|
|
886
|
+
options.profile = metadata.profile;
|
|
887
|
+
}
|
|
888
|
+
result = await this.flows.browser(options);
|
|
889
|
+
}
|
|
890
|
+
return (await this.persist(result, generation)).jar;
|
|
891
|
+
}
|
|
892
|
+
async persist(result, startGeneration) {
|
|
893
|
+
if (startGeneration !== void 0 && this.generation !== startGeneration) {
|
|
894
|
+
return result;
|
|
895
|
+
}
|
|
896
|
+
if (result.validation.state !== "valid") {
|
|
897
|
+
throw new LanhuError(
|
|
898
|
+
"PROTOCOL_ERROR",
|
|
899
|
+
"Refusing to persist a session that was not validated as valid"
|
|
900
|
+
);
|
|
901
|
+
}
|
|
902
|
+
const previousJar = await this.cookies.load();
|
|
903
|
+
try {
|
|
904
|
+
await this.cookies.save(result.jar);
|
|
905
|
+
await this.metadata.save(result.metadata);
|
|
906
|
+
} catch {
|
|
907
|
+
await this.restorePreviousCookieJar(previousJar);
|
|
908
|
+
throw new LanhuError(
|
|
909
|
+
"STORAGE_ERROR",
|
|
910
|
+
"Unable to persist the authenticated session locally"
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
return result;
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Best-effort rollback: if metadata persistence fails after cookies were
|
|
917
|
+
* saved, restore the prior cookie jar so cookies and metadata never diverge.
|
|
918
|
+
* If the restore itself fails the original STORAGE_ERROR is preserved.
|
|
919
|
+
*/
|
|
920
|
+
async restorePreviousCookieJar(previousJar) {
|
|
921
|
+
try {
|
|
922
|
+
await this.cookies.save(previousJar);
|
|
923
|
+
} catch {
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
// src/adapters/lanhu/auth/browser/chrome.ts
|
|
929
|
+
import { spawn as nodeSpawn } from "child_process";
|
|
930
|
+
import { existsSync } from "fs";
|
|
931
|
+
import { mkdir, readFile as fsReadFile, rm as rm2, stat } from "fs/promises";
|
|
932
|
+
import { join, resolve, win32 as pathWin32 } from "path";
|
|
933
|
+
|
|
934
|
+
// src/adapters/lanhu/auth/browser/cdp.ts
|
|
935
|
+
var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
|
|
936
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
|
|
937
|
+
var WS_OPEN = 1;
|
|
938
|
+
var CONNECT_TIMEOUT_HINT = "Chrome did not expose an automation endpoint in time. Retry, or run in your own terminal.";
|
|
939
|
+
var WEBSOCKET_REQUIRED_HINT = "A WebSocket transport is required to automate the browser. Run this command in your own terminal with Node.js >= 22 (which bundles a WebSocket), or ensure the `ws` package is installed.";
|
|
940
|
+
async function createCdpSocketConstructor(deps = {}) {
|
|
941
|
+
let globalCtor;
|
|
942
|
+
if (Object.prototype.hasOwnProperty.call(deps, "globalWebSocket")) {
|
|
943
|
+
globalCtor = deps.globalWebSocket;
|
|
944
|
+
} else {
|
|
945
|
+
globalCtor = globalThis.WebSocket;
|
|
946
|
+
}
|
|
947
|
+
if (globalCtor !== void 0 && typeof globalCtor === "function") return globalCtor;
|
|
948
|
+
const loadWs = deps.loadWs ?? (() => import("ws"));
|
|
949
|
+
let wsModule;
|
|
950
|
+
try {
|
|
951
|
+
wsModule = await loadWs();
|
|
952
|
+
} catch {
|
|
953
|
+
wsModule = void 0;
|
|
954
|
+
}
|
|
955
|
+
if (wsModule !== void 0 && typeof wsModule.WebSocket === "function") {
|
|
956
|
+
return wsModule.WebSocket;
|
|
957
|
+
}
|
|
958
|
+
throw new LanhuError(
|
|
959
|
+
"BROWSER_NOT_FOUND",
|
|
960
|
+
"A WebSocket transport is required to automate the browser",
|
|
961
|
+
WEBSOCKET_REQUIRED_HINT
|
|
962
|
+
);
|
|
963
|
+
}
|
|
964
|
+
function browserError(message, hint) {
|
|
965
|
+
return new LanhuError("BROWSER_TIMEOUT", message, hint);
|
|
966
|
+
}
|
|
967
|
+
function describeProtocolError(error) {
|
|
968
|
+
const code = typeof error === "object" && error !== null ? Reflect.get(error, "code") : void 0;
|
|
969
|
+
return typeof code === "number" ? `The browser automation protocol rejected the request (code ${code})` : "The browser automation protocol rejected the request";
|
|
970
|
+
}
|
|
971
|
+
var CdpClient = class _CdpClient {
|
|
972
|
+
socket;
|
|
973
|
+
pending = /* @__PURE__ */ new Map();
|
|
974
|
+
sequence = 0;
|
|
975
|
+
closed = false;
|
|
976
|
+
constructor(socket) {
|
|
977
|
+
this.socket = socket;
|
|
978
|
+
socket.onmessage = (event) => this.handleMessage(event);
|
|
979
|
+
socket.onclose = () => this.rejectAll("The connection to the browser closed");
|
|
980
|
+
socket.onerror = () => this.rejectAll("The connection to the browser errored");
|
|
981
|
+
}
|
|
982
|
+
static async connect(url, timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS, messenger, ctorDeps = {}) {
|
|
983
|
+
const ctor = messenger !== void 0 ? messenger : await createCdpSocketConstructor(ctorDeps);
|
|
984
|
+
return await new Promise((resolve2, reject) => {
|
|
985
|
+
let settled = false;
|
|
986
|
+
let socket;
|
|
987
|
+
let timer;
|
|
988
|
+
const fail = (error) => {
|
|
989
|
+
if (settled) return;
|
|
990
|
+
settled = true;
|
|
991
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
992
|
+
try {
|
|
993
|
+
socket.close();
|
|
994
|
+
} catch {
|
|
995
|
+
}
|
|
996
|
+
reject(error);
|
|
997
|
+
};
|
|
998
|
+
try {
|
|
999
|
+
socket = new ctor(url);
|
|
1000
|
+
} catch {
|
|
1001
|
+
reject(
|
|
1002
|
+
new LanhuError(
|
|
1003
|
+
"BROWSER_NOT_FOUND",
|
|
1004
|
+
"Unable to open a browser automation endpoint",
|
|
1005
|
+
CONNECT_TIMEOUT_HINT
|
|
1006
|
+
)
|
|
1007
|
+
);
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
timer = setTimeout(() => {
|
|
1011
|
+
fail(
|
|
1012
|
+
new LanhuError(
|
|
1013
|
+
"BROWSER_TIMEOUT",
|
|
1014
|
+
"Timed out while connecting to the browser automation endpoint",
|
|
1015
|
+
CONNECT_TIMEOUT_HINT
|
|
1016
|
+
)
|
|
1017
|
+
);
|
|
1018
|
+
}, timeoutMs);
|
|
1019
|
+
socket.onopen = () => {
|
|
1020
|
+
if (settled) return;
|
|
1021
|
+
settled = true;
|
|
1022
|
+
clearTimeout(timer);
|
|
1023
|
+
resolve2(new _CdpClient(socket));
|
|
1024
|
+
};
|
|
1025
|
+
socket.onerror = () => {
|
|
1026
|
+
fail(
|
|
1027
|
+
new LanhuError(
|
|
1028
|
+
"BROWSER_NOT_FOUND",
|
|
1029
|
+
"The browser automation endpoint is not reachable",
|
|
1030
|
+
CONNECT_TIMEOUT_HINT
|
|
1031
|
+
)
|
|
1032
|
+
);
|
|
1033
|
+
};
|
|
1034
|
+
socket.onclose = () => {
|
|
1035
|
+
fail(
|
|
1036
|
+
new LanhuError(
|
|
1037
|
+
"BROWSER_NOT_FOUND",
|
|
1038
|
+
"The browser automation endpoint closed before connecting",
|
|
1039
|
+
CONNECT_TIMEOUT_HINT
|
|
1040
|
+
)
|
|
1041
|
+
);
|
|
1042
|
+
};
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
send(method, params = {}, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
|
|
1046
|
+
if (this.closed) {
|
|
1047
|
+
return Promise.reject(browserError("The connection to the browser is already closed"));
|
|
1048
|
+
}
|
|
1049
|
+
if (this.socket.readyState !== void 0 && this.socket.readyState !== WS_OPEN) {
|
|
1050
|
+
return Promise.reject(
|
|
1051
|
+
new LanhuError(
|
|
1052
|
+
"PROTOCOL_ERROR",
|
|
1053
|
+
"The connection to the browser is not open",
|
|
1054
|
+
CONNECT_TIMEOUT_HINT
|
|
1055
|
+
)
|
|
1056
|
+
);
|
|
1057
|
+
}
|
|
1058
|
+
const id = ++this.sequence;
|
|
1059
|
+
return new Promise((resolve2, reject) => {
|
|
1060
|
+
const timer = setTimeout(() => {
|
|
1061
|
+
this.pending.delete(id);
|
|
1062
|
+
reject(
|
|
1063
|
+
new LanhuError(
|
|
1064
|
+
"BROWSER_TIMEOUT",
|
|
1065
|
+
`The browser did not respond to ${method} in time`,
|
|
1066
|
+
CONNECT_TIMEOUT_HINT
|
|
1067
|
+
)
|
|
1068
|
+
);
|
|
1069
|
+
}, timeoutMs);
|
|
1070
|
+
this.pending.set(id, {
|
|
1071
|
+
resolve: (value) => resolve2(value),
|
|
1072
|
+
reject,
|
|
1073
|
+
timer
|
|
1074
|
+
});
|
|
1075
|
+
this.socket.send(JSON.stringify({ id, method, params }));
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
handleMessage(event) {
|
|
1079
|
+
let parsed;
|
|
1080
|
+
try {
|
|
1081
|
+
parsed = JSON.parse(event.data);
|
|
1082
|
+
} catch {
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
1085
|
+
if (typeof parsed !== "object" || parsed === null) return;
|
|
1086
|
+
const id = Reflect.get(parsed, "id");
|
|
1087
|
+
if (typeof id !== "number") return;
|
|
1088
|
+
const pending = this.pending.get(id);
|
|
1089
|
+
if (pending === void 0) return;
|
|
1090
|
+
this.pending.delete(id);
|
|
1091
|
+
clearTimeout(pending.timer);
|
|
1092
|
+
const error = Reflect.get(parsed, "error");
|
|
1093
|
+
if (error !== void 0 && error !== null) {
|
|
1094
|
+
pending.reject(
|
|
1095
|
+
new LanhuError(
|
|
1096
|
+
"PROTOCOL_ERROR",
|
|
1097
|
+
describeProtocolError(error),
|
|
1098
|
+
"Chrome returned an unexpected automation protocol response"
|
|
1099
|
+
)
|
|
1100
|
+
);
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
pending.resolve(Reflect.get(parsed, "result"));
|
|
1104
|
+
}
|
|
1105
|
+
close() {
|
|
1106
|
+
if (this.closed) return;
|
|
1107
|
+
this.closed = true;
|
|
1108
|
+
this.rejectAll("The connection to the browser was closed");
|
|
1109
|
+
try {
|
|
1110
|
+
this.socket.close();
|
|
1111
|
+
} catch {
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
rejectAll(message) {
|
|
1115
|
+
for (const [id, pending] of this.pending) {
|
|
1116
|
+
this.pending.delete(id);
|
|
1117
|
+
clearTimeout(pending.timer);
|
|
1118
|
+
pending.reject(browserError(message));
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
|
|
1123
|
+
// src/adapters/lanhu/auth/browser/chrome.ts
|
|
1124
|
+
var DARWIN_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
|
|
1125
|
+
var DARWIN_CANARY = "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary";
|
|
1126
|
+
var LINUX_NAMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
|
|
1127
|
+
var LANHU_URL = "https://lanhuapp.com/web/";
|
|
1128
|
+
var PORT_FILE = "DevToolsActivePort";
|
|
1129
|
+
var PORT_FILE_TIMEOUT_MS = 2e4;
|
|
1130
|
+
var REUSE_PROBE_TIMEOUT_MS = 3e3;
|
|
1131
|
+
var INSTALL_HINT = "Install Google Chrome so Lanhu can open a temporary, isolated browser window for login.";
|
|
1132
|
+
var PORT_FILE_HINT = "Chrome did not expose its debugging port. It may have exited immediately or been blocked.";
|
|
1133
|
+
var defaultAccess = (path) => existsSync(path);
|
|
1134
|
+
function chromeCandidates(platform, env) {
|
|
1135
|
+
if (platform === "darwin") {
|
|
1136
|
+
return [DARWIN_CHROME, DARWIN_CANARY];
|
|
1137
|
+
}
|
|
1138
|
+
if (platform === "win32") {
|
|
1139
|
+
const programFiles = env.PROGRAMFILES;
|
|
1140
|
+
const programFilesX86 = env["PROGRAMFILES(X86)"];
|
|
1141
|
+
const localAppData = env.LOCALAPPDATA;
|
|
1142
|
+
const candidates2 = [];
|
|
1143
|
+
if (programFiles !== void 0) {
|
|
1144
|
+
candidates2.push(pathWin32.join(programFiles, "Google", "Chrome", "Application", "chrome.exe"));
|
|
1145
|
+
}
|
|
1146
|
+
if (programFilesX86 !== void 0) {
|
|
1147
|
+
candidates2.push(
|
|
1148
|
+
pathWin32.join(programFilesX86, "Google", "Chrome", "Application", "chrome.exe")
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
if (localAppData !== void 0) {
|
|
1152
|
+
candidates2.push(
|
|
1153
|
+
pathWin32.join(localAppData, "Google", "Chrome", "Application", "chrome.exe")
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
return candidates2;
|
|
1157
|
+
}
|
|
1158
|
+
const path = env.PATH ?? "";
|
|
1159
|
+
const dirs = path.split(requirePathDelimiter(platform)).map((dir) => dir.trim()).filter((dir) => dir !== "");
|
|
1160
|
+
const candidates = [];
|
|
1161
|
+
for (const name of LINUX_NAMES) {
|
|
1162
|
+
for (const dir of dirs) {
|
|
1163
|
+
candidates.push(resolve(dir, name));
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
return candidates;
|
|
1167
|
+
}
|
|
1168
|
+
function requirePathDelimiter(platform) {
|
|
1169
|
+
return platform === "win32" ? ";" : ":";
|
|
1170
|
+
}
|
|
1171
|
+
function findChrome(dependencies = {}) {
|
|
1172
|
+
const platform = dependencies.platform ?? process.platform;
|
|
1173
|
+
const env = dependencies.env ?? process.env;
|
|
1174
|
+
const access = dependencies.access ?? defaultAccess;
|
|
1175
|
+
for (const candidate of chromeCandidates(platform, env)) {
|
|
1176
|
+
if (access(candidate)) return candidate;
|
|
1177
|
+
}
|
|
1178
|
+
throw new LanhuError(
|
|
1179
|
+
"BROWSER_NOT_FOUND",
|
|
1180
|
+
"Google Chrome does not appear to be installed",
|
|
1181
|
+
INSTALL_HINT
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1185
|
+
async function waitForFile(path, timeoutMs, dependencies = {}) {
|
|
1186
|
+
const sleep = dependencies.sleep ?? defaultSleep;
|
|
1187
|
+
const statFile = dependencies.statFile ?? stat;
|
|
1188
|
+
const deadline = Date.now() + timeoutMs;
|
|
1189
|
+
for (; ; ) {
|
|
1190
|
+
try {
|
|
1191
|
+
await statFile(path);
|
|
1192
|
+
return;
|
|
1193
|
+
} catch {
|
|
1194
|
+
if (Date.now() >= deadline) {
|
|
1195
|
+
throw new LanhuError(
|
|
1196
|
+
"BROWSER_NOT_FOUND",
|
|
1197
|
+
"Timed out waiting for Chrome to expose its debugging port",
|
|
1198
|
+
PORT_FILE_HINT
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
await sleep(50);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
function awaitPortOrExit(waitForPort, child, busyHint) {
|
|
1206
|
+
return new Promise((resolve2, reject) => {
|
|
1207
|
+
let settled = false;
|
|
1208
|
+
const finish = (fn) => {
|
|
1209
|
+
if (settled) return;
|
|
1210
|
+
settled = true;
|
|
1211
|
+
fn();
|
|
1212
|
+
};
|
|
1213
|
+
const onExit = () => {
|
|
1214
|
+
finish(
|
|
1215
|
+
() => reject(
|
|
1216
|
+
new LanhuError(
|
|
1217
|
+
"BROWSER_NOT_FOUND",
|
|
1218
|
+
"Chrome exited before exposing its debugging port",
|
|
1219
|
+
busyHint
|
|
1220
|
+
)
|
|
1221
|
+
)
|
|
1222
|
+
);
|
|
1223
|
+
};
|
|
1224
|
+
const onSpawnError = () => {
|
|
1225
|
+
finish(
|
|
1226
|
+
() => reject(
|
|
1227
|
+
new LanhuError("BROWSER_NOT_FOUND", "Chrome could not be started", busyHint)
|
|
1228
|
+
)
|
|
1229
|
+
);
|
|
1230
|
+
};
|
|
1231
|
+
child.once("exit", onExit);
|
|
1232
|
+
child.once("error", onSpawnError);
|
|
1233
|
+
waitForPort.then(
|
|
1234
|
+
() => finish(() => resolve2()),
|
|
1235
|
+
(error) => {
|
|
1236
|
+
if (error instanceof LanhuError && error.code === "BROWSER_TIMEOUT") {
|
|
1237
|
+
finish(
|
|
1238
|
+
() => reject(
|
|
1239
|
+
new LanhuError(
|
|
1240
|
+
"BROWSER_NOT_FOUND",
|
|
1241
|
+
"Timed out waiting for Chrome to expose its debugging port",
|
|
1242
|
+
busyHint
|
|
1243
|
+
)
|
|
1244
|
+
)
|
|
1245
|
+
);
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
finish(() => reject(error));
|
|
1249
|
+
}
|
|
1250
|
+
);
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
function parsePortFile(content) {
|
|
1254
|
+
const lines = content.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
|
|
1255
|
+
const port = Number(lines[0]);
|
|
1256
|
+
const wsPath = lines[1];
|
|
1257
|
+
if (!Number.isInteger(port) || port <= 0 || !Number.isSafeInteger(port)) return void 0;
|
|
1258
|
+
if (typeof wsPath !== "string" || !wsPath.startsWith("/devtools/browser/")) return void 0;
|
|
1259
|
+
return { port, wsPath };
|
|
1260
|
+
}
|
|
1261
|
+
function passiveChild() {
|
|
1262
|
+
return { pid: void 0, on: () => {
|
|
1263
|
+
}, once: () => {
|
|
1264
|
+
}, kill: () => true };
|
|
1265
|
+
}
|
|
1266
|
+
async function tryReuseSession(connect, url) {
|
|
1267
|
+
let cdp;
|
|
1268
|
+
try {
|
|
1269
|
+
cdp = await connect(url, REUSE_PROBE_TIMEOUT_MS);
|
|
1270
|
+
await cdp.send("Browser.getVersion", {}, REUSE_PROBE_TIMEOUT_MS);
|
|
1271
|
+
const session = cdp;
|
|
1272
|
+
return {
|
|
1273
|
+
cdp: session,
|
|
1274
|
+
close: async () => {
|
|
1275
|
+
try {
|
|
1276
|
+
session.close();
|
|
1277
|
+
} catch {
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
} catch {
|
|
1282
|
+
if (cdp !== void 0) {
|
|
1283
|
+
try {
|
|
1284
|
+
cdp.close();
|
|
1285
|
+
} catch {
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
return void 0;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
async function launchIsolatedChrome(dependencies) {
|
|
1292
|
+
const profileDir = dependencies.profileDir;
|
|
1293
|
+
const portFilePath = join(profileDir, PORT_FILE);
|
|
1294
|
+
const findChromeImpl = dependencies.findChromeImpl ?? (() => findChrome());
|
|
1295
|
+
const spawnChild = dependencies.spawn ?? nodeSpawn;
|
|
1296
|
+
const readTextFile = dependencies.readFile ?? ((file) => fsReadFile(file, "utf8"));
|
|
1297
|
+
const remove = dependencies.rm ?? rm2;
|
|
1298
|
+
const makeDir = dependencies.mkdir ?? mkdir;
|
|
1299
|
+
const connect = dependencies.connect ?? ((url) => CdpClient.connect(url));
|
|
1300
|
+
const customSleep = dependencies.sleep;
|
|
1301
|
+
const portWait = dependencies.waitForFile ?? ((path, timeoutMs) => waitForFile(
|
|
1302
|
+
path,
|
|
1303
|
+
timeoutMs,
|
|
1304
|
+
customSleep === void 0 ? {} : { sleep: customSleep }
|
|
1305
|
+
));
|
|
1306
|
+
let child;
|
|
1307
|
+
let exited = false;
|
|
1308
|
+
let preExisting;
|
|
1309
|
+
try {
|
|
1310
|
+
preExisting = await readTextFile(portFilePath, "utf8");
|
|
1311
|
+
} catch {
|
|
1312
|
+
preExisting = void 0;
|
|
1313
|
+
}
|
|
1314
|
+
if (preExisting !== void 0) {
|
|
1315
|
+
const parsed = parsePortFile(preExisting);
|
|
1316
|
+
if (parsed !== void 0) {
|
|
1317
|
+
const probeUrl = `ws://127.0.0.1:${parsed.port}${parsed.wsPath}`;
|
|
1318
|
+
const reused = await tryReuseSession(connect, probeUrl);
|
|
1319
|
+
if (reused !== void 0) {
|
|
1320
|
+
return {
|
|
1321
|
+
child: passiveChild(),
|
|
1322
|
+
cdp: reused.cdp,
|
|
1323
|
+
close: reused.close
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
const busyHint = `\u8BF7\u5148\u5173\u95ED\u4E4B\u524D\u6253\u5F00\u7684\u72EC\u7ACB\u767B\u5F55\u7A97\u53E3\uFF08${profileDir}\uFF09\u540E\u91CD\u8BD5\uFF0C\u5426\u5219\u65B0\u8FDB\u7A0B\u53EF\u80FD\u56E0\u65E7\u5B9E\u4F8B\u5360\u7528\u8BE5\u76EE\u5F55\u800C\u7ACB\u5373\u9000\u51FA\u3002${PORT_FILE_HINT}`;
|
|
1329
|
+
try {
|
|
1330
|
+
await remove(portFilePath, { force: true });
|
|
1331
|
+
await makeDir(profileDir, { recursive: true, mode: 448 });
|
|
1332
|
+
const executable = findChromeImpl();
|
|
1333
|
+
child = spawnChild(executable, [
|
|
1334
|
+
`--user-data-dir=${profileDir}`,
|
|
1335
|
+
"--remote-debugging-port=0",
|
|
1336
|
+
"--no-first-run",
|
|
1337
|
+
"--no-default-browser-check",
|
|
1338
|
+
"--new-window",
|
|
1339
|
+
LANHU_URL
|
|
1340
|
+
], { stdio: "ignore" });
|
|
1341
|
+
const started = child;
|
|
1342
|
+
started.on("exit", () => {
|
|
1343
|
+
exited = true;
|
|
1344
|
+
});
|
|
1345
|
+
started.on("error", () => {
|
|
1346
|
+
});
|
|
1347
|
+
await awaitPortOrExit(portWait(portFilePath, PORT_FILE_TIMEOUT_MS), started, busyHint);
|
|
1348
|
+
if (exited) {
|
|
1349
|
+
started.kill();
|
|
1350
|
+
throw new LanhuError(
|
|
1351
|
+
"BROWSER_NOT_FOUND",
|
|
1352
|
+
"Chrome exited before exposing its debugging port",
|
|
1353
|
+
busyHint
|
|
1354
|
+
);
|
|
1355
|
+
}
|
|
1356
|
+
const content = await readTextFile(portFilePath, "utf8");
|
|
1357
|
+
const parsed = parsePortFile(content);
|
|
1358
|
+
if (parsed === void 0) {
|
|
1359
|
+
started.kill();
|
|
1360
|
+
throw new LanhuError(
|
|
1361
|
+
"BROWSER_NOT_FOUND",
|
|
1362
|
+
"Chrome returned an invalid debugging endpoint",
|
|
1363
|
+
busyHint
|
|
1364
|
+
);
|
|
1365
|
+
}
|
|
1366
|
+
const { port, wsPath } = parsed;
|
|
1367
|
+
const cdp = await connect(`ws://127.0.0.1:${port}${wsPath}`);
|
|
1368
|
+
return {
|
|
1369
|
+
child: started,
|
|
1370
|
+
cdp,
|
|
1371
|
+
close: async () => {
|
|
1372
|
+
try {
|
|
1373
|
+
await cdp.send("Browser.close", {}, 3e3);
|
|
1374
|
+
} catch {
|
|
1375
|
+
}
|
|
1376
|
+
try {
|
|
1377
|
+
cdp.close();
|
|
1378
|
+
} catch {
|
|
1379
|
+
}
|
|
1380
|
+
if (!exited) {
|
|
1381
|
+
try {
|
|
1382
|
+
started.kill();
|
|
1383
|
+
} catch {
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1388
|
+
} catch (error) {
|
|
1389
|
+
if (child !== void 0) {
|
|
1390
|
+
try {
|
|
1391
|
+
child.kill();
|
|
1392
|
+
} catch {
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
if (error instanceof LanhuError) throw error;
|
|
1396
|
+
throw new LanhuError(
|
|
1397
|
+
"BROWSER_NOT_FOUND",
|
|
1398
|
+
"Unable to launch an isolated Chrome window",
|
|
1399
|
+
busyHint
|
|
1400
|
+
);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// src/adapters/lanhu/auth/browser/existing-browser.ts
|
|
1405
|
+
import { readFile } from "fs/promises";
|
|
1406
|
+
import { homedir } from "os";
|
|
1407
|
+
import { join as join2 } from "path";
|
|
1408
|
+
import { Cookie, CookieJar } from "tough-cookie";
|
|
1409
|
+
var LANHU_ORIGIN = "https://lanhuapp.com/";
|
|
1410
|
+
var PERMISSION_HINT = "Run this command in your own terminal and allow browser Keychain, Safe Storage, or keyring access when prompted.";
|
|
1411
|
+
var BLOCKED_ERROR_PATTERN = /permission denied|access denied|operation not permitted|interaction not allowed|interaction is not allowed|failed to read macOS keychain|cancelled the password prompt operation|canceled the password prompt|\bEPERM\b|\bEACCES\b/i;
|
|
1412
|
+
var BROWSER_NOT_FOUND_PATTERN = /browser.*(?:not found|not installed)|(?:not found|not installed).*browser|ENOENT|no such file or directory/i;
|
|
1413
|
+
var BROWSERS = {
|
|
1414
|
+
chrome: { backend: "chrome", chromiumBrowser: "chrome", root: ["Google", "Chrome"] },
|
|
1415
|
+
edge: { backend: "edge", root: ["Microsoft Edge"] },
|
|
1416
|
+
brave: {
|
|
1417
|
+
backend: "chrome",
|
|
1418
|
+
chromiumBrowser: "brave",
|
|
1419
|
+
root: ["BraveSoftware", "Brave-Browser"]
|
|
1420
|
+
},
|
|
1421
|
+
arc: { backend: "chrome", chromiumBrowser: "arc", root: ["Arc", "User Data"] },
|
|
1422
|
+
chromium: { backend: "chrome", chromiumBrowser: "chromium", root: ["Chromium"] }
|
|
1423
|
+
};
|
|
1424
|
+
function cdpCookieToBrowser(cookie) {
|
|
1425
|
+
return {
|
|
1426
|
+
name: cookie.name,
|
|
1427
|
+
value: cookie.value,
|
|
1428
|
+
domain: cookie.domain,
|
|
1429
|
+
path: cookie.path,
|
|
1430
|
+
...typeof cookie.expires === "number" && cookie.expires > 0 ? { expirationDate: cookie.expires } : {},
|
|
1431
|
+
...cookie.secure === true ? { secure: true } : {},
|
|
1432
|
+
...cookie.httpOnly === true ? { httpOnly: true } : {},
|
|
1433
|
+
...typeof cookie.sameSite === "string" ? { sameSite: cookie.sameSite } : {},
|
|
1434
|
+
...cookie.hostOnly === true ? { hostOnly: true } : {}
|
|
1435
|
+
};
|
|
1436
|
+
}
|
|
1437
|
+
function definitionFor(browser) {
|
|
1438
|
+
if (typeof browser !== "string" || !Object.hasOwn(BROWSERS, browser)) {
|
|
1439
|
+
throw new LanhuError(
|
|
1440
|
+
"USAGE_ERROR",
|
|
1441
|
+
"Unsupported browser; choose chrome, edge, brave, arc, or chromium"
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
return BROWSERS[browser];
|
|
1445
|
+
}
|
|
1446
|
+
function nonemptyProfile(value) {
|
|
1447
|
+
if (typeof value !== "string") return void 0;
|
|
1448
|
+
const profile = value.trim();
|
|
1449
|
+
return profile === "" ? void 0 : profile;
|
|
1450
|
+
}
|
|
1451
|
+
function permissionDenied(message) {
|
|
1452
|
+
return new LanhuError("BROWSER_PERMISSION_DENIED", message, PERMISSION_HINT);
|
|
1453
|
+
}
|
|
1454
|
+
function hasErrorCode(error, code) {
|
|
1455
|
+
return typeof error === "object" && error !== null && Reflect.get(error, "code") === code;
|
|
1456
|
+
}
|
|
1457
|
+
function errorText(error) {
|
|
1458
|
+
if (typeof error === "string") return error;
|
|
1459
|
+
if (typeof error === "object" && error !== null) {
|
|
1460
|
+
return ["name", "message", "code"].map((property) => Reflect.get(error, property)).filter(
|
|
1461
|
+
(value) => typeof value === "string" || typeof value === "number"
|
|
1462
|
+
).join(" ");
|
|
1463
|
+
}
|
|
1464
|
+
return String(error);
|
|
1465
|
+
}
|
|
1466
|
+
function isBlockedError(error) {
|
|
1467
|
+
return BLOCKED_ERROR_PATTERN.test(errorText(error));
|
|
1468
|
+
}
|
|
1469
|
+
function domainFromUrl(value) {
|
|
1470
|
+
if (value === void 0) return void 0;
|
|
1471
|
+
try {
|
|
1472
|
+
return new URL(value).hostname;
|
|
1473
|
+
} catch {
|
|
1474
|
+
return void 0;
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
function fromSweetCookie(cookie) {
|
|
1478
|
+
return {
|
|
1479
|
+
name: cookie.name,
|
|
1480
|
+
value: cookie.value,
|
|
1481
|
+
domain: cookie.domain ?? domainFromUrl(cookie.url) ?? "lanhuapp.com",
|
|
1482
|
+
path: cookie.path ?? "/",
|
|
1483
|
+
...typeof cookie.expires === "number" ? { expirationDate: cookie.expires } : {},
|
|
1484
|
+
...typeof cookie.secure === "boolean" ? { secure: cookie.secure } : {},
|
|
1485
|
+
...typeof cookie.httpOnly === "boolean" ? { httpOnly: cookie.httpOnly } : {},
|
|
1486
|
+
...typeof cookie.sameSite === "string" ? { sameSite: cookie.sameSite } : {},
|
|
1487
|
+
...typeof cookie.hostOnly === "boolean" ? { hostOnly: cookie.hostOnly } : {}
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
async function resolveProfile(browser, explicitProfile, dependencies = {}) {
|
|
1491
|
+
const definition = definitionFor(browser);
|
|
1492
|
+
const selectedProfile = nonemptyProfile(explicitProfile);
|
|
1493
|
+
if (selectedProfile !== void 0) return selectedProfile;
|
|
1494
|
+
const platform = dependencies.platform ?? process.platform;
|
|
1495
|
+
if (platform !== "darwin") return void 0;
|
|
1496
|
+
const homeDir = dependencies.homeDir ?? homedir();
|
|
1497
|
+
const readTextFile = dependencies.readFile ?? ((file) => readFile(file, "utf8"));
|
|
1498
|
+
const localState = join2(
|
|
1499
|
+
homeDir,
|
|
1500
|
+
"Library",
|
|
1501
|
+
"Application Support",
|
|
1502
|
+
...definition.root,
|
|
1503
|
+
"Local State"
|
|
1504
|
+
);
|
|
1505
|
+
let serialized;
|
|
1506
|
+
try {
|
|
1507
|
+
serialized = await readTextFile(localState, "utf8");
|
|
1508
|
+
} catch (error) {
|
|
1509
|
+
if (hasErrorCode(error, "ENOENT") || hasErrorCode(error, "ENOTDIR")) return void 0;
|
|
1510
|
+
if (isBlockedError(error)) {
|
|
1511
|
+
throw permissionDenied("Access to browser profile metadata was denied");
|
|
1512
|
+
}
|
|
1513
|
+
throw new LanhuError("STORAGE_ERROR", "Unable to read browser profile metadata");
|
|
1514
|
+
}
|
|
1515
|
+
try {
|
|
1516
|
+
const value = JSON.parse(serialized);
|
|
1517
|
+
if (typeof value === "object" && value !== null && "profile" in value) {
|
|
1518
|
+
const profile = Reflect.get(value, "profile");
|
|
1519
|
+
if (typeof profile === "object" && profile !== null && "last_used" in profile) {
|
|
1520
|
+
return nonemptyProfile(Reflect.get(profile, "last_used")) ?? "Default";
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
} catch {
|
|
1524
|
+
return "Default";
|
|
1525
|
+
}
|
|
1526
|
+
return "Default";
|
|
1527
|
+
}
|
|
1528
|
+
var SweetCookieReader = class {
|
|
1529
|
+
loadSweetCookie;
|
|
1530
|
+
profileResolver;
|
|
1531
|
+
constructor(dependencies = {}) {
|
|
1532
|
+
this.loadSweetCookie = dependencies.loadSweetCookie ?? (() => import("@steipete/sweet-cookie"));
|
|
1533
|
+
this.profileResolver = dependencies.resolveProfile ?? resolveProfile;
|
|
1534
|
+
}
|
|
1535
|
+
async read(browser, explicitProfile) {
|
|
1536
|
+
const definition = definitionFor(browser);
|
|
1537
|
+
const profile = nonemptyProfile(await this.profileResolver(browser, explicitProfile));
|
|
1538
|
+
try {
|
|
1539
|
+
const { getCookies } = await this.loadSweetCookie();
|
|
1540
|
+
const result = await getCookies({
|
|
1541
|
+
url: LANHU_ORIGIN,
|
|
1542
|
+
browsers: [definition.backend],
|
|
1543
|
+
..."chromiumBrowser" in definition ? { chromiumBrowser: definition.chromiumBrowser } : {},
|
|
1544
|
+
...profile !== void 0 ? { profile } : {},
|
|
1545
|
+
mode: "first",
|
|
1546
|
+
timeoutMs: 3e4
|
|
1547
|
+
});
|
|
1548
|
+
if (BLOCKED_ERROR_PATTERN.test(result.warnings.join("; "))) {
|
|
1549
|
+
throw permissionDenied("The operating system or browser blocked cookie access");
|
|
1550
|
+
}
|
|
1551
|
+
return result.cookies.map(fromSweetCookie);
|
|
1552
|
+
} catch (error) {
|
|
1553
|
+
if (error instanceof LanhuError) throw error;
|
|
1554
|
+
if (isBlockedError(error)) {
|
|
1555
|
+
throw permissionDenied("The operating system or browser blocked cookie access");
|
|
1556
|
+
}
|
|
1557
|
+
if (BROWSER_NOT_FOUND_PATTERN.test(errorText(error))) {
|
|
1558
|
+
throw new LanhuError("BROWSER_NOT_FOUND", "The selected browser could not be found");
|
|
1559
|
+
}
|
|
1560
|
+
throw new LanhuError("STORAGE_ERROR", "Unable to read cookies from the selected browser");
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
function allowedDomain(value) {
|
|
1565
|
+
if (typeof value !== "string") return void 0;
|
|
1566
|
+
const withoutLeadingDot = value.trim().toLowerCase().replace(/^\./, "");
|
|
1567
|
+
if (withoutLeadingDot === "" || withoutLeadingDot.startsWith(".") || withoutLeadingDot.includes("..")) {
|
|
1568
|
+
return void 0;
|
|
1569
|
+
}
|
|
1570
|
+
if (withoutLeadingDot !== "lanhuapp.com" && !withoutLeadingDot.endsWith(".lanhuapp.com")) {
|
|
1571
|
+
return void 0;
|
|
1572
|
+
}
|
|
1573
|
+
return withoutLeadingDot;
|
|
1574
|
+
}
|
|
1575
|
+
function normalizedSameSite(value) {
|
|
1576
|
+
if (typeof value !== "string") return void 0;
|
|
1577
|
+
const sameSite = value.trim().toLowerCase();
|
|
1578
|
+
if (sameSite === "no_restriction") return "none";
|
|
1579
|
+
if (sameSite === "strict" || sameSite === "lax" || sameSite === "none") return sameSite;
|
|
1580
|
+
return void 0;
|
|
1581
|
+
}
|
|
1582
|
+
function toCookieJar(cookies) {
|
|
1583
|
+
const jar = new CookieJar();
|
|
1584
|
+
for (const entry of cookies) {
|
|
1585
|
+
try {
|
|
1586
|
+
if (typeof entry.name !== "string" || entry.name === "" || typeof entry.value !== "string" || typeof entry.path !== "string") {
|
|
1587
|
+
continue;
|
|
1588
|
+
}
|
|
1589
|
+
const domain = allowedDomain(entry.domain);
|
|
1590
|
+
const path = entry.path === "" ? "/" : entry.path;
|
|
1591
|
+
if (domain === void 0 || !path.startsWith("/")) continue;
|
|
1592
|
+
if (entry.expirationDate !== void 0 && (typeof entry.expirationDate !== "number" || !Number.isFinite(entry.expirationDate))) {
|
|
1593
|
+
continue;
|
|
1594
|
+
}
|
|
1595
|
+
const sameSite = normalizedSameSite(entry.sameSite);
|
|
1596
|
+
const cookie = new Cookie({
|
|
1597
|
+
key: entry.name,
|
|
1598
|
+
value: entry.value,
|
|
1599
|
+
domain,
|
|
1600
|
+
path,
|
|
1601
|
+
...entry.expirationDate !== void 0 && entry.expirationDate > 0 ? { expires: new Date(entry.expirationDate * 1e3) } : {},
|
|
1602
|
+
...typeof entry.secure === "boolean" ? { secure: entry.secure } : {},
|
|
1603
|
+
...typeof entry.httpOnly === "boolean" ? { httpOnly: entry.httpOnly } : {},
|
|
1604
|
+
...sameSite !== void 0 ? { sameSite } : {},
|
|
1605
|
+
...typeof entry.hostOnly === "boolean" ? { hostOnly: entry.hostOnly } : {}
|
|
1606
|
+
});
|
|
1607
|
+
jar.setCookieSync(cookie, `https://${domain}/`);
|
|
1608
|
+
} catch {
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
return jar;
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
// src/adapters/lanhu/auth/browser/login.ts
|
|
1615
|
+
var POLL_INTERVAL_MS = 2e3;
|
|
1616
|
+
var BROWSER_TIMEOUT_HINT = "Complete login in the opened browser window. The window closes automatically when the timeout is reached.";
|
|
1617
|
+
var asyncMs = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1618
|
+
function networkError2(action) {
|
|
1619
|
+
return new LanhuError("NETWORK_ERROR", `Unable to verify the Lanhu session ${action}`);
|
|
1620
|
+
}
|
|
1621
|
+
function authRequiredError2() {
|
|
1622
|
+
return new LanhuError(
|
|
1623
|
+
"AUTH_REQUIRED",
|
|
1624
|
+
"Lanhu browser login requires an interactive browser session"
|
|
1625
|
+
);
|
|
1626
|
+
}
|
|
1627
|
+
function cookieFingerprint(cookies) {
|
|
1628
|
+
return cookies.map(
|
|
1629
|
+
(cookie, index) => `${index}:${cookie.name}|${cookie.domain}|${cookie.path}|${cookie.value}`
|
|
1630
|
+
).join(";");
|
|
1631
|
+
}
|
|
1632
|
+
function hasSessionCookie(cookies) {
|
|
1633
|
+
return cookies.some(
|
|
1634
|
+
(cookie) => cookie.name === "session" || cookie.name === "user_token"
|
|
1635
|
+
);
|
|
1636
|
+
}
|
|
1637
|
+
function loginResult(jar, validation, options) {
|
|
1638
|
+
const metadata = {
|
|
1639
|
+
version: 1,
|
|
1640
|
+
method: "browser",
|
|
1641
|
+
browser: options.browser,
|
|
1642
|
+
lastLoginAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1643
|
+
};
|
|
1644
|
+
if (options.profile !== void 0) {
|
|
1645
|
+
metadata.profile = options.profile;
|
|
1646
|
+
}
|
|
1647
|
+
if (validation.account !== void 0) {
|
|
1648
|
+
metadata.account = validation.account;
|
|
1649
|
+
}
|
|
1650
|
+
return { jar, metadata, validation };
|
|
1651
|
+
}
|
|
1652
|
+
var BrowserLoginFlow = class {
|
|
1653
|
+
constructor(reader, validator, openChrome, profileDir, sleep = asyncMs) {
|
|
1654
|
+
this.reader = reader;
|
|
1655
|
+
this.validator = validator;
|
|
1656
|
+
this.openChrome = openChrome;
|
|
1657
|
+
this.profileDir = profileDir;
|
|
1658
|
+
this.sleep = sleep;
|
|
1659
|
+
}
|
|
1660
|
+
reader;
|
|
1661
|
+
validator;
|
|
1662
|
+
openChrome;
|
|
1663
|
+
profileDir;
|
|
1664
|
+
sleep;
|
|
1665
|
+
async login(options) {
|
|
1666
|
+
if (!options.forceLogin) {
|
|
1667
|
+
const existing = await this.reader.read(options.browser, options.profile);
|
|
1668
|
+
const jar = toCookieJar(existing);
|
|
1669
|
+
if (hasSessionCookie(existing)) {
|
|
1670
|
+
const validation = await this.validator.validate(jar);
|
|
1671
|
+
if (validation.state === "valid") {
|
|
1672
|
+
return loginResult(jar, validation, options);
|
|
1673
|
+
}
|
|
1674
|
+
if (validation.state === "unreachable") {
|
|
1675
|
+
throw networkError2("from existing cookies");
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
if (!options.interactive) {
|
|
1680
|
+
throw authRequiredError2();
|
|
1681
|
+
}
|
|
1682
|
+
const chrome = await this.openChrome(this.profileDir);
|
|
1683
|
+
try {
|
|
1684
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
1685
|
+
let lastFingerprint;
|
|
1686
|
+
for (; ; ) {
|
|
1687
|
+
const current = await chrome.cookies();
|
|
1688
|
+
const fingerprint = cookieFingerprint(current);
|
|
1689
|
+
if (fingerprint !== lastFingerprint) {
|
|
1690
|
+
lastFingerprint = fingerprint;
|
|
1691
|
+
if (hasSessionCookie(current)) {
|
|
1692
|
+
const jar = toCookieJar(current);
|
|
1693
|
+
const validation = await this.validator.validate(jar);
|
|
1694
|
+
if (validation.state === "valid") {
|
|
1695
|
+
return loginResult(jar, validation, options);
|
|
1696
|
+
}
|
|
1697
|
+
if (validation.state === "unreachable") {
|
|
1698
|
+
throw networkError2("from the browser");
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
if (Date.now() >= deadline) {
|
|
1703
|
+
throw new LanhuError(
|
|
1704
|
+
"BROWSER_TIMEOUT",
|
|
1705
|
+
"Timed out waiting for login in the browser",
|
|
1706
|
+
BROWSER_TIMEOUT_HINT
|
|
1707
|
+
);
|
|
1708
|
+
}
|
|
1709
|
+
await this.sleep(POLL_INTERVAL_MS);
|
|
1710
|
+
}
|
|
1711
|
+
} finally {
|
|
1712
|
+
await chrome.close();
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
};
|
|
1716
|
+
|
|
1717
|
+
// src/adapters/lanhu/auth/password/rsa.ts
|
|
1718
|
+
import { constants, publicEncrypt } from "crypto";
|
|
1719
|
+
function encryptPassword(password2, publicKey) {
|
|
1720
|
+
try {
|
|
1721
|
+
return publicEncrypt(
|
|
1722
|
+
{ key: publicKey, padding: constants.RSA_PKCS1_PADDING },
|
|
1723
|
+
Buffer.from(password2, "utf8")
|
|
1724
|
+
).toString("base64");
|
|
1725
|
+
} catch {
|
|
1726
|
+
throw new LanhuError("ENCRYPTION_FAILED", "Unable to encrypt the password with the public key");
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
// src/adapters/lanhu/auth/password/login.ts
|
|
1731
|
+
var BROWSER_LOGIN_HINT = "Complete the verification in your browser and try again";
|
|
1732
|
+
var VERIFICATION_PATTERN = /captcha|验证码|人机|risk|verify/i;
|
|
1733
|
+
var CREDENTIAL_PATTERN = /password|account|密码|账号/i;
|
|
1734
|
+
function isRecord(value) {
|
|
1735
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1736
|
+
}
|
|
1737
|
+
function isNonblankString(value) {
|
|
1738
|
+
return typeof value === "string" && value.trim() !== "";
|
|
1739
|
+
}
|
|
1740
|
+
function protocolError2(message) {
|
|
1741
|
+
return new LanhuError("PROTOCOL_ERROR", message);
|
|
1742
|
+
}
|
|
1743
|
+
function rejectionError(code, message) {
|
|
1744
|
+
const serverMessage = typeof message === "string" ? message : "";
|
|
1745
|
+
if (VERIFICATION_PATTERN.test(serverMessage)) {
|
|
1746
|
+
return new LanhuError(
|
|
1747
|
+
"VERIFICATION_REQUIRED",
|
|
1748
|
+
`Lanhu login requires verification (business code ${code})`,
|
|
1749
|
+
BROWSER_LOGIN_HINT
|
|
1750
|
+
);
|
|
1751
|
+
}
|
|
1752
|
+
if (CREDENTIAL_PATTERN.test(serverMessage)) {
|
|
1753
|
+
return new LanhuError(
|
|
1754
|
+
"INVALID_CREDENTIALS",
|
|
1755
|
+
`Lanhu rejected the account or password (business code ${code})`
|
|
1756
|
+
);
|
|
1757
|
+
}
|
|
1758
|
+
return new LanhuError(
|
|
1759
|
+
"LOGIN_REJECTED",
|
|
1760
|
+
`Lanhu rejected the login (business code ${code})`
|
|
1761
|
+
);
|
|
1762
|
+
}
|
|
1763
|
+
async function readLoginResponse(response) {
|
|
1764
|
+
try {
|
|
1765
|
+
return await response.json();
|
|
1766
|
+
} catch (error) {
|
|
1767
|
+
if (error instanceof SyntaxError) {
|
|
1768
|
+
throw protocolError2("Lanhu login returned malformed JSON");
|
|
1769
|
+
}
|
|
1770
|
+
throw error;
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
async function cancelResponseBody2(response) {
|
|
1774
|
+
try {
|
|
1775
|
+
await response.body?.cancel();
|
|
1776
|
+
} catch {
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
function loginHttpError(status) {
|
|
1780
|
+
if (status === 401 || status === 403) {
|
|
1781
|
+
return new LanhuError("INVALID_CREDENTIALS", `Lanhu passport login returned HTTP ${status}`);
|
|
1782
|
+
}
|
|
1783
|
+
if (status >= 500) {
|
|
1784
|
+
return new LanhuError("NETWORK_ERROR", `Lanhu passport login returned HTTP ${status}`);
|
|
1785
|
+
}
|
|
1786
|
+
return new LanhuError("LOGIN_REJECTED", `Lanhu passport login returned HTTP ${status}`);
|
|
1787
|
+
}
|
|
1788
|
+
function authHttpError(status) {
|
|
1789
|
+
if (status === 401 || status === 403) {
|
|
1790
|
+
return new LanhuError("AUTH_REQUIRED", `Lanhu auth returned HTTP ${status}`);
|
|
1791
|
+
}
|
|
1792
|
+
if (status >= 500) {
|
|
1793
|
+
return new LanhuError("NETWORK_ERROR", `Lanhu auth returned HTTP ${status}`);
|
|
1794
|
+
}
|
|
1795
|
+
return protocolError2(`Lanhu auth returned HTTP ${status}`);
|
|
1796
|
+
}
|
|
1797
|
+
function acceptedRedirectUri(value, origin) {
|
|
1798
|
+
if (!isNonblankString(value)) return `${origin}/web/`;
|
|
1799
|
+
let redirect;
|
|
1800
|
+
try {
|
|
1801
|
+
redirect = new URL(value);
|
|
1802
|
+
} catch {
|
|
1803
|
+
throw protocolError2("Lanhu login returned an invalid redirect URI");
|
|
1804
|
+
}
|
|
1805
|
+
if (redirect.protocol !== "https:" || redirect.origin !== new URL(origin).origin || redirect.username !== "" || redirect.password !== "") {
|
|
1806
|
+
throw protocolError2("Lanhu login returned an unsafe redirect URI");
|
|
1807
|
+
}
|
|
1808
|
+
return value;
|
|
1809
|
+
}
|
|
1810
|
+
var PasswordLoginFlow = class {
|
|
1811
|
+
constructor(keys, validator, jar, origin = "https://lanhuapp.com", request = requestWithCookies) {
|
|
1812
|
+
this.keys = keys;
|
|
1813
|
+
this.validator = validator;
|
|
1814
|
+
this.jar = jar;
|
|
1815
|
+
this.origin = origin;
|
|
1816
|
+
this.request = request;
|
|
1817
|
+
}
|
|
1818
|
+
keys;
|
|
1819
|
+
validator;
|
|
1820
|
+
jar;
|
|
1821
|
+
origin;
|
|
1822
|
+
request;
|
|
1823
|
+
async login({
|
|
1824
|
+
account,
|
|
1825
|
+
password: password2,
|
|
1826
|
+
extraAuthParams
|
|
1827
|
+
}) {
|
|
1828
|
+
const publicKey = await this.keys.get();
|
|
1829
|
+
const encryptedPassword = encryptPassword(password2, publicKey);
|
|
1830
|
+
try {
|
|
1831
|
+
const loginResponse = await this.request(
|
|
1832
|
+
`${this.origin}/api/passport/login`,
|
|
1833
|
+
{
|
|
1834
|
+
method: "POST",
|
|
1835
|
+
headers: {
|
|
1836
|
+
"Content-Type": "application/json;charset=UTF-8",
|
|
1837
|
+
Accept: "application/json",
|
|
1838
|
+
"User-From": this.origin
|
|
1839
|
+
},
|
|
1840
|
+
body: JSON.stringify({
|
|
1841
|
+
mobile_or_email: account,
|
|
1842
|
+
password: encryptedPassword
|
|
1843
|
+
})
|
|
1844
|
+
},
|
|
1845
|
+
this.jar
|
|
1846
|
+
);
|
|
1847
|
+
if (!loginResponse.ok) {
|
|
1848
|
+
await cancelResponseBody2(loginResponse);
|
|
1849
|
+
throw loginHttpError(loginResponse.status);
|
|
1850
|
+
}
|
|
1851
|
+
const body = await readLoginResponse(loginResponse);
|
|
1852
|
+
if (!isRecord(body) || typeof body.code !== "number" || !Number.isFinite(body.code)) {
|
|
1853
|
+
throw protocolError2("Lanhu login returned an invalid response schema");
|
|
1854
|
+
}
|
|
1855
|
+
if (body.code !== 0) {
|
|
1856
|
+
throw rejectionError(body.code, body.message);
|
|
1857
|
+
}
|
|
1858
|
+
if (!isRecord(body.data) || !isNonblankString(body.data.ticket)) {
|
|
1859
|
+
throw protocolError2("Lanhu login response is missing a valid ticket");
|
|
1860
|
+
}
|
|
1861
|
+
const ticket = body.data.ticket;
|
|
1862
|
+
const redirectUri = acceptedRedirectUri(
|
|
1863
|
+
`${this.origin}/dashboard/?action=login&corpId=null&action_type=password`,
|
|
1864
|
+
this.origin
|
|
1865
|
+
);
|
|
1866
|
+
const extras = extraAuthParams ?? {};
|
|
1867
|
+
const action = isNonblankString(extras.action) ? extras.action : "login";
|
|
1868
|
+
const actionType = isNonblankString(extras.action_type) ? extras.action_type : "password";
|
|
1869
|
+
const query = new URLSearchParams();
|
|
1870
|
+
query.append("request_from", "web");
|
|
1871
|
+
query.append("sso_ticket", ticket);
|
|
1872
|
+
query.append("redirect_uri", redirectUri);
|
|
1873
|
+
query.append("action", action);
|
|
1874
|
+
query.append("action_type", actionType);
|
|
1875
|
+
const reserved = /* @__PURE__ */ new Set([
|
|
1876
|
+
"request_from",
|
|
1877
|
+
"sso_ticket",
|
|
1878
|
+
"redirect_uri",
|
|
1879
|
+
"action",
|
|
1880
|
+
"action_type"
|
|
1881
|
+
]);
|
|
1882
|
+
for (const [key, value] of Object.entries(extras)) {
|
|
1883
|
+
if (!reserved.has(key) && isNonblankString(value)) query.append(key, value);
|
|
1884
|
+
}
|
|
1885
|
+
let authResponse;
|
|
1886
|
+
try {
|
|
1887
|
+
authResponse = await this.request(
|
|
1888
|
+
`${this.origin}/api/auth?${query.toString()}`,
|
|
1889
|
+
{ headers: { "User-From": this.origin } },
|
|
1890
|
+
this.jar,
|
|
1891
|
+
{ sameOriginRedirects: true }
|
|
1892
|
+
);
|
|
1893
|
+
if (!authResponse.ok) throw authHttpError(authResponse.status);
|
|
1894
|
+
} finally {
|
|
1895
|
+
if (authResponse !== void 0) await cancelResponseBody2(authResponse);
|
|
1896
|
+
}
|
|
1897
|
+
if (authResponse !== void 0 && authResponse.ok && authResponse.url !== "") {
|
|
1898
|
+
try {
|
|
1899
|
+
const finalUrl = new URL(authResponse.url);
|
|
1900
|
+
const ssoToken = finalUrl.searchParams.get("sso_token");
|
|
1901
|
+
if (isNonblankString(ssoToken)) {
|
|
1902
|
+
await this.jar.setCookie(
|
|
1903
|
+
`user_token=${ssoToken}; Path=/; Secure`,
|
|
1904
|
+
this.origin
|
|
1905
|
+
);
|
|
1906
|
+
}
|
|
1907
|
+
} catch {
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
const validation = await this.validator.validate(this.jar);
|
|
1911
|
+
if (validation.state === "invalid") {
|
|
1912
|
+
throw new LanhuError("AUTH_REQUIRED", "Lanhu session validation did not confirm login");
|
|
1913
|
+
}
|
|
1914
|
+
if (validation.state === "unreachable") {
|
|
1915
|
+
throw new LanhuError("NETWORK_ERROR", "Unable to verify the Lanhu session");
|
|
1916
|
+
}
|
|
1917
|
+
if (validation.state !== "valid") {
|
|
1918
|
+
throw protocolError2("Lanhu session validation returned an invalid state");
|
|
1919
|
+
}
|
|
1920
|
+
return {
|
|
1921
|
+
jar: this.jar,
|
|
1922
|
+
validation,
|
|
1923
|
+
metadata: {
|
|
1924
|
+
version: 1,
|
|
1925
|
+
method: "password",
|
|
1926
|
+
account,
|
|
1927
|
+
lastLoginAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1928
|
+
}
|
|
1929
|
+
};
|
|
1930
|
+
} catch (error) {
|
|
1931
|
+
if (error instanceof LanhuError) throw error;
|
|
1932
|
+
throw new LanhuError(
|
|
1933
|
+
"NETWORK_ERROR",
|
|
1934
|
+
"Unable to complete Lanhu login because a request failed"
|
|
1935
|
+
);
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
};
|
|
1939
|
+
|
|
1940
|
+
// src/adapters/lanhu/auth/password/public-key.ts
|
|
1941
|
+
import { createPublicKey } from "crypto";
|
|
1942
|
+
var BROWSER_LOGIN_HINT2 = "Log in to Lanhu in your browser and try again";
|
|
1943
|
+
var MAX_REDIRECTS = 5;
|
|
1944
|
+
var REDIRECT_STATUSES2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
1945
|
+
var PUBLIC_KEY_PATTERN = /-----BEGIN RSA PUBLIC KEY-----[\s\S]*?-----END RSA PUBLIC KEY-----/g;
|
|
1946
|
+
var SCRIPT_SOURCE_PATTERN = /<script\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)')[^>]*>|\bwindow\._(?:New|Old)JS\s*=\s*(\[[\s\S]*?\])/gi;
|
|
1947
|
+
function publicKeyNotFound(message = "Unable to locate the Lanhu RSA public key") {
|
|
1948
|
+
return new LanhuError("PUBLIC_KEY_NOT_FOUND", message, BROWSER_LOGIN_HINT2);
|
|
1949
|
+
}
|
|
1950
|
+
function addCandidate(candidates, candidate, base) {
|
|
1951
|
+
try {
|
|
1952
|
+
const url = candidate.startsWith("//") ? new URL(`https:${candidate}`) : new URL(candidate, base);
|
|
1953
|
+
candidates.push(url.href);
|
|
1954
|
+
} catch {
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
function discoverScriptUrls(html, base) {
|
|
1958
|
+
const candidates = [];
|
|
1959
|
+
for (const match of html.matchAll(SCRIPT_SOURCE_PATTERN)) {
|
|
1960
|
+
const scriptSource = match[1] ?? match[2];
|
|
1961
|
+
if (scriptSource !== void 0) {
|
|
1962
|
+
addCandidate(candidates, scriptSource, base);
|
|
1963
|
+
continue;
|
|
1964
|
+
}
|
|
1965
|
+
const arraySource = match[3];
|
|
1966
|
+
if (arraySource === void 0) continue;
|
|
1967
|
+
try {
|
|
1968
|
+
const values = JSON.parse(arraySource);
|
|
1969
|
+
if (!Array.isArray(values)) continue;
|
|
1970
|
+
for (const value of values) {
|
|
1971
|
+
if (typeof value === "string") addCandidate(candidates, value, base);
|
|
1972
|
+
}
|
|
1973
|
+
} catch {
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
return [...new Set(candidates)];
|
|
1977
|
+
}
|
|
1978
|
+
function extractPublicKey(bundle) {
|
|
1979
|
+
for (const [match] of bundle.matchAll(PUBLIC_KEY_PATTERN)) {
|
|
1980
|
+
const candidate = match.replaceAll(String.raw`\n`, "\n").replace(/\r\n?/g, "\n").trim();
|
|
1981
|
+
try {
|
|
1982
|
+
const key = createPublicKey(candidate);
|
|
1983
|
+
if (key.asymmetricKeyType === "rsa") return candidate;
|
|
1984
|
+
} catch {
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
return void 0;
|
|
1988
|
+
}
|
|
1989
|
+
function isAllowedScriptUrl(value) {
|
|
1990
|
+
try {
|
|
1991
|
+
const url = new URL(value);
|
|
1992
|
+
return url.protocol === "https:" && url.username === "" && url.password === "" && (url.port === "" || url.port === "443") && (url.hostname === "lanhuapp.com" || url.hostname.endsWith(".lanhuapp.com"));
|
|
1993
|
+
} catch {
|
|
1994
|
+
return false;
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
async function cancelResponseBody3(response) {
|
|
1998
|
+
if (response.body !== null) await response.body.cancel();
|
|
1999
|
+
}
|
|
2000
|
+
async function fetchWithRedirects(fetchImpl, initialUrl, timeoutMs) {
|
|
2001
|
+
if (!isAllowedScriptUrl(initialUrl)) throw new Error("URL is not allowed");
|
|
2002
|
+
let currentUrl = initialUrl;
|
|
2003
|
+
let redirectCount = 0;
|
|
2004
|
+
for (; ; ) {
|
|
2005
|
+
const response = await fetchImpl(currentUrl, {
|
|
2006
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
2007
|
+
redirect: "manual"
|
|
2008
|
+
});
|
|
2009
|
+
const location = REDIRECT_STATUSES2.has(response.status) ? response.headers.get("location") : null;
|
|
2010
|
+
if (location !== null) {
|
|
2011
|
+
await cancelResponseBody3(response);
|
|
2012
|
+
if (redirectCount >= MAX_REDIRECTS) throw new Error("Too many redirects");
|
|
2013
|
+
const target = new URL(location, currentUrl);
|
|
2014
|
+
if (!isAllowedScriptUrl(target.href)) throw new Error("Redirect URL is not allowed");
|
|
2015
|
+
currentUrl = target.href;
|
|
2016
|
+
redirectCount += 1;
|
|
2017
|
+
continue;
|
|
2018
|
+
}
|
|
2019
|
+
if (!isAllowedScriptUrl(response.url || currentUrl)) {
|
|
2020
|
+
await cancelResponseBody3(response);
|
|
2021
|
+
throw new Error("Final response URL is not allowed");
|
|
2022
|
+
}
|
|
2023
|
+
return response;
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
var BundlePublicKeyProvider = class {
|
|
2027
|
+
constructor(loginUrl = "https://lanhuapp.com/web/", fetchImpl = fetch) {
|
|
2028
|
+
this.loginUrl = loginUrl;
|
|
2029
|
+
this.fetchImpl = fetchImpl;
|
|
2030
|
+
}
|
|
2031
|
+
loginUrl;
|
|
2032
|
+
fetchImpl;
|
|
2033
|
+
cachedPublicKey;
|
|
2034
|
+
async get() {
|
|
2035
|
+
if (this.cachedPublicKey !== void 0) return this.cachedPublicKey;
|
|
2036
|
+
let response;
|
|
2037
|
+
try {
|
|
2038
|
+
response = await fetchWithRedirects(this.fetchImpl, this.loginUrl, 15e3);
|
|
2039
|
+
} catch {
|
|
2040
|
+
throw publicKeyNotFound();
|
|
2041
|
+
}
|
|
2042
|
+
if (!response.ok) {
|
|
2043
|
+
try {
|
|
2044
|
+
await cancelResponseBody3(response);
|
|
2045
|
+
} catch {
|
|
2046
|
+
}
|
|
2047
|
+
throw publicKeyNotFound(`Unable to locate the Lanhu RSA public key (HTTP ${response.status})`);
|
|
2048
|
+
}
|
|
2049
|
+
let html;
|
|
2050
|
+
try {
|
|
2051
|
+
html = await response.text();
|
|
2052
|
+
} catch {
|
|
2053
|
+
throw publicKeyNotFound();
|
|
2054
|
+
}
|
|
2055
|
+
for (const scriptUrl of discoverScriptUrls(html, this.loginUrl)) {
|
|
2056
|
+
if (!isAllowedScriptUrl(scriptUrl)) continue;
|
|
2057
|
+
try {
|
|
2058
|
+
const response2 = await fetchWithRedirects(this.fetchImpl, scriptUrl, 2e4);
|
|
2059
|
+
if (!response2.ok) {
|
|
2060
|
+
await cancelResponseBody3(response2);
|
|
2061
|
+
continue;
|
|
2062
|
+
}
|
|
2063
|
+
const publicKey = extractPublicKey(await response2.text());
|
|
2064
|
+
if (publicKey !== void 0) {
|
|
2065
|
+
this.cachedPublicKey = publicKey;
|
|
2066
|
+
return publicKey;
|
|
2067
|
+
}
|
|
2068
|
+
} catch {
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
throw publicKeyNotFound();
|
|
2072
|
+
}
|
|
2073
|
+
};
|
|
2074
|
+
|
|
2075
|
+
// src/adapters/lanhu/auth/session/cookie-storage.ts
|
|
2076
|
+
import { readFile as readFile2, rm as rm4 } from "fs/promises";
|
|
2077
|
+
import { CookieJar as CookieJar2 } from "tough-cookie";
|
|
2078
|
+
|
|
2079
|
+
// src/adapters/lanhu/auth/storage/atomic-file.ts
|
|
2080
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
2081
|
+
import { mkdir as mkdir2, open, rename, rm as rm3 } from "fs/promises";
|
|
2082
|
+
import { basename as basename2, dirname, join as join3 } from "path";
|
|
2083
|
+
async function writeJsonAtomic(file, value) {
|
|
2084
|
+
let handle;
|
|
2085
|
+
let temporaryFile;
|
|
2086
|
+
try {
|
|
2087
|
+
const serialized = JSON.stringify(value, null, 2);
|
|
2088
|
+
if (serialized === void 0) {
|
|
2089
|
+
throw new TypeError("Value is not JSON serializable");
|
|
2090
|
+
}
|
|
2091
|
+
const parent = dirname(file);
|
|
2092
|
+
await mkdir2(parent, { recursive: true, mode: 448 });
|
|
2093
|
+
temporaryFile = join3(parent, `.${basename2(file)}.${process.pid}.${randomUUID3()}.tmp`);
|
|
2094
|
+
handle = await open(temporaryFile, "wx", 384);
|
|
2095
|
+
await handle.writeFile(`${serialized}
|
|
2096
|
+
`, "utf8");
|
|
2097
|
+
await handle.sync();
|
|
2098
|
+
await handle.close();
|
|
2099
|
+
handle = void 0;
|
|
2100
|
+
await rename(temporaryFile, file);
|
|
2101
|
+
temporaryFile = void 0;
|
|
2102
|
+
} catch {
|
|
2103
|
+
if (handle !== void 0) {
|
|
2104
|
+
try {
|
|
2105
|
+
await handle.close();
|
|
2106
|
+
} catch {
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
if (temporaryFile !== void 0) {
|
|
2110
|
+
try {
|
|
2111
|
+
await rm3(temporaryFile, { force: true });
|
|
2112
|
+
} catch {
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
throw new LanhuError("STORAGE_ERROR", "Unable to write JSON storage atomically");
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
// src/adapters/lanhu/auth/session/cookie-storage.ts
|
|
2120
|
+
function hasErrorCode2(error, code) {
|
|
2121
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
|
2122
|
+
}
|
|
2123
|
+
function storageError(message) {
|
|
2124
|
+
return new LanhuError("STORAGE_ERROR", message);
|
|
2125
|
+
}
|
|
2126
|
+
var DATE_PROPERTIES = ["expires", "creation", "lastAccessed"];
|
|
2127
|
+
function isValidSerializedDate(value) {
|
|
2128
|
+
if (value === void 0 || value === null || value === "Infinity") {
|
|
2129
|
+
return true;
|
|
2130
|
+
}
|
|
2131
|
+
if (typeof value !== "string" && typeof value !== "number") {
|
|
2132
|
+
return false;
|
|
2133
|
+
}
|
|
2134
|
+
return !Number.isNaN(new Date(value).getTime());
|
|
2135
|
+
}
|
|
2136
|
+
function isSerializedCookie(value) {
|
|
2137
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || !("key" in value) || typeof value.key !== "string" || value.key === "" || !("value" in value) || typeof value.value !== "string") {
|
|
2138
|
+
return false;
|
|
2139
|
+
}
|
|
2140
|
+
return DATE_PROPERTIES.every(
|
|
2141
|
+
(property) => isValidSerializedDate(Reflect.get(value, property))
|
|
2142
|
+
);
|
|
2143
|
+
}
|
|
2144
|
+
var FileCookieStorage = class {
|
|
2145
|
+
constructor(file) {
|
|
2146
|
+
this.file = file;
|
|
2147
|
+
}
|
|
2148
|
+
file;
|
|
2149
|
+
async load() {
|
|
2150
|
+
let serialized;
|
|
2151
|
+
try {
|
|
2152
|
+
serialized = await readFile2(this.file, "utf8");
|
|
2153
|
+
} catch (error) {
|
|
2154
|
+
if (hasErrorCode2(error, "ENOENT")) {
|
|
2155
|
+
return new CookieJar2();
|
|
2156
|
+
}
|
|
2157
|
+
throw storageError("Unable to read cookie storage");
|
|
2158
|
+
}
|
|
2159
|
+
try {
|
|
2160
|
+
const value = JSON.parse(serialized);
|
|
2161
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || !("cookies" in value) || !Array.isArray(value.cookies) || !value.cookies.every(isSerializedCookie)) {
|
|
2162
|
+
throw new TypeError("Invalid cookie storage schema");
|
|
2163
|
+
}
|
|
2164
|
+
const serializedCookieCount = value.cookies.length;
|
|
2165
|
+
const jar = CookieJar2.fromJSON(JSON.stringify(value));
|
|
2166
|
+
const roundTripped = jar.toJSON();
|
|
2167
|
+
if (roundTripped === void 0 || roundTripped.cookies.length !== serializedCookieCount) {
|
|
2168
|
+
throw new TypeError("Cookie deserialization dropped entries");
|
|
2169
|
+
}
|
|
2170
|
+
return jar;
|
|
2171
|
+
} catch {
|
|
2172
|
+
throw storageError("Cookie storage is corrupt or has an invalid schema");
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
async save(jar) {
|
|
2176
|
+
await writeJsonAtomic(this.file, jar.toJSON());
|
|
2177
|
+
}
|
|
2178
|
+
async clear() {
|
|
2179
|
+
try {
|
|
2180
|
+
await rm4(this.file, { force: true });
|
|
2181
|
+
} catch {
|
|
2182
|
+
throw storageError("Unable to clear cookie storage");
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
};
|
|
2186
|
+
|
|
2187
|
+
// src/adapters/lanhu/auth/session/session-validator.ts
|
|
2188
|
+
function isRecord2(value) {
|
|
2189
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2190
|
+
}
|
|
2191
|
+
async function cancelResponseBody4(response) {
|
|
2192
|
+
try {
|
|
2193
|
+
await response.body?.cancel();
|
|
2194
|
+
} catch {
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
function accountFrom(body) {
|
|
2198
|
+
if (!isRecord2(body) || !isRecord2(body.result)) {
|
|
2199
|
+
return void 0;
|
|
2200
|
+
}
|
|
2201
|
+
if (typeof body.result.email === "string") {
|
|
2202
|
+
return body.result.email;
|
|
2203
|
+
}
|
|
2204
|
+
return typeof body.result.name === "string" ? body.result.name : void 0;
|
|
2205
|
+
}
|
|
2206
|
+
function sanitizedBusinessCode(code) {
|
|
2207
|
+
if (typeof code === "number" && Number.isFinite(code)) {
|
|
2208
|
+
return String(code);
|
|
2209
|
+
}
|
|
2210
|
+
if (typeof code === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(code)) {
|
|
2211
|
+
return code;
|
|
2212
|
+
}
|
|
2213
|
+
return "\u672A\u77E5";
|
|
2214
|
+
}
|
|
2215
|
+
function normalizeBusinessCode(code) {
|
|
2216
|
+
if (typeof code === "number") {
|
|
2217
|
+
return Number.isFinite(code) ? code : void 0;
|
|
2218
|
+
}
|
|
2219
|
+
if (typeof code === "string" && /^\d{1,16}$/.test(code)) {
|
|
2220
|
+
return Number.parseInt(code, 10);
|
|
2221
|
+
}
|
|
2222
|
+
return void 0;
|
|
2223
|
+
}
|
|
2224
|
+
var LanhuSessionValidator = class {
|
|
2225
|
+
constructor(origin = "https://lanhuapp.com") {
|
|
2226
|
+
this.origin = origin;
|
|
2227
|
+
}
|
|
2228
|
+
origin;
|
|
2229
|
+
async validate(jar) {
|
|
2230
|
+
try {
|
|
2231
|
+
const response = await requestWithCookies(
|
|
2232
|
+
`${this.origin}/api/account/user/detail`,
|
|
2233
|
+
{
|
|
2234
|
+
headers: {
|
|
2235
|
+
Accept: "application/json, text/plain, */*",
|
|
2236
|
+
"User-From": this.origin
|
|
2237
|
+
}
|
|
2238
|
+
},
|
|
2239
|
+
jar
|
|
2240
|
+
);
|
|
2241
|
+
if (response.status === 401 || response.status === 403) {
|
|
2242
|
+
await cancelResponseBody4(response);
|
|
2243
|
+
return { state: "invalid", reason: `HTTP ${response.status}` };
|
|
2244
|
+
}
|
|
2245
|
+
if (!response.ok) {
|
|
2246
|
+
await cancelResponseBody4(response);
|
|
2247
|
+
return { state: "unreachable", reason: `HTTP ${response.status}` };
|
|
2248
|
+
}
|
|
2249
|
+
const body = await response.json();
|
|
2250
|
+
if (!isRecord2(body) || normalizeBusinessCode(body.code) === void 0) {
|
|
2251
|
+
return { state: "unreachable", reason: "ProtocolError" };
|
|
2252
|
+
}
|
|
2253
|
+
const code = normalizeBusinessCode(body.code);
|
|
2254
|
+
if (code === 30001) {
|
|
2255
|
+
return { state: "invalid", reason: "\u84DD\u6E56\u8FD4\u56DE\u672A\u767B\u5F55" };
|
|
2256
|
+
}
|
|
2257
|
+
if (code !== 0) {
|
|
2258
|
+
return { state: "invalid", reason: `\u84DD\u6E56\u4E1A\u52A1\u7801 ${sanitizedBusinessCode(body.code)}` };
|
|
2259
|
+
}
|
|
2260
|
+
if (!isRecord2(body.result)) {
|
|
2261
|
+
return { state: "unreachable", reason: "ProtocolError" };
|
|
2262
|
+
}
|
|
2263
|
+
const account = accountFrom(body);
|
|
2264
|
+
return account === void 0 ? { state: "valid" } : { state: "valid", account };
|
|
2265
|
+
} catch (error) {
|
|
2266
|
+
return {
|
|
2267
|
+
state: "unreachable",
|
|
2268
|
+
reason: error instanceof Error && error.name !== "" ? error.name : "UnknownError"
|
|
2269
|
+
};
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
};
|
|
2273
|
+
|
|
2274
|
+
// src/adapters/lanhu/auth/storage/credential-store.ts
|
|
2275
|
+
import {
|
|
2276
|
+
createCipheriv,
|
|
2277
|
+
createDecipheriv,
|
|
2278
|
+
randomBytes,
|
|
2279
|
+
scryptSync
|
|
2280
|
+
} from "crypto";
|
|
2281
|
+
import { readFile as readFile3, rm as rm5 } from "fs/promises";
|
|
2282
|
+
|
|
2283
|
+
// src/adapters/lanhu/auth/storage/paths.ts
|
|
2284
|
+
import { homedir as homedir2 } from "os";
|
|
2285
|
+
import { join as join4 } from "path";
|
|
2286
|
+
function lanhuPaths(home = homedir2()) {
|
|
2287
|
+
const root = join4(home, ".dt-cli", "lanhu");
|
|
2288
|
+
return {
|
|
2289
|
+
root,
|
|
2290
|
+
config: join4(root, "config.json"),
|
|
2291
|
+
cookies: join4(root, "auth", "cookies.json"),
|
|
2292
|
+
password: join4(root, "auth", "password.enc"),
|
|
2293
|
+
browserProfile: join4(root, "browser-profile")
|
|
2294
|
+
};
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
// src/adapters/lanhu/auth/storage/credential-store.ts
|
|
2298
|
+
var SERVICE = "dt-lanhu-cli";
|
|
2299
|
+
var ACCOUNT_PREFIX = "lanhu:";
|
|
2300
|
+
var FILE_VERSION = 1;
|
|
2301
|
+
var PLAINTEXT_SEPARATOR = "::";
|
|
2302
|
+
var KEY_MATERIAL = "dt-lanhu-cli-credential-obfuscation-key";
|
|
2303
|
+
var KEY_SALT = "dt-lanhu-cli-credential-obfuscation-salt";
|
|
2304
|
+
function storageError2(message) {
|
|
2305
|
+
return new LanhuError("STORAGE_ERROR", message);
|
|
2306
|
+
}
|
|
2307
|
+
function hasEnoent(error) {
|
|
2308
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
2309
|
+
}
|
|
2310
|
+
function deriveKey() {
|
|
2311
|
+
return scryptSync(KEY_MATERIAL, KEY_SALT, 32);
|
|
2312
|
+
}
|
|
2313
|
+
function accountKey(account) {
|
|
2314
|
+
if (account.trim().length === 0) {
|
|
2315
|
+
throw new LanhuError("USAGE_ERROR", "Account must not be blank");
|
|
2316
|
+
}
|
|
2317
|
+
return `${ACCOUNT_PREFIX}${account}`;
|
|
2318
|
+
}
|
|
2319
|
+
function isValidPayload(value) {
|
|
2320
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && "v" in value && value.v === FILE_VERSION && "iv" in value && typeof value.iv === "string" && "tag" in value && typeof value.tag === "string" && "data" in value && typeof value.data === "string";
|
|
2321
|
+
}
|
|
2322
|
+
function createAesFileBackend(file) {
|
|
2323
|
+
async function readStored() {
|
|
2324
|
+
let text;
|
|
2325
|
+
try {
|
|
2326
|
+
text = await readFile3(file, "utf8");
|
|
2327
|
+
} catch (error) {
|
|
2328
|
+
if (hasEnoent(error)) {
|
|
2329
|
+
return null;
|
|
2330
|
+
}
|
|
2331
|
+
throw storageError2("Unable to read credential storage");
|
|
2332
|
+
}
|
|
2333
|
+
let parsed;
|
|
2334
|
+
try {
|
|
2335
|
+
parsed = JSON.parse(text);
|
|
2336
|
+
} catch {
|
|
2337
|
+
throw storageError2("Credential storage is corrupt");
|
|
2338
|
+
}
|
|
2339
|
+
if (!isValidPayload(parsed)) {
|
|
2340
|
+
throw storageError2("Credential storage has an invalid format");
|
|
2341
|
+
}
|
|
2342
|
+
return parsed;
|
|
2343
|
+
}
|
|
2344
|
+
return {
|
|
2345
|
+
async set(_service, account, password2) {
|
|
2346
|
+
const key = deriveKey();
|
|
2347
|
+
const iv = randomBytes(16);
|
|
2348
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
2349
|
+
const plaintext = Buffer.from(`${account}${PLAINTEXT_SEPARATOR}${password2}`, "utf8");
|
|
2350
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
2351
|
+
const tag = cipher.getAuthTag();
|
|
2352
|
+
const payload = {
|
|
2353
|
+
v: FILE_VERSION,
|
|
2354
|
+
iv: iv.toString("base64"),
|
|
2355
|
+
tag: tag.toString("base64"),
|
|
2356
|
+
data: ciphertext.toString("base64")
|
|
2357
|
+
};
|
|
2358
|
+
await writeJsonAtomic(file, payload);
|
|
2359
|
+
},
|
|
2360
|
+
async get(_service, account) {
|
|
2361
|
+
const stored = await readStored();
|
|
2362
|
+
if (stored === null) {
|
|
2363
|
+
return null;
|
|
2364
|
+
}
|
|
2365
|
+
const key = deriveKey();
|
|
2366
|
+
try {
|
|
2367
|
+
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(stored.iv, "base64"));
|
|
2368
|
+
decipher.setAuthTag(Buffer.from(stored.tag, "base64"));
|
|
2369
|
+
const plaintext = Buffer.concat([
|
|
2370
|
+
decipher.update(Buffer.from(stored.data, "base64")),
|
|
2371
|
+
decipher.final()
|
|
2372
|
+
]);
|
|
2373
|
+
const decoded = plaintext.toString("utf8");
|
|
2374
|
+
const prefix = `${account}${PLAINTEXT_SEPARATOR}`;
|
|
2375
|
+
if (!decoded.startsWith(prefix)) {
|
|
2376
|
+
throw storageError2("Credential account mismatch");
|
|
2377
|
+
}
|
|
2378
|
+
return decoded.slice(prefix.length);
|
|
2379
|
+
} catch (error) {
|
|
2380
|
+
if (error instanceof LanhuError) {
|
|
2381
|
+
throw error;
|
|
2382
|
+
}
|
|
2383
|
+
throw storageError2("Unable to decrypt credential");
|
|
2384
|
+
}
|
|
2385
|
+
},
|
|
2386
|
+
async delete() {
|
|
2387
|
+
try {
|
|
2388
|
+
await rm5(file, { force: true });
|
|
2389
|
+
} catch {
|
|
2390
|
+
}
|
|
2391
|
+
return true;
|
|
2392
|
+
}
|
|
2393
|
+
};
|
|
2394
|
+
}
|
|
2395
|
+
var SystemCredentialStore = class {
|
|
2396
|
+
constructor(backend, filePath) {
|
|
2397
|
+
this.backend = backend;
|
|
2398
|
+
this.fileBackend = createAesFileBackend(filePath ?? lanhuPaths().password);
|
|
2399
|
+
}
|
|
2400
|
+
backend;
|
|
2401
|
+
fileBackend;
|
|
2402
|
+
async getBackend() {
|
|
2403
|
+
return this.backend ?? this.fileBackend;
|
|
2404
|
+
}
|
|
2405
|
+
async save(account, password2) {
|
|
2406
|
+
const key = accountKey(account);
|
|
2407
|
+
try {
|
|
2408
|
+
const backend = await this.getBackend();
|
|
2409
|
+
await backend.set(SERVICE, key, password2);
|
|
2410
|
+
} catch {
|
|
2411
|
+
throw storageError2("Unable to save credential to credential storage");
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
async load(account) {
|
|
2415
|
+
const key = accountKey(account);
|
|
2416
|
+
try {
|
|
2417
|
+
const backend = await this.getBackend();
|
|
2418
|
+
const password2 = await backend.get(SERVICE, key);
|
|
2419
|
+
return password2 ?? void 0;
|
|
2420
|
+
} catch {
|
|
2421
|
+
throw storageError2("Unable to load credential from credential storage");
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
async delete(account) {
|
|
2425
|
+
const key = accountKey(account);
|
|
2426
|
+
try {
|
|
2427
|
+
const backend = await this.getBackend();
|
|
2428
|
+
await backend.delete(SERVICE, key);
|
|
2429
|
+
} catch {
|
|
2430
|
+
throw storageError2("Unable to delete credential from credential storage");
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
/**
|
|
2434
|
+
* Remove the single AES credential file unconditionally. The password.enc
|
|
2435
|
+
* store is a single-record file (see the AES backend above), so wiping it is
|
|
2436
|
+
* always correct regardless of which account/method it currently holds. This
|
|
2437
|
+
* is what `logout` relies on so a leftover obfuscated password never persists
|
|
2438
|
+
* after the session is cleared, even for a browser-method login.
|
|
2439
|
+
*/
|
|
2440
|
+
async clear() {
|
|
2441
|
+
try {
|
|
2442
|
+
const backend = await this.getBackend();
|
|
2443
|
+
await backend.delete(SERVICE, "");
|
|
2444
|
+
} catch {
|
|
2445
|
+
throw storageError2("Unable to clear credential storage");
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
};
|
|
2449
|
+
|
|
2450
|
+
// src/adapters/lanhu/auth/storage/metadata-store.ts
|
|
2451
|
+
import { readFile as readFile4, rm as rm6 } from "fs/promises";
|
|
2452
|
+
var BROWSER_NAMES = ["chrome", "edge", "brave", "arc", "chromium"];
|
|
2453
|
+
var ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
2454
|
+
function hasErrorCode3(error, code) {
|
|
2455
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
|
2456
|
+
}
|
|
2457
|
+
function storageError3(message) {
|
|
2458
|
+
return new LanhuError("STORAGE_ERROR", message);
|
|
2459
|
+
}
|
|
2460
|
+
function isNonemptyString(value) {
|
|
2461
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
2462
|
+
}
|
|
2463
|
+
function isValidIsoDate(value) {
|
|
2464
|
+
if (typeof value !== "string" || !ISO_DATE_PATTERN.test(value) || Number.isNaN(Date.parse(value))) {
|
|
2465
|
+
return false;
|
|
2466
|
+
}
|
|
2467
|
+
const year = Number(value.slice(0, 4));
|
|
2468
|
+
const month = Number(value.slice(5, 7));
|
|
2469
|
+
const day = Number(value.slice(8, 10));
|
|
2470
|
+
const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
2471
|
+
return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth;
|
|
2472
|
+
}
|
|
2473
|
+
function isBrowserName(value) {
|
|
2474
|
+
return typeof value === "string" && BROWSER_NAMES.includes(value);
|
|
2475
|
+
}
|
|
2476
|
+
function safeMetadata(value) {
|
|
2477
|
+
const metadata = {
|
|
2478
|
+
version: value.version,
|
|
2479
|
+
method: value.method,
|
|
2480
|
+
lastLoginAt: value.lastLoginAt
|
|
2481
|
+
};
|
|
2482
|
+
if (value.account !== void 0) {
|
|
2483
|
+
metadata.account = value.account;
|
|
2484
|
+
}
|
|
2485
|
+
if (value.browser !== void 0) {
|
|
2486
|
+
metadata.browser = value.browser;
|
|
2487
|
+
}
|
|
2488
|
+
if (value.profile !== void 0) {
|
|
2489
|
+
metadata.profile = value.profile;
|
|
2490
|
+
}
|
|
2491
|
+
return metadata;
|
|
2492
|
+
}
|
|
2493
|
+
function parseMetadata(value) {
|
|
2494
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || !("version" in value) || value.version !== 1 || !("method" in value) || value.method !== "password" && value.method !== "browser" || !("lastLoginAt" in value) || !isValidIsoDate(value.lastLoginAt)) {
|
|
2495
|
+
throw new TypeError("Invalid metadata schema");
|
|
2496
|
+
}
|
|
2497
|
+
if ("account" in value && value.account !== void 0 && !isNonemptyString(value.account)) {
|
|
2498
|
+
throw new TypeError("Invalid metadata account");
|
|
2499
|
+
}
|
|
2500
|
+
if ("browser" in value && value.browser !== void 0 && !isBrowserName(value.browser)) {
|
|
2501
|
+
throw new TypeError("Invalid metadata browser");
|
|
2502
|
+
}
|
|
2503
|
+
if ("profile" in value && value.profile !== void 0 && !isNonemptyString(value.profile)) {
|
|
2504
|
+
throw new TypeError("Invalid metadata profile");
|
|
2505
|
+
}
|
|
2506
|
+
if (value.method === "password" && !("account" in value)) {
|
|
2507
|
+
throw new TypeError("Password metadata requires an account");
|
|
2508
|
+
}
|
|
2509
|
+
if (value.method === "browser" && !("browser" in value)) {
|
|
2510
|
+
throw new TypeError("Browser metadata requires a browser");
|
|
2511
|
+
}
|
|
2512
|
+
return safeMetadata(value);
|
|
2513
|
+
}
|
|
2514
|
+
var FileMetadataStore = class {
|
|
2515
|
+
constructor(file) {
|
|
2516
|
+
this.file = file;
|
|
2517
|
+
}
|
|
2518
|
+
file;
|
|
2519
|
+
async load() {
|
|
2520
|
+
let serialized;
|
|
2521
|
+
try {
|
|
2522
|
+
serialized = await readFile4(this.file, "utf8");
|
|
2523
|
+
} catch (error) {
|
|
2524
|
+
if (hasErrorCode3(error, "ENOENT")) {
|
|
2525
|
+
return void 0;
|
|
2526
|
+
}
|
|
2527
|
+
throw storageError3("Unable to read authentication metadata");
|
|
2528
|
+
}
|
|
2529
|
+
try {
|
|
2530
|
+
return parseMetadata(JSON.parse(serialized));
|
|
2531
|
+
} catch {
|
|
2532
|
+
throw storageError3("Authentication metadata is corrupt or has an invalid schema");
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
async save(value) {
|
|
2536
|
+
let metadata;
|
|
2537
|
+
try {
|
|
2538
|
+
metadata = parseMetadata(safeMetadata(value));
|
|
2539
|
+
} catch {
|
|
2540
|
+
throw storageError3("Authentication metadata is corrupt or has an invalid schema");
|
|
2541
|
+
}
|
|
2542
|
+
await writeJsonAtomic(this.file, metadata);
|
|
2543
|
+
}
|
|
2544
|
+
async clear() {
|
|
2545
|
+
try {
|
|
2546
|
+
await rm6(this.file, { force: true });
|
|
2547
|
+
} catch {
|
|
2548
|
+
throw storageError3("Unable to clear authentication metadata");
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
};
|
|
2552
|
+
|
|
2553
|
+
// src/adapters/lanhu/factory.ts
|
|
2554
|
+
function chromeOpenerFromLaunch() {
|
|
2555
|
+
return async (profileDir) => {
|
|
2556
|
+
const chrome = await launchIsolatedChrome({ profileDir });
|
|
2557
|
+
return {
|
|
2558
|
+
async cookies() {
|
|
2559
|
+
const result = await chrome.cdp.send(
|
|
2560
|
+
"Storage.getCookies",
|
|
2561
|
+
// Wide matching: collect cookies scoped to the apex host and its
|
|
2562
|
+
// subdomains so a `session` / `user_token` set on either is seen.
|
|
2563
|
+
{ urls: ["https://lanhuapp.com", "https://www.lanhuapp.com"] }
|
|
2564
|
+
);
|
|
2565
|
+
return result.cookies.map(cdpCookieToBrowser);
|
|
2566
|
+
},
|
|
2567
|
+
async close() {
|
|
2568
|
+
await chrome.close();
|
|
2569
|
+
}
|
|
2570
|
+
};
|
|
2571
|
+
};
|
|
2572
|
+
}
|
|
2573
|
+
function buildLanhuAuthService() {
|
|
2574
|
+
const paths = lanhuPaths();
|
|
2575
|
+
const validator = new LanhuSessionValidator();
|
|
2576
|
+
const cookies = new FileCookieStorage(paths.cookies);
|
|
2577
|
+
const metadata = new FileMetadataStore(paths.config);
|
|
2578
|
+
const credentials = new SystemCredentialStore(void 0, paths.password);
|
|
2579
|
+
const reader = new SweetCookieReader();
|
|
2580
|
+
const browserFlow = new BrowserLoginFlow(
|
|
2581
|
+
reader,
|
|
2582
|
+
validator,
|
|
2583
|
+
chromeOpenerFromLaunch(),
|
|
2584
|
+
paths.browserProfile
|
|
2585
|
+
);
|
|
2586
|
+
const flows = {
|
|
2587
|
+
browser: (options) => browserFlow.login(options),
|
|
2588
|
+
password: (options) => {
|
|
2589
|
+
const jar = new CookieJar3();
|
|
2590
|
+
const flow = new PasswordLoginFlow(new BundlePublicKeyProvider(), validator, jar);
|
|
2591
|
+
return flow.login(options);
|
|
2592
|
+
}
|
|
2593
|
+
};
|
|
2594
|
+
return new AuthService(flows, validator, cookies, metadata, credentials, paths.browserProfile);
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
// src/adapters/omp/token-cache.ts
|
|
2598
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
2599
|
+
import { homedir as homedir3 } from "os";
|
|
2600
|
+
import { dirname as dirname2, join as join5 } from "path";
|
|
2601
|
+
import { mkdir as mkdir3, readFile as readFile5, rename as rename2, unlink, writeFile } from "fs/promises";
|
|
2602
|
+
function defaultOmpTokenCachePath(env = process.env) {
|
|
2603
|
+
const cacheRoot = env.XDG_CACHE_HOME || join5(homedir3(), ".cache");
|
|
2604
|
+
return join5(cacheRoot, "dt-cli", "omp-token-cache.json");
|
|
2605
|
+
}
|
|
2606
|
+
var FileOmpTokenCache = class {
|
|
2607
|
+
constructor(path = defaultOmpTokenCachePath()) {
|
|
2608
|
+
this.path = path;
|
|
2609
|
+
}
|
|
2610
|
+
path;
|
|
2611
|
+
async get(username) {
|
|
2612
|
+
return (await this.read()).tokens[username];
|
|
2613
|
+
}
|
|
2614
|
+
async set(username, entry) {
|
|
2615
|
+
const data = await this.read();
|
|
2616
|
+
data.tokens[username] = entry;
|
|
2617
|
+
await this.write(data);
|
|
2618
|
+
}
|
|
2619
|
+
async remove(username) {
|
|
2620
|
+
const data = await this.read();
|
|
2621
|
+
if (!(username in data.tokens)) return;
|
|
2622
|
+
delete data.tokens[username];
|
|
2623
|
+
await this.write(data);
|
|
2624
|
+
}
|
|
2625
|
+
async getActiveUsername() {
|
|
2626
|
+
return (await this.read()).activeUsername;
|
|
2627
|
+
}
|
|
2628
|
+
async setActiveUsername(username) {
|
|
2629
|
+
const data = await this.read();
|
|
2630
|
+
data.activeUsername = username;
|
|
2631
|
+
await this.write(data);
|
|
2632
|
+
}
|
|
2633
|
+
async clearActiveUsername() {
|
|
2634
|
+
const data = await this.read();
|
|
2635
|
+
if (!data.activeUsername) return;
|
|
2636
|
+
delete data.activeUsername;
|
|
2637
|
+
await this.write(data);
|
|
2638
|
+
}
|
|
2639
|
+
async read() {
|
|
2640
|
+
try {
|
|
2641
|
+
const parsed = JSON.parse(await readFile5(this.path, "utf8"));
|
|
2642
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { tokens: {} };
|
|
2643
|
+
const record = parsed;
|
|
2644
|
+
if (record.tokens && typeof record.tokens === "object" && !Array.isArray(record.tokens)) {
|
|
2645
|
+
return {
|
|
2646
|
+
...typeof record.activeUsername === "string" ? { activeUsername: record.activeUsername } : {},
|
|
2647
|
+
tokens: record.tokens
|
|
2648
|
+
};
|
|
2649
|
+
}
|
|
2650
|
+
return { tokens: record };
|
|
2651
|
+
} catch (error) {
|
|
2652
|
+
const code = error.code;
|
|
2653
|
+
if (code === "ENOENT" || error instanceof SyntaxError) return { tokens: {} };
|
|
2654
|
+
throw new CliError("internal_error", `\u8BFB\u53D6 OMP token \u7F13\u5B58\u5931\u8D25\uFF1A${String(error.message)}`, {
|
|
2655
|
+
cause: error
|
|
2656
|
+
});
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
async write(data) {
|
|
2660
|
+
const directory = dirname2(this.path);
|
|
2661
|
+
const temporary = `${this.path}.${randomUUID4()}.tmp`;
|
|
2662
|
+
try {
|
|
2663
|
+
await mkdir3(directory, { recursive: true, mode: 448 });
|
|
2664
|
+
await writeFile(temporary, `${JSON.stringify(data, null, 2)}
|
|
2665
|
+
`, { encoding: "utf8", mode: 384 });
|
|
2666
|
+
await rename2(temporary, this.path);
|
|
2667
|
+
} catch (error) {
|
|
2668
|
+
await unlink(temporary).catch(() => void 0);
|
|
2669
|
+
throw new CliError("internal_error", `\u5199\u5165 OMP token \u7F13\u5B58\u5931\u8D25\uFF1A${String(error.message)}`, {
|
|
2670
|
+
cause: error
|
|
2671
|
+
});
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
};
|
|
2675
|
+
|
|
2676
|
+
// src/adapters/omp/client.ts
|
|
2677
|
+
var DEFAULT_OMP_BASE_URL = "http://omp.dtstack.cn";
|
|
2678
|
+
var DEFAULT_TOKEN_EXPIRES_IN = 3 * 24 * 60 * 60;
|
|
2679
|
+
var REFRESH_BUFFER_SECONDS = 5 * 60;
|
|
2680
|
+
var DEPLOY_LOG_SCAN_PAGE_SIZE = 1e3;
|
|
2681
|
+
var DEPLOY_LOG_SCAN_MAX_PAGES = 50;
|
|
2682
|
+
function objectPayload(value, context) {
|
|
2683
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
2684
|
+
throw new CliError("invalid_response", `${context}\u8FD4\u56DE\u7ED3\u6784\u4E0D\u662F\u5BF9\u8C61`, {
|
|
2685
|
+
details: value
|
|
2686
|
+
});
|
|
2687
|
+
}
|
|
2688
|
+
return value;
|
|
2689
|
+
}
|
|
2690
|
+
function requiredString(value, field, context) {
|
|
2691
|
+
if (typeof value !== "string" || !value) {
|
|
2692
|
+
throw new CliError("invalid_response", `${context}\u54CD\u5E94\u7F3A\u5C11 ${field}`, {
|
|
2693
|
+
details: value
|
|
2694
|
+
});
|
|
2695
|
+
}
|
|
2696
|
+
return value;
|
|
2697
|
+
}
|
|
2698
|
+
function rawEnvironment(value) {
|
|
2699
|
+
const env = objectPayload(value, "OMP \u73AF\u5883\u5217\u8868");
|
|
2700
|
+
if (!Number.isInteger(env.id) || typeof env.name !== "string") {
|
|
2701
|
+
throw new CliError(
|
|
2702
|
+
"invalid_response",
|
|
2703
|
+
"OMP \u73AF\u5883\u6570\u636E\u7F3A\u5C11\u6709\u6548\u7684 id \u6216 name",
|
|
2704
|
+
{ details: env }
|
|
2705
|
+
);
|
|
2706
|
+
}
|
|
2707
|
+
return env;
|
|
2708
|
+
}
|
|
2709
|
+
function normalizeEnvironment(env) {
|
|
2710
|
+
return {
|
|
2711
|
+
id: env.id,
|
|
2712
|
+
name: env.name,
|
|
2713
|
+
version: typeof env.version === "string" ? env.version : null,
|
|
2714
|
+
branch: typeof env.branch === "string" ? env.branch : null,
|
|
2715
|
+
namespace: typeof env.namespace === "string" ? env.namespace : null,
|
|
2716
|
+
type: typeof env.type === "string" ? env.type : null,
|
|
2717
|
+
productName: typeof env.product_name === "string" ? env.product_name : null,
|
|
2718
|
+
group: env.group,
|
|
2719
|
+
dbType: typeof env.db_type === "string" ? env.db_type : null,
|
|
2720
|
+
updatedTime: typeof env.updated_time === "string" ? env.updated_time : null,
|
|
2721
|
+
status: typeof env.status === "string" ? env.status : null,
|
|
2722
|
+
canApplyActivate: typeof env.can_apply_activate === "boolean" ? env.can_apply_activate : null
|
|
2723
|
+
};
|
|
2724
|
+
}
|
|
2725
|
+
function hasInvalidUnicode(value) {
|
|
2726
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
2727
|
+
const code = value.charCodeAt(index);
|
|
2728
|
+
if (code === 65533) return true;
|
|
2729
|
+
if (code >= 55296 && code <= 56319) {
|
|
2730
|
+
const next = value.charCodeAt(index + 1);
|
|
2731
|
+
if (next < 56320 || next > 57343) return true;
|
|
2732
|
+
index += 1;
|
|
2733
|
+
} else if (code >= 56320 && code <= 57343) {
|
|
2734
|
+
return true;
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
return false;
|
|
2738
|
+
}
|
|
2739
|
+
var OmpClient = class {
|
|
2740
|
+
constructor(options) {
|
|
2741
|
+
this.options = options;
|
|
2742
|
+
if (!options.username)
|
|
2743
|
+
throw new CliError(
|
|
2744
|
+
"not_authenticated",
|
|
2745
|
+
"OMP \u5C1A\u672A\u767B\u5F55\uFF0C\u8BF7\u6267\u884C dt auth login omp"
|
|
2746
|
+
);
|
|
2747
|
+
if (hasInvalidUnicode(options.username)) {
|
|
2748
|
+
throw new CliError(
|
|
2749
|
+
"invalid_argument",
|
|
2750
|
+
"OMP_MCP_USERNAME \u542B\u975E\u6CD5 Unicode \u5B57\u7B26\uFF0C\u8BF7\u4ECE\u767B\u5F55 shell \u91CD\u65B0\u52A0\u8F7D\u73AF\u5883\u53D8\u91CF\u540E\u91CD\u8BD5"
|
|
2751
|
+
);
|
|
2752
|
+
}
|
|
2753
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
2754
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
2755
|
+
this.timeoutMs = options.timeoutMs ?? 15e3;
|
|
2756
|
+
this.tokenCache = options.tokenCache ?? new FileOmpTokenCache();
|
|
2757
|
+
this.now = options.now ?? (() => Date.now() / 1e3);
|
|
2758
|
+
}
|
|
2759
|
+
options;
|
|
2760
|
+
baseUrl;
|
|
2761
|
+
fetchImpl;
|
|
2762
|
+
timeoutMs;
|
|
2763
|
+
tokenCache;
|
|
2764
|
+
now;
|
|
2765
|
+
async authenticate() {
|
|
2766
|
+
return this.login();
|
|
2767
|
+
}
|
|
2768
|
+
async listEnvironments(options) {
|
|
2769
|
+
const environments = await this.fetchEnvironments(options);
|
|
2770
|
+
return {
|
|
2771
|
+
total: environments.length,
|
|
2772
|
+
environments: environments.map(normalizeEnvironment)
|
|
2773
|
+
};
|
|
2774
|
+
}
|
|
2775
|
+
async deploy(request) {
|
|
2776
|
+
if (!Number.isSafeInteger(request.envId) || request.envId <= 0) {
|
|
2777
|
+
throw new CliError("invalid_argument", "env-id \u5FC5\u987B\u662F\u6B63\u6574\u6570");
|
|
2778
|
+
}
|
|
2779
|
+
if (!request.branch.trim())
|
|
2780
|
+
throw new CliError("invalid_argument", "branch \u4E0D\u80FD\u4E3A\u7A7A");
|
|
2781
|
+
if (request.services.length === 0 || request.services.some((service) => !service.trim())) {
|
|
2782
|
+
throw new CliError("invalid_argument", "\u81F3\u5C11\u4F20\u5165\u4E00\u4E2A\u6709\u6548\u7684 service");
|
|
2783
|
+
}
|
|
2784
|
+
const environments = await this.fetchEnvironments();
|
|
2785
|
+
const env = environments.find(
|
|
2786
|
+
(candidate) => candidate.id === request.envId
|
|
2787
|
+
);
|
|
2788
|
+
if (!env)
|
|
2789
|
+
throw new CliError(
|
|
2790
|
+
"invalid_argument",
|
|
2791
|
+
`OMP \u73AF\u5883\u4E0D\u5B58\u5728\uFF1A${request.envId}`
|
|
2792
|
+
);
|
|
2793
|
+
const deployRequest = {
|
|
2794
|
+
id: env.id,
|
|
2795
|
+
name: env.name,
|
|
2796
|
+
version: env.version,
|
|
2797
|
+
javaVersion: env.javaVersion || "jdk8",
|
|
2798
|
+
hadoopVersion: env.hadoopVersion || "hadoop3",
|
|
2799
|
+
describe: env.describe || "",
|
|
2800
|
+
namespace: env.namespace,
|
|
2801
|
+
mvn: env.mvn,
|
|
2802
|
+
type: env.type,
|
|
2803
|
+
branch: request.branch,
|
|
2804
|
+
new_branch: request.newBranch || "",
|
|
2805
|
+
merge: request.merge ?? false,
|
|
2806
|
+
service: request.services,
|
|
2807
|
+
group: env.group,
|
|
2808
|
+
db_type: env.db_type,
|
|
2809
|
+
product_name: env.product_name
|
|
2810
|
+
};
|
|
2811
|
+
const data = await this.authenticatedRequest(
|
|
2812
|
+
"/api/deploy/environment/upgrade_k8s/",
|
|
2813
|
+
{ method: "POST", body: JSON.stringify(deployRequest) },
|
|
2814
|
+
"OMP \u90E8\u7F72"
|
|
2815
|
+
);
|
|
2816
|
+
const normalized = normalizeEnvironment(env);
|
|
2817
|
+
return {
|
|
2818
|
+
status: data.status,
|
|
2819
|
+
deployId: data.id,
|
|
2820
|
+
message: "\u90E8\u7F72\u4EFB\u52A1\u5DF2\u63D0\u4EA4",
|
|
2821
|
+
environment: {
|
|
2822
|
+
id: normalized.id,
|
|
2823
|
+
name: normalized.name,
|
|
2824
|
+
namespace: normalized.namespace ?? null,
|
|
2825
|
+
type: normalized.type ?? null
|
|
2826
|
+
},
|
|
2827
|
+
deployInfo: {
|
|
2828
|
+
branch: request.branch,
|
|
2829
|
+
services: request.services,
|
|
2830
|
+
fullRequestParams: deployRequest
|
|
2831
|
+
}
|
|
2832
|
+
};
|
|
2833
|
+
}
|
|
2834
|
+
async listBranches(query) {
|
|
2835
|
+
if (!query.namespace.trim())
|
|
2836
|
+
throw new CliError("invalid_argument", "namespace \u4E0D\u80FD\u4E3A\u7A7A");
|
|
2837
|
+
const params = new URLSearchParams({ namespace: query.namespace });
|
|
2838
|
+
const data = await this.authenticatedRequest(
|
|
2839
|
+
`/api/deploy/environment/get_branch/?${params}`,
|
|
2840
|
+
{},
|
|
2841
|
+
"OMP \u73AF\u5883\u90E8\u7F72\u5206\u652F",
|
|
2842
|
+
{ allowArray: true }
|
|
2843
|
+
);
|
|
2844
|
+
if (!Array.isArray(data)) {
|
|
2845
|
+
throw new CliError("invalid_response", "OMP \u73AF\u5883\u90E8\u7F72\u5206\u652F\u54CD\u5E94\u4E0D\u662F\u6570\u7EC4", {
|
|
2846
|
+
details: data
|
|
2847
|
+
});
|
|
2848
|
+
}
|
|
2849
|
+
const branches = data.map((value) => {
|
|
2850
|
+
const item = objectPayload(value, "OMP \u73AF\u5883\u90E8\u7F72\u5206\u652F");
|
|
2851
|
+
return {
|
|
2852
|
+
name: item.name,
|
|
2853
|
+
tag: item.tag,
|
|
2854
|
+
status: item.status
|
|
2855
|
+
};
|
|
2856
|
+
});
|
|
2857
|
+
const app = query.app?.trim();
|
|
2858
|
+
const filtered = app ? branches.filter(
|
|
2859
|
+
(branch) => String(branch.name).toLowerCase().includes(app.toLowerCase())
|
|
2860
|
+
) : branches;
|
|
2861
|
+
return { total: filtered.length, branches: filtered };
|
|
2862
|
+
}
|
|
2863
|
+
async listDeployLogs(query) {
|
|
2864
|
+
const userFilter = query.user?.trim();
|
|
2865
|
+
if (!userFilter) {
|
|
2866
|
+
const { total, logs } = await this.fetchDeployLogPage(
|
|
2867
|
+
query.page,
|
|
2868
|
+
query.limit,
|
|
2869
|
+
query
|
|
2870
|
+
);
|
|
2871
|
+
return {
|
|
2872
|
+
total,
|
|
2873
|
+
page: query.page,
|
|
2874
|
+
limit: query.limit,
|
|
2875
|
+
logs,
|
|
2876
|
+
truncated: false
|
|
2877
|
+
};
|
|
2878
|
+
}
|
|
2879
|
+
const needle = userFilter.toLowerCase();
|
|
2880
|
+
const matched = [];
|
|
2881
|
+
let page = query.page;
|
|
2882
|
+
let collected = 0;
|
|
2883
|
+
let serverTotal = 0;
|
|
2884
|
+
let scannedPages = 0;
|
|
2885
|
+
let truncated = false;
|
|
2886
|
+
for (; ; ) {
|
|
2887
|
+
const result = await this.fetchDeployLogPage(
|
|
2888
|
+
page,
|
|
2889
|
+
DEPLOY_LOG_SCAN_PAGE_SIZE,
|
|
2890
|
+
query
|
|
2891
|
+
);
|
|
2892
|
+
serverTotal = result.total;
|
|
2893
|
+
collected += result.logs.length;
|
|
2894
|
+
scannedPages += 1;
|
|
2895
|
+
matched.push(
|
|
2896
|
+
...result.logs.filter(
|
|
2897
|
+
(log) => typeof log.user === "string" && log.user.toLowerCase().includes(needle)
|
|
2898
|
+
)
|
|
2899
|
+
);
|
|
2900
|
+
if (result.logs.length === 0 || collected >= serverTotal) break;
|
|
2901
|
+
if (scannedPages >= DEPLOY_LOG_SCAN_MAX_PAGES) {
|
|
2902
|
+
truncated = true;
|
|
2903
|
+
break;
|
|
2904
|
+
}
|
|
2905
|
+
page += 1;
|
|
2906
|
+
}
|
|
2907
|
+
return {
|
|
2908
|
+
total: matched.length,
|
|
2909
|
+
page: query.page,
|
|
2910
|
+
limit: query.limit,
|
|
2911
|
+
logs: matched,
|
|
2912
|
+
truncated
|
|
2913
|
+
};
|
|
2914
|
+
}
|
|
2915
|
+
async fetchDeployLogPage(page, limit, query) {
|
|
2916
|
+
const params = new URLSearchParams({
|
|
2917
|
+
page: String(page),
|
|
2918
|
+
limit: String(limit),
|
|
2919
|
+
sort: "-id",
|
|
2920
|
+
environmentlog: query.environment ?? "",
|
|
2921
|
+
services: query.services ?? "",
|
|
2922
|
+
product_name: "\u6570\u6808"
|
|
2923
|
+
});
|
|
2924
|
+
const data = await this.authenticatedRequest(
|
|
2925
|
+
`/api/deploy/envlog/?${params}`,
|
|
2926
|
+
{},
|
|
2927
|
+
"OMP \u90E8\u7F72\u5386\u53F2"
|
|
2928
|
+
);
|
|
2929
|
+
if (!Array.isArray(data.results)) {
|
|
2930
|
+
throw new CliError("invalid_response", "OMP \u90E8\u7F72\u5386\u53F2\u54CD\u5E94\u7F3A\u5C11 results", {
|
|
2931
|
+
details: data
|
|
2932
|
+
});
|
|
2933
|
+
}
|
|
2934
|
+
return {
|
|
2935
|
+
total: data.count ?? 0,
|
|
2936
|
+
logs: data.results.map((value) => {
|
|
2937
|
+
const log = objectPayload(value, "OMP \u90E8\u7F72\u5386\u53F2");
|
|
2938
|
+
return {
|
|
2939
|
+
id: log.id,
|
|
2940
|
+
envName: log.name,
|
|
2941
|
+
user: log.user,
|
|
2942
|
+
branch: log.branch,
|
|
2943
|
+
services: log.services,
|
|
2944
|
+
status: log.build_status,
|
|
2945
|
+
createdTime: log.created_time
|
|
2946
|
+
};
|
|
2947
|
+
})
|
|
2948
|
+
};
|
|
2949
|
+
}
|
|
2950
|
+
async fetchEnvironments(options) {
|
|
2951
|
+
const params = new URLSearchParams({
|
|
2952
|
+
page: "1",
|
|
2953
|
+
limit: "999",
|
|
2954
|
+
sort: "id",
|
|
2955
|
+
name: "",
|
|
2956
|
+
version: options?.version ?? "",
|
|
2957
|
+
group: "4,5,6,7,8,9",
|
|
2958
|
+
product_name: "\u6570\u6808"
|
|
2959
|
+
});
|
|
2960
|
+
const data = await this.authenticatedRequest(
|
|
2961
|
+
`/api/deploy/environment/?${params}`,
|
|
2962
|
+
{},
|
|
2963
|
+
"OMP \u73AF\u5883\u5217\u8868"
|
|
2964
|
+
);
|
|
2965
|
+
if (!Array.isArray(data.results)) {
|
|
2966
|
+
throw new CliError("invalid_response", "OMP \u73AF\u5883\u5217\u8868\u54CD\u5E94\u7F3A\u5C11 results", {
|
|
2967
|
+
details: data
|
|
2968
|
+
});
|
|
2969
|
+
}
|
|
2970
|
+
return data.results.map(rawEnvironment);
|
|
2971
|
+
}
|
|
2972
|
+
async authenticatedRequest(path, init, context, options = {}) {
|
|
2973
|
+
let token = await this.accessToken();
|
|
2974
|
+
let response = await this.fetch(path, init, token);
|
|
2975
|
+
if (response.status === 401 || response.status === 403) {
|
|
2976
|
+
await this.tokenCache.remove(this.options.username);
|
|
2977
|
+
token = await this.login();
|
|
2978
|
+
response = await this.fetch(path, init, token);
|
|
2979
|
+
}
|
|
2980
|
+
return this.parseResponse(response, context, options);
|
|
2981
|
+
}
|
|
2982
|
+
async accessToken() {
|
|
2983
|
+
const cached = await this.tokenCache.get(this.options.username);
|
|
2984
|
+
if (cached && this.isUsable(cached)) return cached.accessToken;
|
|
2985
|
+
if (cached) await this.tokenCache.remove(this.options.username);
|
|
2986
|
+
return this.login();
|
|
2987
|
+
}
|
|
2988
|
+
isUsable(entry) {
|
|
2989
|
+
return Boolean(entry.accessToken) && this.now() < entry.createdAt + entry.expiresIn - REFRESH_BUFFER_SECONDS;
|
|
2990
|
+
}
|
|
2991
|
+
async login() {
|
|
2992
|
+
if (!this.options.password) {
|
|
2993
|
+
throw new CliError(
|
|
2994
|
+
"not_authenticated",
|
|
2995
|
+
"OMP access token \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C dt auth login omp"
|
|
2996
|
+
);
|
|
2997
|
+
}
|
|
2998
|
+
const response = await this.fetch("/api/users/login", {
|
|
2999
|
+
method: "POST",
|
|
3000
|
+
body: JSON.stringify({
|
|
3001
|
+
username: this.options.username,
|
|
3002
|
+
password: this.options.password
|
|
3003
|
+
})
|
|
3004
|
+
});
|
|
3005
|
+
const data = await this.parseResponse(response, "OMP \u767B\u5F55");
|
|
3006
|
+
const accessToken = requiredString(
|
|
3007
|
+
data.access ?? data.access_token,
|
|
3008
|
+
"access token",
|
|
3009
|
+
"OMP \u767B\u5F55"
|
|
3010
|
+
);
|
|
3011
|
+
await this.tokenCache.set(this.options.username, {
|
|
3012
|
+
accessToken,
|
|
3013
|
+
refreshToken: typeof data.refresh === "string" ? data.refresh : "",
|
|
3014
|
+
createdAt: this.now(),
|
|
3015
|
+
expiresIn: typeof data.expires_in === "number" ? data.expires_in : DEFAULT_TOKEN_EXPIRES_IN
|
|
3016
|
+
});
|
|
3017
|
+
await this.tokenCache.setActiveUsername(this.options.username);
|
|
3018
|
+
return accessToken;
|
|
3019
|
+
}
|
|
3020
|
+
async fetch(path, init, token) {
|
|
3021
|
+
const headers = new Headers(init.headers);
|
|
3022
|
+
headers.set("accept", "application/json, text/plain, */*");
|
|
3023
|
+
headers.set("content-type", "application/json");
|
|
3024
|
+
headers.set("cache-control", "no-cache");
|
|
3025
|
+
if (token) headers.set("authorization", `jwt ${token}`);
|
|
3026
|
+
try {
|
|
3027
|
+
return await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
3028
|
+
...init,
|
|
3029
|
+
headers,
|
|
3030
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
3031
|
+
});
|
|
3032
|
+
} catch (error) {
|
|
3033
|
+
if (error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) {
|
|
3034
|
+
throw new CliError("timeout", "OMP \u8BF7\u6C42\u8D85\u65F6", {
|
|
3035
|
+
retryable: true,
|
|
3036
|
+
cause: error
|
|
3037
|
+
});
|
|
3038
|
+
}
|
|
3039
|
+
throw new CliError(
|
|
3040
|
+
"network_error",
|
|
3041
|
+
`\u65E0\u6CD5\u8FDE\u63A5 OMP \u670D\u52A1\uFF1A${String(error.message ?? error)}`,
|
|
3042
|
+
{
|
|
3043
|
+
retryable: true,
|
|
3044
|
+
cause: error
|
|
3045
|
+
}
|
|
3046
|
+
);
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
async parseResponse(response, context, options = {}) {
|
|
3050
|
+
const text = await response.text();
|
|
3051
|
+
let data = null;
|
|
3052
|
+
try {
|
|
3053
|
+
data = text ? JSON.parse(text) : null;
|
|
3054
|
+
} catch {
|
|
3055
|
+
throw new CliError("invalid_response", `${context}\u8FD4\u56DE\u4E86\u975E JSON \u5185\u5BB9`, {
|
|
3056
|
+
details: text.slice(0, 500)
|
|
3057
|
+
});
|
|
3058
|
+
}
|
|
3059
|
+
if (!response.ok) {
|
|
3060
|
+
throw new CliError(
|
|
3061
|
+
"upstream_error",
|
|
3062
|
+
`${context}\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${response.status}\uFF09`,
|
|
3063
|
+
{
|
|
3064
|
+
retryable: response.status === 429 || response.status >= 500,
|
|
3065
|
+
details: { status: response.status, response: data }
|
|
3066
|
+
}
|
|
3067
|
+
);
|
|
3068
|
+
}
|
|
3069
|
+
if (options.allowArray && Array.isArray(data)) {
|
|
3070
|
+
return data;
|
|
3071
|
+
}
|
|
3072
|
+
return objectPayload(data, context);
|
|
3073
|
+
}
|
|
3074
|
+
};
|
|
3075
|
+
|
|
3076
|
+
// src/commands/auth.ts
|
|
3077
|
+
var LANHU_TARGET = "https://lanhuapp.com";
|
|
3078
|
+
var LANHU_BROWSERS = ["chrome", "edge", "brave", "arc", "chromium"];
|
|
3079
|
+
var LANHU_METHODS = ["browser", "password"];
|
|
3080
|
+
var defaultDependencies2 = {
|
|
3081
|
+
writer: {
|
|
3082
|
+
stdout: (value) => process.stdout.write(`${value}
|
|
3083
|
+
`),
|
|
3084
|
+
stderr: (value) => process.stderr.write(`${value}
|
|
3085
|
+
`),
|
|
3086
|
+
isTTY: () => Boolean(process.stdout.isTTY)
|
|
3087
|
+
},
|
|
3088
|
+
env: process.env,
|
|
3089
|
+
glabRunner: defaultGlabRunner,
|
|
3090
|
+
glabInteractive: runGlabInteractive,
|
|
3091
|
+
ompTokenCache: new FileOmpTokenCache(),
|
|
3092
|
+
ompPrompt: promptOmpCredentials,
|
|
3093
|
+
createOmpClient: (options) => new OmpClient(options),
|
|
3094
|
+
createLanhuAuthService: buildLanhuAuthService,
|
|
3095
|
+
lanhuPrompt: promptLanhuCredentials
|
|
3096
|
+
};
|
|
3097
|
+
function outputMode(command, dependencies) {
|
|
3098
|
+
const opts = command.optsWithGlobals();
|
|
3099
|
+
return opts.json ? "json" : opts.output ?? dependencies.env.DTSTACK_OUTPUT ?? "auto";
|
|
3100
|
+
}
|
|
3101
|
+
function gitlabHost(env) {
|
|
3102
|
+
return env.DTSTACK_GITLAB_HOST ?? env.GITLAB_HOST ?? DEFAULT_GITLAB_HOST;
|
|
3103
|
+
}
|
|
3104
|
+
function ensureService(service) {
|
|
3105
|
+
if (!["gitlab", "omp", "lanhu"].includes(service)) {
|
|
3106
|
+
throw new CliError("invalid_argument", `auth \u4EC5\u652F\u6301 gitlab\u3001omp \u6216 lanhu\uFF0C\u65E0\u6CD5\u5904\u7406\u670D\u52A1\uFF1A${service}`);
|
|
3107
|
+
}
|
|
3108
|
+
}
|
|
3109
|
+
function ompBaseUrl(command, env) {
|
|
3110
|
+
const globals = command.optsWithGlobals();
|
|
3111
|
+
return globals.ompBaseUrl ?? env.DTSTACK_OMP_BASE_URL ?? DEFAULT_OMP_BASE_URL;
|
|
3112
|
+
}
|
|
3113
|
+
function lanhuBrowser(value) {
|
|
3114
|
+
if (!LANHU_BROWSERS.includes(value)) {
|
|
3115
|
+
throw new CliError(
|
|
3116
|
+
"invalid_argument",
|
|
3117
|
+
`\u4E0D\u652F\u6301\u7684\u6D4F\u89C8\u5668\uFF1A${value}\uFF08\u53EF\u9009 chrome\u3001edge\u3001brave\u3001arc\u3001chromium\uFF09`
|
|
3118
|
+
);
|
|
3119
|
+
}
|
|
3120
|
+
return value;
|
|
3121
|
+
}
|
|
3122
|
+
function lanhuMethod(value) {
|
|
3123
|
+
if (!LANHU_METHODS.includes(value)) {
|
|
3124
|
+
throw new CliError("invalid_argument", `\u4E0D\u652F\u6301\u7684\u65B9\u6CD5\uFF1A${value}\uFF08\u53EF\u9009 browser\u3001password\uFF09`);
|
|
3125
|
+
}
|
|
3126
|
+
return value;
|
|
3127
|
+
}
|
|
3128
|
+
function lanhuTimeout(value) {
|
|
3129
|
+
const seconds = Number(value);
|
|
3130
|
+
if (!Number.isInteger(seconds) || seconds < 10 || seconds > 3600) {
|
|
3131
|
+
throw new CliError("invalid_argument", `\u65E0\u6548\u7684 timeout\uFF1A${value}\uFF08\u5FC5\u987B\u662F 10 \u5230 3600 \u7684\u6574\u6570\u79D2\uFF09`);
|
|
3132
|
+
}
|
|
3133
|
+
return seconds;
|
|
3134
|
+
}
|
|
3135
|
+
function lanhuAuthService(dependencies) {
|
|
3136
|
+
return (dependencies.createLanhuAuthService ?? buildLanhuAuthService)();
|
|
3137
|
+
}
|
|
3138
|
+
function errorMapperFor(service) {
|
|
3139
|
+
if (service === "lanhu") return lanhuToCliError;
|
|
3140
|
+
return (error) => toCliErrorFor(error, service === "omp" ? "OMP" : "GitLab");
|
|
3141
|
+
}
|
|
3142
|
+
function summarizeLanhuLogin(result) {
|
|
3143
|
+
const summary = {
|
|
3144
|
+
configured: true,
|
|
3145
|
+
verified: result.validation.state === "valid",
|
|
3146
|
+
service: "lanhu",
|
|
3147
|
+
target: LANHU_TARGET,
|
|
3148
|
+
source: result.metadata.method,
|
|
3149
|
+
method: result.metadata.method,
|
|
3150
|
+
lastLoginAt: result.metadata.lastLoginAt
|
|
3151
|
+
};
|
|
3152
|
+
const account = result.metadata.account ?? result.validation.account;
|
|
3153
|
+
if (account !== void 0) summary.account = account;
|
|
3154
|
+
if (result.metadata.browser !== void 0) summary.browser = result.metadata.browser;
|
|
3155
|
+
if (result.metadata.profile !== void 0) summary.profile = result.metadata.profile;
|
|
3156
|
+
return summary;
|
|
3157
|
+
}
|
|
3158
|
+
function summarizeLanhuStatus(metadata, validation) {
|
|
3159
|
+
const summary = {
|
|
3160
|
+
service: "lanhu",
|
|
3161
|
+
configured: metadata !== void 0,
|
|
3162
|
+
verified: validation.state === "valid",
|
|
3163
|
+
target: LANHU_TARGET,
|
|
3164
|
+
state: validation.state
|
|
3165
|
+
};
|
|
3166
|
+
if (validation.reason !== void 0) summary.reason = validation.reason;
|
|
3167
|
+
if (validation.account !== void 0) summary.currentAccount = validation.account;
|
|
3168
|
+
if (metadata !== void 0) {
|
|
3169
|
+
summary.method = metadata.method;
|
|
3170
|
+
summary.lastLoginAt = metadata.lastLoginAt;
|
|
3171
|
+
if (metadata.account !== void 0) summary.account = metadata.account;
|
|
3172
|
+
if (metadata.browser !== void 0) summary.browser = metadata.browser;
|
|
3173
|
+
if (metadata.profile !== void 0) summary.profile = metadata.profile;
|
|
3174
|
+
}
|
|
3175
|
+
return summary;
|
|
3176
|
+
}
|
|
3177
|
+
function formatLanhuStatus(data) {
|
|
3178
|
+
if (!data.configured) {
|
|
3179
|
+
const lines2 = ["\u672A\u767B\u5F55"];
|
|
3180
|
+
if (data.reason !== void 0) lines2.push(`\u72B6\u6001\uFF1A${data.state}\uFF08${data.reason}\uFF09`);
|
|
3181
|
+
else lines2.push(`\u72B6\u6001\uFF1A${data.state}`);
|
|
3182
|
+
return lines2;
|
|
3183
|
+
}
|
|
3184
|
+
const lines = [`\u767B\u5F55\u65B9\u5F0F\uFF1A${data.method ?? "-"}`];
|
|
3185
|
+
if (data.account !== void 0) lines.push(`\u8D26\u53F7\uFF1A${data.account}`);
|
|
3186
|
+
if (data.browser !== void 0) lines.push(`\u6D4F\u89C8\u5668\uFF1A${data.browser}`);
|
|
3187
|
+
if (data.profile !== void 0) lines.push(`\u6D4F\u89C8\u5668 profile\uFF1A${data.profile}`);
|
|
3188
|
+
lines.push(`\u6700\u8FD1\u767B\u5F55\uFF1A${data.lastLoginAt ?? "-"}`);
|
|
3189
|
+
lines.push(`\u72B6\u6001\uFF1A${data.state}`);
|
|
3190
|
+
if (data.currentAccount !== void 0) lines.push(`\u5F53\u524D\u8D26\u53F7\uFF1A${data.currentAccount}`);
|
|
3191
|
+
if (data.reason !== void 0) lines.push(`\u8BF4\u660E\uFF1A${data.reason}`);
|
|
3192
|
+
return lines;
|
|
3193
|
+
}
|
|
3194
|
+
function renderLogin(data) {
|
|
3195
|
+
if (data.service === "lanhu") {
|
|
3196
|
+
const account = data.account !== void 0 ? `\uFF08\u8D26\u53F7\uFF1A${data.account}\uFF09` : "";
|
|
3197
|
+
return `\u84DD\u6E56\u767B\u5F55\u6210\u529F${account}`;
|
|
3198
|
+
}
|
|
3199
|
+
if (data.service === "gitlab") {
|
|
3200
|
+
return `GitLab \u767B\u5F55\u6210\u529F
|
|
3201
|
+
\u51ED\u636E\uFF1Aglab Keyring
|
|
3202
|
+
\u76EE\u6807\uFF1A${data.target}`;
|
|
3203
|
+
}
|
|
3204
|
+
return `OMP \u767B\u5F55\u6210\u529F
|
|
3205
|
+
\u51ED\u636E\uFF1Aaccess token \u7F13\u5B58
|
|
3206
|
+
\u76EE\u6807\uFF1A${data.target}`;
|
|
3207
|
+
}
|
|
3208
|
+
function renderStatus(data) {
|
|
3209
|
+
if (data.service === "lanhu") return formatLanhuStatus(data).join("\n");
|
|
3210
|
+
const name = data.service === "gitlab" ? "GitLab" : "OMP";
|
|
3211
|
+
if (!data.configured) return `\u672A\u914D\u7F6E ${name} \u51ED\u636E
|
|
3212
|
+
\u76EE\u6807\uFF1A${data.target}`;
|
|
3213
|
+
const source = data.source === "glab" ? "glab" : data.source === "environment" ? "\u73AF\u5883\u53D8\u91CF" : "access token \u7F13\u5B58";
|
|
3214
|
+
return `\u5DF2\u914D\u7F6E\u5E76\u9A8C\u8BC1 ${name} \u51ED\u636E
|
|
3215
|
+
\u6765\u6E90\uFF1A${source}
|
|
3216
|
+
\u76EE\u6807\uFF1A${data.target}`;
|
|
3217
|
+
}
|
|
3218
|
+
function renderLogout(data) {
|
|
3219
|
+
if (data.service === "lanhu") return "\u84DD\u6E56\u672C\u5730\u767B\u5F55\u4FE1\u606F\u5DF2\u6E05\u7406\uFF08\u4EC5\u5F71\u54CD\u672C\u673A\uFF09";
|
|
3220
|
+
const name = data.service === "gitlab" ? "GitLab" : "OMP";
|
|
3221
|
+
if (data.environmentCredentialStillActive) {
|
|
3222
|
+
return `${name} access token \u5DF2\u5220\u9664\uFF0C\u4F46\u73AF\u5883\u53D8\u91CF\u4E2D\u7684\u51ED\u636E\u4ECD\u7136\u6709\u6548`;
|
|
3223
|
+
}
|
|
3224
|
+
return `${name} \u767B\u5F55\u51ED\u636E\u5DF2\u5220\u9664`;
|
|
3225
|
+
}
|
|
3226
|
+
async function hiddenQuestion(label) {
|
|
3227
|
+
const input2 = process.stdin;
|
|
3228
|
+
const output = process.stderr;
|
|
3229
|
+
if (!input2.isTTY || typeof input2.setRawMode !== "function") {
|
|
3230
|
+
throw new CliError("invalid_argument", "OMP \u767B\u5F55\u9700\u8981\u4EA4\u4E92\u5F0F\u7EC8\u7AEF");
|
|
3231
|
+
}
|
|
3232
|
+
output.write(label);
|
|
3233
|
+
emitKeypressEvents(input2);
|
|
3234
|
+
const wasRaw = input2.isRaw;
|
|
3235
|
+
input2.setRawMode(true);
|
|
3236
|
+
input2.resume();
|
|
3237
|
+
return new Promise((resolve2, reject) => {
|
|
3238
|
+
let value = "";
|
|
3239
|
+
const finish = (error) => {
|
|
3240
|
+
input2.off("keypress", onKeypress);
|
|
3241
|
+
input2.setRawMode(Boolean(wasRaw));
|
|
3242
|
+
input2.pause();
|
|
3243
|
+
output.write("\n");
|
|
3244
|
+
if (error) reject(error);
|
|
3245
|
+
else resolve2(value);
|
|
3246
|
+
};
|
|
3247
|
+
const onKeypress = (text, key) => {
|
|
3248
|
+
if (key.ctrl && key.name === "c") {
|
|
3249
|
+
finish(new CliError("invalid_argument", "OMP \u767B\u5F55\u5DF2\u53D6\u6D88"));
|
|
3250
|
+
} else if (key.name === "return" || key.name === "enter") {
|
|
3251
|
+
finish();
|
|
3252
|
+
} else if (key.name === "backspace") {
|
|
3253
|
+
const characters = Array.from(value);
|
|
3254
|
+
if (characters.length > 0) {
|
|
3255
|
+
characters.pop();
|
|
3256
|
+
value = characters.join("");
|
|
3257
|
+
output.write("\b \b");
|
|
3258
|
+
}
|
|
3259
|
+
} else if (text && !key.ctrl && !key.meta) {
|
|
3260
|
+
value += text;
|
|
3261
|
+
output.write("*");
|
|
3262
|
+
}
|
|
3263
|
+
};
|
|
3264
|
+
input2.on("keypress", onKeypress);
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
async function promptOmpCredentials() {
|
|
3268
|
+
if (!process.stdin.isTTY) throw new CliError("invalid_argument", "OMP \u767B\u5F55\u9700\u8981\u4EA4\u4E92\u5F0F\u7EC8\u7AEF");
|
|
3269
|
+
const readline = createInterface({ input: process.stdin, output: process.stderr });
|
|
3270
|
+
let username;
|
|
3271
|
+
try {
|
|
3272
|
+
username = (await readline.question("OMP \u7528\u6237\u540D: ")).trim();
|
|
3273
|
+
} finally {
|
|
3274
|
+
readline.close();
|
|
3275
|
+
}
|
|
3276
|
+
if (!username) throw new CliError("invalid_argument", "OMP \u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A");
|
|
3277
|
+
const password2 = await hiddenQuestion("OMP \u5BC6\u7801: ");
|
|
3278
|
+
if (!password2) throw new CliError("invalid_argument", "OMP \u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A");
|
|
3279
|
+
return { username, password: password2 };
|
|
3280
|
+
}
|
|
3281
|
+
async function promptLanhuCredentials() {
|
|
3282
|
+
if (!process.stdin.isTTY) {
|
|
3283
|
+
throw new CliError(
|
|
3284
|
+
"invalid_argument",
|
|
3285
|
+
"\u84DD\u6E56\u5BC6\u7801\u767B\u5F55\u9700\u8981\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\uFF0C\u8BF7\u5728\u6709\u4EA4\u4E92\u7684\u7EC8\u7AEF\u6267\u884C\uFF0C\u6216\u6539\u7528 --method browser\uFF08\u53BB\u6389 --method password\uFF09"
|
|
3286
|
+
);
|
|
3287
|
+
}
|
|
3288
|
+
const account = await input({
|
|
3289
|
+
message: "\u84DD\u6E56\u8D26\u53F7\uFF1A",
|
|
3290
|
+
validate: (value) => value.trim() ? true : "\u8D26\u53F7\u4E0D\u80FD\u4E3A\u7A7A"
|
|
3291
|
+
});
|
|
3292
|
+
const secret = await password({ message: "\u84DD\u6E56\u5BC6\u7801\uFF1A", mask: "*" });
|
|
3293
|
+
return { account: account.trim(), password: secret };
|
|
3294
|
+
}
|
|
3295
|
+
async function execute(name, command, action, render, dependencies, mapError) {
|
|
3296
|
+
const startedAt = Date.now();
|
|
3297
|
+
const requestId = randomUUID5();
|
|
3298
|
+
let output = "auto";
|
|
3299
|
+
try {
|
|
3300
|
+
output = outputMode(command, dependencies);
|
|
3301
|
+
const data = await action();
|
|
3302
|
+
printResult(success(data, name, startedAt, requestId), output, render, dependencies.writer);
|
|
3303
|
+
} catch (error) {
|
|
3304
|
+
printResult(failure(mapError(error), name, startedAt, requestId), output, render, dependencies.writer);
|
|
3305
|
+
process.exitCode = 1;
|
|
3306
|
+
}
|
|
3307
|
+
}
|
|
3308
|
+
function registerAuthCommands(program, dependencies = defaultDependencies2) {
|
|
3309
|
+
const auth = program.command("auth").description("\u7BA1\u7406 GitLab\u3001OMP \u548C\u84DD\u6E56\u8BA4\u8BC1\u51ED\u636E");
|
|
3310
|
+
auth.command("login").description("\u767B\u5F55 GitLab\u3001OMP \u6216\u84DD\u6E56").argument("[service]", "\u670D\u52A1\u540D\u79F0\uFF1Agitlab\u3001omp \u6216 lanhu", "gitlab").option("--browser [browser]", "GitLab \u4F7F\u7528\u6D4F\u89C8\u5668\u767B\u5F55\uFF1Blanhu \u65F6\u6307\u5B9A\u6D4F\u89C8\u5668\u540D\uFF1Achrome\u3001edge\u3001brave\u3001arc \u6216 chromium").option("--method <method>", "\u4EC5 lanhu\uFF1A\u767B\u5F55\u65B9\u5F0F browser \u6216 password", "browser").option("--profile <profile>", "\u4EC5 lanhu\uFF1A\u6D4F\u89C8\u5668 profile \u540D").option("--force-login", "\u4EC5 lanhu\uFF1A\u8DF3\u8FC7\u73B0\u6709 Cookie\uFF0C\u76F4\u63A5\u6253\u5F00\u72EC\u7ACB\u767B\u5F55\u7A97\u53E3", false).option("--timeout <seconds>", "\u4EC5 lanhu\uFF1A\u6D4F\u89C8\u5668\u767B\u5F55\u7B49\u5F85\u79D2\u6570\uFF0810-3600\uFF09", "300").action(async (service, options, command) => {
|
|
3311
|
+
await execute(
|
|
3312
|
+
"auth.login",
|
|
3313
|
+
command,
|
|
3314
|
+
async () => {
|
|
3315
|
+
ensureService(service);
|
|
3316
|
+
if (service === "gitlab") {
|
|
3317
|
+
if (typeof options.browser === "string") {
|
|
3318
|
+
throw new CliError("invalid_argument", "-browser \u4E0D\u63A5\u53D7\u53D6\u503C\uFF1BGitLab \u6D4F\u89C8\u5668\u767B\u5F55\u8BF7\u76F4\u63A5\u4F7F\u7528 -browser");
|
|
3319
|
+
}
|
|
3320
|
+
const host = gitlabHost(dependencies.env);
|
|
3321
|
+
const args = ["auth", "login", "--hostname", host, "--use-keyring"];
|
|
3322
|
+
if (options.browser) args.push("--web");
|
|
3323
|
+
(dependencies.glabInteractive ?? runGlabInteractive)(args, {
|
|
3324
|
+
env: gitlabEnvironment(dependencies.env)
|
|
3325
|
+
});
|
|
3326
|
+
return { configured: true, verified: true, service, target: host, source: "glab" };
|
|
3327
|
+
}
|
|
3328
|
+
if (service === "omp") {
|
|
3329
|
+
if (options.browser) {
|
|
3330
|
+
throw new CliError("invalid_argument", "-browser \u4EC5\u9002\u7528\u4E8E GitLab \u6216\u84DD\u6E56\u767B\u5F55");
|
|
3331
|
+
}
|
|
3332
|
+
const credentials = await (dependencies.ompPrompt ?? promptOmpCredentials)();
|
|
3333
|
+
const target = ompBaseUrl(command, dependencies.env);
|
|
3334
|
+
const tokenCache = dependencies.ompTokenCache ?? new FileOmpTokenCache();
|
|
3335
|
+
const client = (dependencies.createOmpClient ?? ((clientOptions) => new OmpClient(clientOptions)))({
|
|
3336
|
+
baseUrl: target,
|
|
3337
|
+
username: credentials.username,
|
|
3338
|
+
password: credentials.password,
|
|
3339
|
+
tokenCache
|
|
3340
|
+
});
|
|
3341
|
+
await client.authenticate();
|
|
3342
|
+
return {
|
|
3343
|
+
configured: true,
|
|
3344
|
+
verified: true,
|
|
3345
|
+
service,
|
|
3346
|
+
target,
|
|
3347
|
+
source: "access_token"
|
|
3348
|
+
};
|
|
3349
|
+
}
|
|
3350
|
+
const authService = lanhuAuthService(dependencies);
|
|
3351
|
+
const method = lanhuMethod(options.method);
|
|
3352
|
+
if (method === "password") {
|
|
3353
|
+
const credentials = await (dependencies.lanhuPrompt ?? promptLanhuCredentials)();
|
|
3354
|
+
return summarizeLanhuLogin(
|
|
3355
|
+
await authService.loginPassword({
|
|
3356
|
+
account: credentials.account.trim(),
|
|
3357
|
+
password: credentials.password
|
|
3358
|
+
})
|
|
3359
|
+
);
|
|
3360
|
+
}
|
|
3361
|
+
const browser = lanhuBrowser(
|
|
3362
|
+
typeof options.browser === "string" ? options.browser : "chrome"
|
|
3363
|
+
);
|
|
3364
|
+
const timeoutMs = lanhuTimeout(options.timeout) * 1e3;
|
|
3365
|
+
const browserOptions = {
|
|
3366
|
+
browser,
|
|
3367
|
+
forceLogin: Boolean(options.forceLogin),
|
|
3368
|
+
timeoutMs,
|
|
3369
|
+
interactive: true,
|
|
3370
|
+
...options.profile !== void 0 && options.profile !== "" ? { profile: options.profile } : {}
|
|
3371
|
+
};
|
|
3372
|
+
return summarizeLanhuLogin(await authService.loginBrowser(browserOptions));
|
|
3373
|
+
},
|
|
3374
|
+
renderLogin,
|
|
3375
|
+
dependencies,
|
|
3376
|
+
errorMapperFor(service)
|
|
3377
|
+
);
|
|
3378
|
+
});
|
|
3379
|
+
auth.command("status").description("\u67E5\u770B GitLab\u3001OMP \u6216\u84DD\u6E56\u8BA4\u8BC1\u72B6\u6001\uFF0C\u4E0D\u663E\u793A\u654F\u611F\u51ED\u636E").argument("[service]", "\u670D\u52A1\u540D\u79F0\uFF1Agitlab\u3001omp \u6216 lanhu", "gitlab").action(async (service, _options, command) => {
|
|
3380
|
+
await execute(
|
|
3381
|
+
"auth.status",
|
|
3382
|
+
command,
|
|
3383
|
+
async () => {
|
|
3384
|
+
ensureService(service);
|
|
3385
|
+
if (service === "lanhu") {
|
|
3386
|
+
const { metadata, validation } = await lanhuAuthService(dependencies).status();
|
|
3387
|
+
return summarizeLanhuStatus(metadata, validation);
|
|
3388
|
+
}
|
|
3389
|
+
if (service === "gitlab") {
|
|
3390
|
+
const host = gitlabHost(dependencies.env);
|
|
3391
|
+
try {
|
|
3392
|
+
await (dependencies.glabRunner ?? defaultGlabRunner)(["auth", "status", "--hostname", host], {
|
|
3393
|
+
env: gitlabEnvironment(dependencies.env)
|
|
3394
|
+
});
|
|
3395
|
+
return { configured: true, verified: true, source: "glab", service, target: host };
|
|
3396
|
+
} catch (error) {
|
|
3397
|
+
const cliError = toCliErrorFor(error, "GitLab");
|
|
3398
|
+
if (cliError.code === "not_authenticated") {
|
|
3399
|
+
return { configured: false, verified: false, source: "none", service, target: host };
|
|
3400
|
+
}
|
|
3401
|
+
throw cliError;
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
const tokenCache = dependencies.ompTokenCache ?? new FileOmpTokenCache();
|
|
3405
|
+
const target = ompBaseUrl(command, dependencies.env);
|
|
3406
|
+
const environmentUsername = dependencies.env.OMP_MCP_USERNAME;
|
|
3407
|
+
const environmentPassword = dependencies.env.OMP_MCP_PASSWORD;
|
|
3408
|
+
if (environmentUsername || environmentPassword) {
|
|
3409
|
+
if (!environmentUsername || !environmentPassword) {
|
|
3410
|
+
throw new CliError("not_authenticated", "OMP \u73AF\u5883\u53D8\u91CF\u914D\u7F6E\u4E0D\u5B8C\u6574");
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
const username = environmentUsername ?? await tokenCache.getActiveUsername();
|
|
3414
|
+
if (!username) {
|
|
3415
|
+
return { configured: false, verified: false, source: "none", service, target };
|
|
3416
|
+
}
|
|
3417
|
+
const source = environmentUsername && environmentPassword ? "environment" : "access_token";
|
|
3418
|
+
const client = (dependencies.createOmpClient ?? ((clientOptions) => new OmpClient(clientOptions)))({
|
|
3419
|
+
baseUrl: target,
|
|
3420
|
+
username,
|
|
3421
|
+
...environmentPassword ? { password: environmentPassword } : {},
|
|
3422
|
+
tokenCache
|
|
3423
|
+
});
|
|
3424
|
+
await client.listEnvironments();
|
|
3425
|
+
return { configured: true, verified: true, source, service, target };
|
|
3426
|
+
},
|
|
3427
|
+
renderStatus,
|
|
3428
|
+
dependencies,
|
|
3429
|
+
errorMapperFor(service)
|
|
3430
|
+
);
|
|
3431
|
+
});
|
|
3432
|
+
auth.command("refresh").description("\u5237\u65B0/\u6062\u590D\u84DD\u6E56\u767B\u5F55\u6001").argument("[service]", "\u670D\u52A1\u540D\u79F0\uFF1Alanhu", "lanhu").action(async (service, _options, command) => {
|
|
3433
|
+
await execute(
|
|
3434
|
+
"auth.refresh",
|
|
3435
|
+
command,
|
|
3436
|
+
async () => {
|
|
3437
|
+
if (service !== "lanhu") {
|
|
3438
|
+
throw new CliError("invalid_argument", "auth refresh \u76EE\u524D\u4EC5\u652F\u6301 lanhu");
|
|
3439
|
+
}
|
|
3440
|
+
const interactive = Boolean(process.stdin.isTTY);
|
|
3441
|
+
await lanhuAuthService(dependencies).refresh(interactive);
|
|
3442
|
+
return { service: "lanhu", refreshed: true, target: LANHU_TARGET, interactive };
|
|
3443
|
+
},
|
|
3444
|
+
() => "\u84DD\u6E56\u767B\u5F55\u6001\u5DF2\u5237\u65B0",
|
|
3445
|
+
dependencies,
|
|
3446
|
+
errorMapperFor(service)
|
|
3447
|
+
);
|
|
3448
|
+
});
|
|
3449
|
+
auth.command("logout").description("\u5220\u9664 GitLab\u3001OMP \u6216\u84DD\u6E56\u767B\u5F55\u51ED\u636E").argument("[service]", "\u670D\u52A1\u540D\u79F0\uFF1Agitlab\u3001omp \u6216 lanhu", "gitlab").action(async (service, _options, command) => {
|
|
3450
|
+
await execute(
|
|
3451
|
+
"auth.logout",
|
|
3452
|
+
command,
|
|
3453
|
+
async () => {
|
|
3454
|
+
ensureService(service);
|
|
3455
|
+
if (service === "lanhu") {
|
|
3456
|
+
await lanhuAuthService(dependencies).logout();
|
|
3457
|
+
return {
|
|
3458
|
+
service,
|
|
3459
|
+
loggedOut: true,
|
|
3460
|
+
target: LANHU_TARGET,
|
|
3461
|
+
environmentCredentialStillActive: false
|
|
3462
|
+
};
|
|
3463
|
+
}
|
|
3464
|
+
if (service === "gitlab") {
|
|
3465
|
+
const host = gitlabHost(dependencies.env);
|
|
3466
|
+
await (dependencies.glabRunner ?? defaultGlabRunner)(["auth", "logout", "--hostname", host], {
|
|
3467
|
+
env: gitlabEnvironment(dependencies.env)
|
|
3468
|
+
});
|
|
3469
|
+
return {
|
|
3470
|
+
service,
|
|
3471
|
+
loggedOut: true,
|
|
3472
|
+
target: host,
|
|
3473
|
+
environmentCredentialStillActive: Boolean(
|
|
3474
|
+
dependencies.env.GITLAB_TOKEN ?? dependencies.env.GITLAB_ACCESS_TOKEN ?? dependencies.env.OAUTH_TOKEN
|
|
3475
|
+
)
|
|
3476
|
+
};
|
|
3477
|
+
}
|
|
3478
|
+
const tokenCache = dependencies.ompTokenCache ?? new FileOmpTokenCache();
|
|
3479
|
+
const activeUsername = await tokenCache.getActiveUsername();
|
|
3480
|
+
if (activeUsername) await tokenCache.remove(activeUsername);
|
|
3481
|
+
await tokenCache.clearActiveUsername();
|
|
3482
|
+
return {
|
|
3483
|
+
service,
|
|
3484
|
+
loggedOut: true,
|
|
3485
|
+
target: ompBaseUrl(command, dependencies.env),
|
|
3486
|
+
environmentCredentialStillActive: Boolean(
|
|
3487
|
+
dependencies.env.OMP_MCP_USERNAME || dependencies.env.OMP_MCP_PASSWORD
|
|
3488
|
+
)
|
|
3489
|
+
};
|
|
3490
|
+
},
|
|
3491
|
+
renderLogout,
|
|
3492
|
+
dependencies,
|
|
3493
|
+
errorMapperFor(service)
|
|
3494
|
+
);
|
|
3495
|
+
});
|
|
3496
|
+
}
|
|
3497
|
+
|
|
3498
|
+
// src/commands/mr.ts
|
|
3499
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
3500
|
+
import { z as z3 } from "zod";
|
|
3501
|
+
|
|
3502
|
+
// src/adapters/git/local.ts
|
|
3503
|
+
import { execFile as execFile2 } from "child_process";
|
|
3504
|
+
import { promisify as promisify2 } from "util";
|
|
3505
|
+
var execFileAsync2 = promisify2(execFile2);
|
|
3506
|
+
var defaultGitRunner = async (args, options = {}) => {
|
|
3507
|
+
try {
|
|
3508
|
+
const { stdout, stderr } = await execFileAsync2("git", args, {
|
|
3509
|
+
cwd: options.cwd,
|
|
3510
|
+
encoding: "utf8",
|
|
3511
|
+
maxBuffer: 10 * 1024 * 1024
|
|
3512
|
+
});
|
|
3513
|
+
return { stdout, stderr };
|
|
3514
|
+
} catch (error) {
|
|
3515
|
+
const detail = error;
|
|
3516
|
+
if (detail.code === "ENOENT") {
|
|
3517
|
+
throw new CliError("invalid_argument", "\u672A\u627E\u5230 git \u547D\u4EE4", { cause: error });
|
|
3518
|
+
}
|
|
3519
|
+
throw new CliError("invalid_argument", "Git \u4ED3\u5E93\u4FE1\u606F\u8BFB\u53D6\u5931\u8D25", {
|
|
3520
|
+
details: `${detail.stderr ?? ""}
|
|
3521
|
+
${detail.message ?? ""}`.trim(),
|
|
3522
|
+
cause: error
|
|
3523
|
+
});
|
|
3524
|
+
}
|
|
3525
|
+
};
|
|
3526
|
+
var LocalGitRepository = class {
|
|
3527
|
+
constructor(runner = defaultGitRunner, options = {}) {
|
|
3528
|
+
this.runner = runner;
|
|
3529
|
+
this.options = options;
|
|
3530
|
+
}
|
|
3531
|
+
runner;
|
|
3532
|
+
options;
|
|
3533
|
+
async currentBranch() {
|
|
3534
|
+
const result = await this.runner(["branch", "--show-current"], this.options);
|
|
3535
|
+
const branch = result.stdout.trim();
|
|
3536
|
+
if (!branch) throw new CliError("invalid_argument", "\u5F53\u524D\u5904\u4E8E detached HEAD\uFF0C\u8BF7\u901A\u8FC7 --source \u6307\u5B9A\u6E90\u5206\u652F");
|
|
3537
|
+
return branch;
|
|
3538
|
+
}
|
|
3539
|
+
async commitSubjects(target, source) {
|
|
3540
|
+
let result;
|
|
3541
|
+
try {
|
|
3542
|
+
result = await this.runner(
|
|
3543
|
+
["log", "--pretty=format:%s", `${target}..${source}`],
|
|
3544
|
+
this.options
|
|
3545
|
+
);
|
|
3546
|
+
} catch (error) {
|
|
3547
|
+
const remoteBranches = await this.runner(["branch", "--remotes", "--list", `*/${target}`], this.options);
|
|
3548
|
+
const candidates = remoteBranches.stdout.split("\n").map((branch) => branch.trim().replace(/^\*\s*/, "")).filter((branch) => branch.endsWith(`/${target}`));
|
|
3549
|
+
if (candidates.length === 0) {
|
|
3550
|
+
throw new CliError("invalid_argument", `\u76EE\u6807\u5206\u652F\u5728\u672C\u5730\u53CA\u8FDC\u7AEF\u8DDF\u8E2A\u5F15\u7528\u4E2D\u5747\u4E0D\u5B58\u5728\uFF1A${target}`, {
|
|
3551
|
+
details: error
|
|
3552
|
+
});
|
|
3553
|
+
}
|
|
3554
|
+
if (candidates.length > 1) {
|
|
3555
|
+
throw new CliError("invalid_argument", `\u76EE\u6807\u5206\u652F\u5B58\u5728\u4E8E\u591A\u4E2A\u8FDC\u7AEF\uFF0C\u8BF7\u4F7F\u7528\u5B8C\u6574 Git ref\uFF1A${target}`, {
|
|
3556
|
+
details: candidates
|
|
3557
|
+
});
|
|
3558
|
+
}
|
|
3559
|
+
result = await this.runner(
|
|
3560
|
+
["log", "--pretty=format:%s", `${String(candidates[0])}..${source}`],
|
|
3561
|
+
this.options
|
|
3562
|
+
);
|
|
3563
|
+
}
|
|
3564
|
+
return result.stdout.split("\n").map((subject) => subject.trim()).filter(Boolean);
|
|
3565
|
+
}
|
|
3566
|
+
async commitAll(message) {
|
|
3567
|
+
const status = await this.runner(["status", "--short"], this.options);
|
|
3568
|
+
if (!status.stdout.trim()) return false;
|
|
3569
|
+
await this.runner(["add", "--all"], this.options);
|
|
3570
|
+
await this.runner(["commit", "--message", message], this.options);
|
|
3571
|
+
return true;
|
|
3572
|
+
}
|
|
3573
|
+
async pushBranch(source) {
|
|
3574
|
+
let remote;
|
|
3575
|
+
try {
|
|
3576
|
+
const upstream = await this.runner(
|
|
3577
|
+
["rev-parse", "--abbrev-ref", "--symbolic-full-name", `${source}@{upstream}`],
|
|
3578
|
+
this.options
|
|
3579
|
+
);
|
|
3580
|
+
remote = upstream.stdout.trim().split("/")[0];
|
|
3581
|
+
} catch {
|
|
3582
|
+
const remoteBranches = await this.runner(["branch", "--remotes", "--list", `*/${source}`], this.options);
|
|
3583
|
+
const candidates = remoteBranches.stdout.split("\n").map((line) => line.trim().replace(/^\*\s*/, "")).filter((line) => line.endsWith(`/${source}`)).map((line) => line.slice(0, -(source.length + 1)));
|
|
3584
|
+
if (new Set(candidates).size === 1) remote = candidates[0];
|
|
3585
|
+
if (!remote) {
|
|
3586
|
+
const remotes = await this.runner(["remote"], this.options);
|
|
3587
|
+
const names = remotes.stdout.split("\n").map((name) => name.trim()).filter(Boolean);
|
|
3588
|
+
if (names.length === 1) remote = names[0];
|
|
3589
|
+
}
|
|
3590
|
+
}
|
|
3591
|
+
if (!remote) {
|
|
3592
|
+
throw new CliError("invalid_argument", "\u65E0\u6CD5\u552F\u4E00\u786E\u5B9A\u6E90\u5206\u652F\u5BF9\u5E94\u7684\u8FDC\u7AEF\uFF0C\u8BF7\u5148\u4E3A\u5F53\u524D\u5206\u652F\u8BBE\u7F6E upstream");
|
|
3593
|
+
}
|
|
3594
|
+
await this.runner(["push", "--set-upstream", remote, `${source}:${source}`], this.options);
|
|
3595
|
+
return remote;
|
|
3596
|
+
}
|
|
3597
|
+
};
|
|
3598
|
+
|
|
3599
|
+
// src/domain/mr-create.ts
|
|
3600
|
+
var ACTION_PATTERN = /(?:^|[/_])(feat|fix|hotfix|release|prod|dev|test|conflict)(?=[/_]|$)/;
|
|
3601
|
+
var VERSION_PATTERN = /\d+\.\d+\.x/;
|
|
3602
|
+
var DT_COMMON_VERSION_PATTERN = /\d+\.x\.\d+/;
|
|
3603
|
+
function parseDtBranch(input2) {
|
|
3604
|
+
const branch = input2.replace(/^remotes\/[^/]+\//, "");
|
|
3605
|
+
const slash = branch.indexOf("/");
|
|
3606
|
+
if (slash <= 0) throw new CliError("invalid_argument", `\u65E0\u6CD5\u4ECE\u5206\u652F\u540D\u89E3\u6790\u9879\u76EE\uFF1A${branch}`);
|
|
3607
|
+
const project = branch.slice(0, slash);
|
|
3608
|
+
const actionMatch = ACTION_PATTERN.exec(branch);
|
|
3609
|
+
if (!actionMatch?.[1]) throw new CliError("invalid_argument", `\u65E0\u6CD5\u4ECE\u5206\u652F\u540D\u89E3\u6790\u64CD\u4F5C\u7C7B\u578B\uFF1A${branch}`);
|
|
3610
|
+
const action = actionMatch[1];
|
|
3611
|
+
const versionMatch = project === "dt-common" && action === "dev" ? DT_COMMON_VERSION_PATTERN.exec(branch) : VERSION_PATTERN.exec(branch);
|
|
3612
|
+
if (!versionMatch) throw new CliError("invalid_argument", `\u65E0\u6CD5\u4ECE\u5206\u652F\u540D\u89E3\u6790\u7248\u672C\uFF1A${branch}`);
|
|
3613
|
+
const suffix = branch.slice((versionMatch.index ?? 0) + versionMatch[0].length).replace(/^_+/, "");
|
|
3614
|
+
const uuid = suffix || void 0;
|
|
3615
|
+
const pieces = suffix ? suffix.split("_") : [];
|
|
3616
|
+
const numeric = [...pieces].reverse().find((piece) => /^\d+$/.test(piece));
|
|
3617
|
+
const parsedBugId = numeric ? Number(numeric) : void 0;
|
|
3618
|
+
const bugId = parsedBugId && parsedBugId > 6e4 ? parsedBugId : void 0;
|
|
3619
|
+
const customMark = bugId && pieces.length > 1 ? pieces[pieces.indexOf(String(bugId)) - 1] : void 0;
|
|
3620
|
+
return {
|
|
3621
|
+
branch,
|
|
3622
|
+
project,
|
|
3623
|
+
action,
|
|
3624
|
+
version: versionMatch[0],
|
|
3625
|
+
...uuid ? { uuid } : {},
|
|
3626
|
+
...bugId ? { bugId } : {},
|
|
3627
|
+
...customMark && !/^\d+$/.test(customMark) ? { customMark } : {}
|
|
3628
|
+
};
|
|
3629
|
+
}
|
|
3630
|
+
function bugIdsFromCommits(commits) {
|
|
3631
|
+
const result = [];
|
|
3632
|
+
for (const commit of commits) {
|
|
3633
|
+
for (const match of commit.matchAll(/#(\d+)/g)) {
|
|
3634
|
+
const id = Number(match[1]);
|
|
3635
|
+
if (id > 6e4 && !result.includes(id)) result.push(id);
|
|
3636
|
+
}
|
|
3637
|
+
}
|
|
3638
|
+
return result;
|
|
3639
|
+
}
|
|
3640
|
+
function changeType(action, commits) {
|
|
3641
|
+
const hasFixWithBug = commits.some(
|
|
3642
|
+
(subject) => /^(?:fix|hotfix)(?:\([^)]*\))?:/i.test(subject) && /#\d+/.test(subject)
|
|
3643
|
+
);
|
|
3644
|
+
if (hasFixWithBug || action === "fix" || action === "hotfix") return "fix";
|
|
3645
|
+
if (action === "conflict") return "conflict";
|
|
3646
|
+
return "feat";
|
|
3647
|
+
}
|
|
3648
|
+
function titleBody(commits, branch, bugIds) {
|
|
3649
|
+
if (commits.length === 1) return commits[0];
|
|
3650
|
+
if (commits.length > 1) {
|
|
3651
|
+
const first = commits[0];
|
|
3652
|
+
return `${first} (+${commits.length - 1} commits)`;
|
|
3653
|
+
}
|
|
3654
|
+
const bug = bugIds[0] ?? branch.bugId;
|
|
3655
|
+
return bug ? `${branch.action}(${branch.project}): #${bug}` : `${branch.action}(${branch.project}): ${branch.uuid ?? branch.version}`;
|
|
3656
|
+
}
|
|
3657
|
+
function template(type, bugIds, cause, solution) {
|
|
3658
|
+
const links = bugIds.map((id) => `- http://zenpms.dtstack.cn/zentao/bug-view-${id}.html`).join("\n");
|
|
3659
|
+
return [
|
|
3660
|
+
"### \u63D0\u4EA4\u7684\u53D8\u66F4\u7C7B\u578B\u662F...",
|
|
3661
|
+
`- [${type === "feat" ? "x" : " "}] \u6DFB\u52A0\u65B0\u529F\u80FD`,
|
|
3662
|
+
`- [${type === "fix" ? "x" : " "}] \u4FEE\u590Dbug`,
|
|
3663
|
+
"- [ ] \u4F18\u5316\u4EE3\u7801\u98CE\u683C",
|
|
3664
|
+
"- [ ] \u4EE3\u7801\u91CD\u6784",
|
|
3665
|
+
"- [ ] \u589E\u52A0\u5355\u5143\u6D4B\u8BD5",
|
|
3666
|
+
"- [ ] \u589E\u52A0\u4F9D\u8D56\u5E93/\u5DE5\u5177",
|
|
3667
|
+
`- [${type === "conflict" ? "x" : " "}] \u89E3\u51B3\u51B2\u7A81\u540E\u9A8C\u8BC1CI`,
|
|
3668
|
+
"",
|
|
3669
|
+
"### \u76F8\u5173\u94FE\u63A5",
|
|
3670
|
+
links,
|
|
3671
|
+
"",
|
|
3672
|
+
"### \u9700\u6C42\u63CF\u8FF0\u548C\u89E3\u51B3\u65B9\u6848",
|
|
3673
|
+
"#### \u63CF\u8FF0",
|
|
3674
|
+
cause ? `- ${cause}` : "-",
|
|
3675
|
+
"",
|
|
3676
|
+
"#### \u89E3\u51B3\u65B9\u6848",
|
|
3677
|
+
solution ? `- ${solution}` : "-",
|
|
3678
|
+
"",
|
|
3679
|
+
"### \u81EA\u67E5\u6E05\u5355",
|
|
3680
|
+
"- [ ] \u4EE3\u7801\u9075\u5FAA\u8FD9\u4E2A\u9879\u76EE\u7684\u98CE\u683C\u6307\u5357",
|
|
3681
|
+
"- [ ] \u5BF9\u4EE3\u7801\u8FDB\u884C\u4E86\u81EA\u6211\u5BA1\u67E5",
|
|
3682
|
+
"- [ ] \u5DF2\u7ECF\u5728\u96BE\u4EE5\u7406\u89E3\u7684\u4EE3\u7801\u5904\u505A\u4E86\u76F8\u5173\u6CE8\u91CA",
|
|
3683
|
+
"- [ ] \u66F4\u6539\u4E0D\u4F1A\u4EA7\u751F\u65B0\u7684\u8B66\u544A",
|
|
3684
|
+
"- [ ] \u4EFB\u4F55\u4F9D\u8D56\u66F4\u6539\u90FD\u5DF2\u5408\u5E76\u5E76\u53D1\u5E03\u5728\u4E0B\u6E38\u6A21\u5757\u4E2D"
|
|
3685
|
+
].join("\n");
|
|
3686
|
+
}
|
|
3687
|
+
function buildMergeRequestDraft(options) {
|
|
3688
|
+
const selected = parseDtBranch(options.source);
|
|
3689
|
+
const releaseToTest = Boolean(options.releaseToTest);
|
|
3690
|
+
if (releaseToTest && selected.action !== "test") {
|
|
3691
|
+
throw new CliError("invalid_argument", "-release-to-test \u53EA\u80FD\u7528\u4E8E test \u5206\u652F");
|
|
3692
|
+
}
|
|
3693
|
+
if (!options.target?.trim()) {
|
|
3694
|
+
throw new CliError("invalid_argument", "\u521B\u5EFA MR \u5FC5\u987B\u663E\u5F0F\u4F20\u5165 -target <branch>");
|
|
3695
|
+
}
|
|
3696
|
+
const sourceBranch = releaseToTest ? `${selected.project}/release_${selected.version}` : selected.branch;
|
|
3697
|
+
const targetBranch = options.target.trim();
|
|
3698
|
+
const commitBugIds = bugIdsFromCommits(options.commits);
|
|
3699
|
+
const bugIds = commitBugIds.length > 0 ? commitBugIds : selected.bugId ? [selected.bugId] : [];
|
|
3700
|
+
const type = changeType(selected.action, options.commits);
|
|
3701
|
+
const body = titleBody(options.commits, selected, bugIds);
|
|
3702
|
+
const defaultTitle = selected.action === "hotfix" || selected.action === "conflict" ? `Draft: ${body}` : body;
|
|
3703
|
+
if (releaseToTest) {
|
|
3704
|
+
return {
|
|
3705
|
+
sourceBranch,
|
|
3706
|
+
targetBranch,
|
|
3707
|
+
title: options.title ?? `${sourceBranch} -> ${targetBranch}`,
|
|
3708
|
+
description: options.description ?? `${sourceBranch} -> ${targetBranch}`,
|
|
3709
|
+
bugIds,
|
|
3710
|
+
action: selected.action
|
|
3711
|
+
};
|
|
3712
|
+
}
|
|
3713
|
+
return {
|
|
3714
|
+
sourceBranch,
|
|
3715
|
+
targetBranch,
|
|
3716
|
+
title: options.title ?? defaultTitle,
|
|
3717
|
+
description: options.description ?? template(type, bugIds, options.cause, options.solution),
|
|
3718
|
+
removeSourceBranch: !options.keepSourceBranch,
|
|
3719
|
+
bugIds,
|
|
3720
|
+
action: selected.action
|
|
3721
|
+
};
|
|
3722
|
+
}
|
|
3723
|
+
|
|
3724
|
+
// src/commands/mr.ts
|
|
3725
|
+
var defaultDependencies3 = {
|
|
3726
|
+
writer: {
|
|
3727
|
+
stdout: (value) => process.stdout.write(`${value}
|
|
3728
|
+
`),
|
|
3729
|
+
stderr: (value) => process.stderr.write(`${value}
|
|
3730
|
+
`),
|
|
3731
|
+
isTTY: () => Boolean(process.stdout.isTTY)
|
|
3732
|
+
},
|
|
3733
|
+
env: process.env,
|
|
3734
|
+
cwd: process.cwd(),
|
|
3735
|
+
runner: defaultGlabRunner,
|
|
3736
|
+
gitRunner: defaultGitRunner
|
|
3737
|
+
};
|
|
3738
|
+
function positiveInteger2(name, value, max = Number.MAX_SAFE_INTEGER) {
|
|
3739
|
+
const parsed = z3.coerce.number().int().positive().max(max).safeParse(value);
|
|
3740
|
+
if (!parsed.success) throw new CliError("invalid_argument", `${name} \u5FC5\u987B\u662F\u6B63\u6574\u6570`);
|
|
3741
|
+
return parsed.data;
|
|
3742
|
+
}
|
|
3743
|
+
function outputMode2(command, env) {
|
|
3744
|
+
const options = command.optsWithGlobals();
|
|
3745
|
+
return options.json ? "json" : options.output ?? env.DTSTACK_OUTPUT ?? "auto";
|
|
3746
|
+
}
|
|
3747
|
+
function renderHuman(data) {
|
|
3748
|
+
if (Array.isArray(data)) {
|
|
3749
|
+
if (data.length === 0) return "\u672A\u627E\u5230 Merge Request";
|
|
3750
|
+
return data.map((item) => {
|
|
3751
|
+
const mr = item;
|
|
3752
|
+
return `!${String(mr.iid ?? mr.id ?? "-")} [${String(mr.state ?? "-")}] ${String(mr.title ?? "-")}`;
|
|
3753
|
+
}).join("\n");
|
|
3754
|
+
}
|
|
3755
|
+
if (data && typeof data === "object" && "diff" in data) return String(data.diff);
|
|
3756
|
+
return JSON.stringify(data, null, 2);
|
|
3757
|
+
}
|
|
3758
|
+
async function run2(name, command, action, dependencies) {
|
|
3759
|
+
const startedAt = Date.now();
|
|
3760
|
+
const requestId = randomUUID6();
|
|
3761
|
+
const mode = outputMode2(command, dependencies.env);
|
|
3762
|
+
try {
|
|
3763
|
+
const client = new GlabClient(dependencies.runner, {
|
|
3764
|
+
cwd: dependencies.cwd,
|
|
3765
|
+
env: gitlabEnvironment(dependencies.env)
|
|
3766
|
+
});
|
|
3767
|
+
const data = await action(client);
|
|
3768
|
+
printResult(success(data, name, startedAt, requestId), mode, renderHuman, dependencies.writer);
|
|
3769
|
+
} catch (error) {
|
|
3770
|
+
printResult(failure(toCliError(error), name, startedAt, requestId), mode, renderHuman, dependencies.writer);
|
|
3771
|
+
process.exitCode = 1;
|
|
3772
|
+
}
|
|
3773
|
+
}
|
|
3774
|
+
function registerMrCommands(program, dependencies = defaultDependencies3) {
|
|
3775
|
+
const mr = program.command("mr").description("\u521B\u5EFA\u3001\u67E5\u8BE2 GitLab Merge Request \u548C Pipeline");
|
|
3776
|
+
mr.command("create").description("\u6309 DTStack \u5206\u652F\u89C4\u8303\u521B\u5EFA Merge Request\uFF0C\u5E76\u5728\u521B\u5EFA\u540E\u590D\u67E5").option("-R, --repo <repo>", "GitLab \u4ED3\u5E93\uFF0C\u4F8B\u5982 group/project").option("--source <branch>", "\u6E90\u5206\u652F\uFF0C\u9ED8\u8BA4\u4F7F\u7528\u5F53\u524D\u5206\u652F").option("--target <branch>", "\u76EE\u6807\u5206\u652F\uFF08\u5FC5\u586B\uFF0C\u4E0D\u81EA\u52A8\u63A8\u5BFC\uFF09").option("--title <title>", "\u8986\u76D6\u4ECE\u63D0\u4EA4\u4FE1\u606F\u751F\u6210\u7684\u6807\u9898").option("--description <description>", "\u8986\u76D6\u6807\u51C6 MR \u63CF\u8FF0\uFF0C\u5FC5\u987B\u5305\u542B\u771F\u5B9E\u6362\u884C").option("--cause <text>", "\u586B\u5165\u6A21\u677F\u4E2D\u7684\u95EE\u9898\u539F\u56E0").option("--solution <text>", "\u586B\u5165\u6A21\u677F\u4E2D\u7684\u4FEE\u6539\u6458\u8981").option("--assignee <username>", "\u6307\u6D3E\u7ED9 GitLab \u7528\u6237").option("--commit-message <message>", "\u6682\u5B58\u5168\u90E8\u6539\u52A8\u5E76\u4F7F\u7528\u6307\u5B9A\u4FE1\u606F\u63D0\u4EA4").option("--keep-source-branch", "\u5408\u5E76\u540E\u4FDD\u7559\u6E90\u5206\u652F").option("--release-to-test", "\u4ECE\u5F53\u524D test \u5206\u652F\u5BF9\u5E94\u7684 release \u521B\u5EFA\u5230 test \u7684 MR").option("--no-push", "\u521B\u5EFA\u524D\u4E0D\u81EA\u52A8\u63A8\u9001\u6E90\u5206\u652F").option("--dry-run", "\u53EA\u751F\u6210\u5E76\u8F93\u51FA MR \u53C2\u6570\uFF0C\u4E0D\u8C03\u7528 GitLab \u521B\u5EFA\u63A5\u53E3").action(async (options, command) => {
|
|
3777
|
+
await run2(
|
|
3778
|
+
"mr.create",
|
|
3779
|
+
command,
|
|
3780
|
+
async (client) => {
|
|
3781
|
+
const git = new LocalGitRepository(dependencies.gitRunner ?? defaultGitRunner, { cwd: dependencies.cwd });
|
|
3782
|
+
const selectedSource = typeof options.source === "string" ? options.source : await git.currentBranch();
|
|
3783
|
+
const draftOptions = {
|
|
3784
|
+
source: selectedSource,
|
|
3785
|
+
commits: [],
|
|
3786
|
+
...typeof options.target === "string" ? { target: options.target } : {},
|
|
3787
|
+
...typeof options.title === "string" ? { title: options.title } : {},
|
|
3788
|
+
...typeof options.description === "string" ? { description: options.description } : {},
|
|
3789
|
+
...typeof options.cause === "string" ? { cause: options.cause } : {},
|
|
3790
|
+
...typeof options.solution === "string" ? { solution: options.solution } : {},
|
|
3791
|
+
releaseToTest: Boolean(options.releaseToTest),
|
|
3792
|
+
keepSourceBranch: Boolean(options.keepSourceBranch)
|
|
3793
|
+
};
|
|
3794
|
+
const preliminary = buildMergeRequestDraft(draftOptions);
|
|
3795
|
+
if (!options.dryRun && typeof options.commitMessage === "string") {
|
|
3796
|
+
const currentBranch = await git.currentBranch();
|
|
3797
|
+
if (currentBranch !== selectedSource) {
|
|
3798
|
+
throw new CliError("invalid_argument", "-commit-message \u53EA\u80FD\u7528\u4E8E\u5F53\u524D\u68C0\u51FA\u7684\u6E90\u5206\u652F");
|
|
3799
|
+
}
|
|
3800
|
+
await git.commitAll(options.commitMessage);
|
|
3801
|
+
}
|
|
3802
|
+
const commits = options.releaseToTest ? [] : await git.commitSubjects(preliminary.targetBranch, preliminary.sourceBranch);
|
|
3803
|
+
const draft = buildMergeRequestDraft({ ...draftOptions, commits });
|
|
3804
|
+
if (options.dryRun) {
|
|
3805
|
+
return {
|
|
3806
|
+
dryRun: true,
|
|
3807
|
+
...typeof options.repo === "string" ? { repo: options.repo } : {},
|
|
3808
|
+
sourceBranch: draft.sourceBranch,
|
|
3809
|
+
targetBranch: draft.targetBranch,
|
|
3810
|
+
title: draft.title,
|
|
3811
|
+
description: draft.description,
|
|
3812
|
+
...draft.removeSourceBranch !== void 0 ? { removeSourceBranch: draft.removeSourceBranch } : {},
|
|
3813
|
+
...typeof options.assignee === "string" ? { assignee: options.assignee } : {},
|
|
3814
|
+
push: options.push !== false,
|
|
3815
|
+
...typeof options.commitMessage === "string" ? { commitMessage: options.commitMessage } : {},
|
|
3816
|
+
commits,
|
|
3817
|
+
bugIds: draft.bugIds
|
|
3818
|
+
};
|
|
3819
|
+
}
|
|
3820
|
+
if (options.push !== false && !options.releaseToTest) {
|
|
3821
|
+
await git.pushBranch(draft.sourceBranch);
|
|
3822
|
+
}
|
|
3823
|
+
const assigneeId = typeof options.assignee === "string" ? await client.resolveUserId(options.assignee) : void 0;
|
|
3824
|
+
const request = {
|
|
3825
|
+
...typeof options.repo === "string" ? { repo: options.repo } : {},
|
|
3826
|
+
sourceBranch: draft.sourceBranch,
|
|
3827
|
+
targetBranch: draft.targetBranch,
|
|
3828
|
+
title: draft.title,
|
|
3829
|
+
description: draft.description,
|
|
3830
|
+
...draft.removeSourceBranch !== void 0 ? { removeSourceBranch: draft.removeSourceBranch } : {},
|
|
3831
|
+
...assigneeId !== void 0 ? { assigneeId } : {}
|
|
3832
|
+
};
|
|
3833
|
+
return client.createMergeRequest(request);
|
|
3834
|
+
},
|
|
3835
|
+
dependencies
|
|
3836
|
+
);
|
|
3837
|
+
});
|
|
3838
|
+
mr.command("view").description("\u67E5\u770B Merge Request \u8BE6\u60C5").argument("<iid>", "\u9879\u76EE\u5185 MR IID").option("-R, --repo <repo>", "GitLab \u4ED3\u5E93\uFF0C\u4F8B\u5982 group/project").action(async (iid, options, command) => {
|
|
3839
|
+
await run2("mr.view", command, (client) => client.viewMergeRequest(positiveInteger2("iid", iid), options.repo), dependencies);
|
|
3840
|
+
});
|
|
3841
|
+
mr.command("list").description("\u5217\u51FA Merge Request\uFF0C\u9ED8\u8BA4\u53EA\u663E\u793A opened").option("-R, --repo <repo>", "GitLab \u4ED3\u5E93\uFF0C\u4F8B\u5982 group/project").option("--state <state>", "opened\u3001closed\u3001merged \u6216 all", "opened").option("--mine", "\u53EA\u663E\u793A\u81EA\u5DF1\u521B\u5EFA\u7684 MR").option("--author <username>", "\u6309\u521B\u5EFA\u4EBA\u7B5B\u9009").option("--assignee <username>", "\u6309\u5904\u7406\u4EBA\u7B5B\u9009").option("--search <query>", "\u641C\u7D22\u6807\u9898\u548C\u63CF\u8FF0").option("--page <number>", "\u9875\u7801", "1").option("--page-size <number>", "\u6BCF\u9875\u6570\u91CF\uFF0C\u6700\u5927 100", "30").action(async (options, command) => {
|
|
3842
|
+
const state = options.state ?? "opened";
|
|
3843
|
+
if (!["opened", "closed", "merged", "all"].includes(String(state))) {
|
|
3844
|
+
throw new CliError("invalid_argument", "-state \u53EA\u80FD\u662F opened\u3001closed\u3001merged \u6216 all");
|
|
3845
|
+
}
|
|
3846
|
+
const query = {
|
|
3847
|
+
state,
|
|
3848
|
+
mine: Boolean(options.mine),
|
|
3849
|
+
page: positiveInteger2("page", String(options.page ?? "1")),
|
|
3850
|
+
perPage: positiveInteger2("page-size", String(options.pageSize ?? "30"), 100)
|
|
3851
|
+
};
|
|
3852
|
+
if (typeof options.repo === "string") query.repo = options.repo;
|
|
3853
|
+
if (typeof options.author === "string") query.author = options.author;
|
|
3854
|
+
if (typeof options.assignee === "string") query.assignee = options.assignee;
|
|
3855
|
+
if (typeof options.search === "string") query.search = options.search;
|
|
3856
|
+
await run2("mr.list", command, (client) => client.listMergeRequests(query), dependencies);
|
|
3857
|
+
});
|
|
3858
|
+
mr.command("diff").description("\u67E5\u770B Merge Request \u7684\u539F\u59CB diff").argument("<iid>", "\u9879\u76EE\u5185 MR IID").option("-R, --repo <repo>", "GitLab \u4ED3\u5E93\uFF0C\u4F8B\u5982 group/project").action(async (iid, options, command) => {
|
|
3859
|
+
await run2("mr.diff", command, (client) => client.diffMergeRequest(positiveInteger2("iid", iid), options.repo), dependencies);
|
|
3860
|
+
});
|
|
3861
|
+
mr.command("pipeline").description("\u67E5\u770B Merge Request source branch \u5BF9\u5E94\u7684 Pipeline \u72B6\u6001").argument("<iid>", "\u9879\u76EE\u5185 MR IID").option("-R, --repo <repo>", "GitLab \u4ED3\u5E93\uFF0C\u4F8B\u5982 group/project").action(async (iid, options, command) => {
|
|
3862
|
+
await run2("mr.pipeline", command, (client) => client.mergeRequestPipeline(positiveInteger2("iid", iid), options.repo), dependencies);
|
|
3863
|
+
});
|
|
3864
|
+
}
|
|
3865
|
+
|
|
3866
|
+
// src/commands/branch.ts
|
|
3867
|
+
import { randomUUID as randomUUID7 } from "crypto";
|
|
3868
|
+
|
|
3869
|
+
// src/domain/branch-create.ts
|
|
3870
|
+
var EXECUTABLE_BRANCH_TYPES = ["feat", "fix", "hotfix", "conflict"];
|
|
3871
|
+
var APPS = /* @__PURE__ */ new Set([
|
|
3872
|
+
"batch",
|
|
3873
|
+
"console",
|
|
3874
|
+
"dataAssets",
|
|
3875
|
+
"dataApi",
|
|
3876
|
+
"dataLake",
|
|
3877
|
+
"easyIndex",
|
|
3878
|
+
"stream",
|
|
3879
|
+
"tag",
|
|
3880
|
+
"uic",
|
|
3881
|
+
"global",
|
|
3882
|
+
"dt-common"
|
|
3883
|
+
]);
|
|
3884
|
+
function normalizeRemoteBranch(branch) {
|
|
3885
|
+
return branch.trim().replace(/^refs\/heads\//, "").replace(/^refs\/remotes\/[^/]+\//, "").replace(/^remotes\/[^/]+\//, "");
|
|
3886
|
+
}
|
|
3887
|
+
function validate(options) {
|
|
3888
|
+
if (!APPS.has(options.app)) {
|
|
3889
|
+
const replacement = ["publicService", "portal"].includes(options.app) ? "\uFF1Bv6.4.x \u53CA\u4EE5\u4E0A\u8BF7\u4F7F\u7528 console" : "";
|
|
3890
|
+
throw new CliError("invalid_argument", `\u4E0D\u652F\u6301\u7684 appName\uFF1A${options.app}${replacement}`);
|
|
3891
|
+
}
|
|
3892
|
+
if (!EXECUTABLE_BRANCH_TYPES.includes(options.type)) {
|
|
3893
|
+
throw new CliError("invalid_argument", "branch create \u4EC5\u652F\u6301 feat\u3001fix\u3001hotfix\u3001conflict");
|
|
3894
|
+
}
|
|
3895
|
+
const versionPattern = options.app === "dt-common" ? /^\d+\.x\.y$/ : /^\d+\.\d+\.x$/;
|
|
3896
|
+
if (!versionPattern.test(options.version)) {
|
|
3897
|
+
throw new CliError(
|
|
3898
|
+
"invalid_argument",
|
|
3899
|
+
options.app === "dt-common" ? "dt-common \u7248\u672C\u5FC5\u987B\u4F7F\u7528 14.x.y \u683C\u5F0F" : "\u7248\u672C\u5FC5\u987B\u4F7F\u7528 6.3.x \u683C\u5F0F"
|
|
3900
|
+
);
|
|
3901
|
+
}
|
|
3902
|
+
const type = options.type;
|
|
3903
|
+
const descriptionPattern = type === "fix" ? /^(?:\d+|v\d+)$/ : /^\d+$/;
|
|
3904
|
+
if (!descriptionPattern.test(options.description)) {
|
|
3905
|
+
const expected = type === "fix" ? "\u6570\u5B57\u7985\u9053\u7F16\u53F7\u6216 v+\u8FED\u4EE3\u53F7" : "\u6570\u5B57\u7F16\u53F7";
|
|
3906
|
+
throw new CliError("invalid_argument", `${type} \u5206\u652F description \u5FC5\u987B\u662F${expected}`);
|
|
3907
|
+
}
|
|
3908
|
+
return type;
|
|
3909
|
+
}
|
|
3910
|
+
function candidatesFor(app, type, version, remoteBranches) {
|
|
3911
|
+
const prefixes = type === "feat" || type === "fix" ? [`${app}/test_${version}`] : type === "hotfix" ? [`${app}/release_${version}`] : [`${app}/release_${version}`, `${app}/test_${version}`];
|
|
3912
|
+
return remoteBranches.filter(
|
|
3913
|
+
(branch) => prefixes.some((prefix) => branch === prefix || branch.startsWith(`${prefix}_`))
|
|
3914
|
+
);
|
|
3915
|
+
}
|
|
3916
|
+
function customMarkFromBase(baseBranch, version) {
|
|
3917
|
+
const versionIndex = baseBranch.indexOf(version);
|
|
3918
|
+
if (versionIndex < 0) return void 0;
|
|
3919
|
+
const suffix = baseBranch.slice(versionIndex + version.length).replace(/^_+/, "");
|
|
3920
|
+
if (!suffix) return void 0;
|
|
3921
|
+
const parts = suffix.split("_");
|
|
3922
|
+
const branchName = baseBranch.slice(baseBranch.indexOf("/") + 1);
|
|
3923
|
+
if (branchName.startsWith("test_") && /^v\d+$/.test(parts[0] ?? "")) parts.shift();
|
|
3924
|
+
return parts.length > 0 ? parts.join("_") : void 0;
|
|
3925
|
+
}
|
|
3926
|
+
function buildBranchCreatePlan(options) {
|
|
3927
|
+
const type = validate(options);
|
|
3928
|
+
const remoteBranches = [...new Set(options.remoteBranches.map(normalizeRemoteBranch).filter(Boolean))];
|
|
3929
|
+
let baseBranch;
|
|
3930
|
+
if (options.baseBranch) {
|
|
3931
|
+
baseBranch = normalizeRemoteBranch(options.baseBranch);
|
|
3932
|
+
if (!remoteBranches.includes(baseBranch)) {
|
|
3933
|
+
throw new CliError("invalid_argument", `\u8FDC\u7AEF\u4E0D\u5B58\u5728\u6765\u6E90\u5206\u652F\uFF1A${baseBranch}`);
|
|
3934
|
+
}
|
|
3935
|
+
} else {
|
|
3936
|
+
const candidates = candidatesFor(options.app, type, options.version, remoteBranches);
|
|
3937
|
+
if (candidates.length === 0) {
|
|
3938
|
+
throw new CliError("invalid_argument", `\u8FDC\u7AEF\u6CA1\u6709\u5339\u914D\u7684\u6765\u6E90\u5206\u652F\uFF1A${options.app} ${type} ${options.version}`);
|
|
3939
|
+
}
|
|
3940
|
+
if (candidates.length > 1) {
|
|
3941
|
+
throw new CliError("invalid_argument", "\u5B58\u5728\u591A\u4E2A\u6765\u6E90\u5206\u652F\uFF0C\u8BF7\u901A\u8FC7 -base \u660E\u786E\u9009\u62E9", {
|
|
3942
|
+
details: { candidates }
|
|
3943
|
+
});
|
|
3944
|
+
}
|
|
3945
|
+
baseBranch = candidates[0];
|
|
3946
|
+
}
|
|
3947
|
+
const customMark = customMarkFromBase(baseBranch, options.version);
|
|
3948
|
+
const targetBranch = [
|
|
3949
|
+
`${options.app}/${type}_${options.version}`,
|
|
3950
|
+
customMark,
|
|
3951
|
+
options.description
|
|
3952
|
+
].filter(Boolean).join("_");
|
|
3953
|
+
return {
|
|
3954
|
+
app: options.app,
|
|
3955
|
+
type,
|
|
3956
|
+
version: options.version,
|
|
3957
|
+
description: options.description,
|
|
3958
|
+
baseBranch,
|
|
3959
|
+
targetBranch,
|
|
3960
|
+
...customMark ? { customMark } : {}
|
|
3961
|
+
};
|
|
3962
|
+
}
|
|
3963
|
+
|
|
3964
|
+
// src/commands/branch.ts
|
|
3965
|
+
var defaultDependencies4 = {
|
|
3966
|
+
writer: {
|
|
3967
|
+
stdout: (value) => process.stdout.write(`${value}
|
|
3968
|
+
`),
|
|
3969
|
+
stderr: (value) => process.stderr.write(`${value}
|
|
3970
|
+
`),
|
|
3971
|
+
isTTY: () => Boolean(process.stdout.isTTY)
|
|
3972
|
+
},
|
|
3973
|
+
env: process.env,
|
|
3974
|
+
cwd: process.cwd(),
|
|
3975
|
+
runner: defaultGitRunner
|
|
3976
|
+
};
|
|
3977
|
+
function outputMode3(command, env) {
|
|
3978
|
+
const options = command.optsWithGlobals();
|
|
3979
|
+
return options.json ? "json" : options.output ?? env.DTSTACK_OUTPUT ?? "auto";
|
|
3980
|
+
}
|
|
3981
|
+
function parseRemoteBranches(stdout) {
|
|
3982
|
+
return stdout.split("\n").map((line) => line.trim().split(/\s+/)[1]).filter((ref) => Boolean(ref?.startsWith("refs/heads/")));
|
|
3983
|
+
}
|
|
3984
|
+
function registerBranchCommands(program, dependencies = defaultDependencies4) {
|
|
3985
|
+
const branch = program.command("branch").description("\u521B\u5EFA\u7B26\u5408 DTStack \u89C4\u8303\u7684 Git \u5206\u652F");
|
|
3986
|
+
branch.command("create").description("\u4ECE\u5339\u914D\u7684\u8FDC\u7AEF test \u6216 release \u5206\u652F\u521B\u5EFA feat/fix/hotfix/conflict \u5206\u652F").argument("<type>", "\u5206\u652F\u7C7B\u578B\uFF1Afeat\u3001fix\u3001hotfix\u3001conflict").argument("<description>", "\u7985\u9053\u7F16\u53F7\uFF1Bfix \u4E5F\u652F\u6301 v+\u8FED\u4EE3\u53F7").requiredOption("-p, --app <name>", "\u5E94\u7528\u540D\u79F0\uFF0C\u4F8B\u5982 dataAssets").requiredOption("-v, --branch-version <version>", "\u5206\u652F\u7248\u672C\uFF0C\u4F8B\u5982 6.3.x\uFF1Bdt-common \u4F7F\u7528 14.x.y").option("--base <branch>", "\u663E\u5F0F\u6307\u5B9A\u6765\u6E90\u5206\u652F\uFF1B\u591A\u4E2A\u5019\u9009\u65F6\u5FC5\u586B").option("--remote <name>", "\u8FDC\u7AEF\u540D\u79F0", "origin").option("--no-push", "\u521B\u5EFA\u540E\u4E0D\u63A8\u9001\u76EE\u6807\u5206\u652F").option("--dry-run", "\u53EA\u8F93\u51FA\u521B\u5EFA\u8BA1\u5212\uFF0C\u4E0D fetch\u3001checkout \u6216 push").action(async (type, description, options, command) => {
|
|
3987
|
+
const startedAt = Date.now();
|
|
3988
|
+
const requestId = randomUUID7();
|
|
3989
|
+
const mode = outputMode3(command, dependencies.env);
|
|
3990
|
+
try {
|
|
3991
|
+
const remote = options.remote.trim();
|
|
3992
|
+
if (!remote) throw new CliError("invalid_argument", "-remote \u4E0D\u80FD\u4E3A\u7A7A");
|
|
3993
|
+
const refs = await dependencies.runner(["ls-remote", "--heads", remote], { cwd: dependencies.cwd });
|
|
3994
|
+
const plan = buildBranchCreatePlan({
|
|
3995
|
+
app: options.app,
|
|
3996
|
+
type,
|
|
3997
|
+
version: options.branchVersion,
|
|
3998
|
+
description,
|
|
3999
|
+
remoteBranches: parseRemoteBranches(refs.stdout),
|
|
4000
|
+
...options.base ? { baseBranch: options.base } : {}
|
|
4001
|
+
});
|
|
4002
|
+
if (options.dryRun) {
|
|
4003
|
+
printResult(
|
|
4004
|
+
success({ dryRun: true, remote, push: options.push, ...plan }, "branch.create", startedAt, requestId),
|
|
4005
|
+
mode,
|
|
4006
|
+
(data) => `\u6765\u6E90\uFF1A${data.baseBranch}
|
|
4007
|
+
\u76EE\u6807\uFF1A${data.targetBranch}
|
|
4008
|
+
\u8FDC\u7AEF\uFF1A${data.remote}`,
|
|
4009
|
+
dependencies.writer
|
|
4010
|
+
);
|
|
4011
|
+
return;
|
|
4012
|
+
}
|
|
4013
|
+
await dependencies.runner(
|
|
4014
|
+
["fetch", remote, `${plan.baseBranch}:refs/remotes/${remote}/${plan.baseBranch}`],
|
|
4015
|
+
{ cwd: dependencies.cwd }
|
|
4016
|
+
);
|
|
4017
|
+
await dependencies.runner(
|
|
4018
|
+
["checkout", "-b", plan.targetBranch, `${remote}/${plan.baseBranch}`],
|
|
4019
|
+
{ cwd: dependencies.cwd }
|
|
4020
|
+
);
|
|
4021
|
+
if (options.push) {
|
|
4022
|
+
await dependencies.runner(["push", "--set-upstream", remote, plan.targetBranch], { cwd: dependencies.cwd });
|
|
4023
|
+
}
|
|
4024
|
+
printResult(
|
|
4025
|
+
success({ dryRun: false, remote, pushed: options.push, ...plan }, "branch.create", startedAt, requestId),
|
|
4026
|
+
mode,
|
|
4027
|
+
(data) => `fetch\uFF1A${data.remote}/${data.baseBranch}
|
|
4028
|
+
\u6765\u6E90\uFF1A${data.baseBranch}
|
|
4029
|
+
\u76EE\u6807\uFF1A${data.targetBranch}
|
|
4030
|
+
${data.pushed ? "\u5DF2\u63A8\u9001" : "\u672A\u63A8\u9001"}`,
|
|
4031
|
+
dependencies.writer
|
|
4032
|
+
);
|
|
4033
|
+
} catch (error) {
|
|
4034
|
+
printResult(
|
|
4035
|
+
failure(toCliError(error), "branch.create", startedAt, requestId),
|
|
4036
|
+
mode,
|
|
4037
|
+
() => "",
|
|
4038
|
+
dependencies.writer
|
|
4039
|
+
);
|
|
4040
|
+
process.exitCode = 1;
|
|
4041
|
+
}
|
|
4042
|
+
});
|
|
4043
|
+
}
|
|
4044
|
+
|
|
4045
|
+
// src/commands/omp.ts
|
|
4046
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
4047
|
+
import { z as z4 } from "zod";
|
|
4048
|
+
var defaultDependencies5 = {
|
|
4049
|
+
writer: {
|
|
4050
|
+
stdout: (value) => process.stdout.write(`${value}
|
|
4051
|
+
`),
|
|
4052
|
+
stderr: (value) => process.stderr.write(`${value}
|
|
4053
|
+
`),
|
|
4054
|
+
isTTY: () => Boolean(process.stdout.isTTY)
|
|
4055
|
+
},
|
|
4056
|
+
env: process.env,
|
|
4057
|
+
cwd: process.cwd(),
|
|
4058
|
+
gitRunner: defaultGitRunner,
|
|
4059
|
+
createClient: (options) => new OmpClient(options)
|
|
4060
|
+
};
|
|
4061
|
+
function positiveInteger3(name, value, max = Number.MAX_SAFE_INTEGER) {
|
|
4062
|
+
const parsed = z4.coerce.number().int().positive().max(max).safeParse(value);
|
|
4063
|
+
if (!parsed.success) throw new CliError("invalid_argument", `${name} \u5FC5\u987B\u662F\u6B63\u6574\u6570`);
|
|
4064
|
+
return parsed.data;
|
|
4065
|
+
}
|
|
4066
|
+
function outputMode4(command, env) {
|
|
4067
|
+
const options = command.optsWithGlobals();
|
|
4068
|
+
const output = options.json ? "json" : options.output ?? env.DTSTACK_OUTPUT ?? "auto";
|
|
4069
|
+
if (!["auto", "human", "json"].includes(output)) {
|
|
4070
|
+
throw new CliError("invalid_argument", `\u4E0D\u652F\u6301\u7684\u8F93\u51FA\u6A21\u5F0F\uFF1A${output}`);
|
|
4071
|
+
}
|
|
4072
|
+
return output;
|
|
4073
|
+
}
|
|
4074
|
+
function environmentType(type) {
|
|
4075
|
+
if (type === "Standard") return "\u6807\u54C1";
|
|
4076
|
+
if (type === "Customized") return "\u5B9A\u5236\u5316";
|
|
4077
|
+
return String(type ?? "\u672A\u77E5\u7C7B\u578B");
|
|
4078
|
+
}
|
|
4079
|
+
function renderEnvironments(data) {
|
|
4080
|
+
if (data.environments.length === 0) return "\u672A\u627E\u5230 OMP \u73AF\u5883";
|
|
4081
|
+
const groups = /* @__PURE__ */ new Map();
|
|
4082
|
+
for (const env of data.environments) {
|
|
4083
|
+
const label = environmentType(env.type);
|
|
4084
|
+
const bucket = groups.get(label);
|
|
4085
|
+
if (bucket) bucket.push(env);
|
|
4086
|
+
else groups.set(label, [env]);
|
|
4087
|
+
}
|
|
4088
|
+
const lines = [];
|
|
4089
|
+
for (const [label, environments] of groups) {
|
|
4090
|
+
lines.push(`\u3010${label}\u3011`, ...environments.flatMap((env) => [
|
|
4091
|
+
`[${env.id}] ${env.name}`,
|
|
4092
|
+
`\u73AF\u5883\u72B6\u6001: ${env.status ?? "-"} \u7248\u672C: ${env.version ?? "-"} \u5206\u652F: ${env.branch ?? "-"}`,
|
|
4093
|
+
`UIC\u767B\u5F55\uFF1Ahttp://${env.namespace}.k8s.dtstack.cn`
|
|
4094
|
+
]));
|
|
4095
|
+
}
|
|
4096
|
+
return lines.join("\n");
|
|
4097
|
+
}
|
|
4098
|
+
function renderDeploy(data) {
|
|
4099
|
+
return [
|
|
4100
|
+
"\u90E8\u7F72\u4EFB\u52A1\u5DF2\u63D0\u4EA4\uFF08\u4E0D\u4EE3\u8868\u90E8\u7F72\u5B8C\u6210\uFF09",
|
|
4101
|
+
`\u73AF\u5883: ${data.environment.name}\uFF08${environmentType(data.environment.type)}\uFF09`,
|
|
4102
|
+
`\u90E8\u7F72 ID: ${String(data.deployId ?? "-")}`,
|
|
4103
|
+
`\u5206\u652F: ${data.deployInfo.branch}`,
|
|
4104
|
+
`\u670D\u52A1: ${data.deployInfo.services.join(", ")}`
|
|
4105
|
+
].join("\n");
|
|
4106
|
+
}
|
|
4107
|
+
function renderBranches(data) {
|
|
4108
|
+
if (data.branches.length === 0) return "\u672A\u627E\u5230\u53EF\u7528\u7684\u90E8\u7F72\u5206\u652F";
|
|
4109
|
+
return data.branches.map((branch) => [
|
|
4110
|
+
`${String(branch.name ?? "-")}`,
|
|
4111
|
+
`\u90E8\u7F72\u5206\u652F: ${String(branch.tag ?? "-")} \u72B6\u6001: ${String(branch.status ?? "-")}`
|
|
4112
|
+
].join("\n")).join("\n\n");
|
|
4113
|
+
}
|
|
4114
|
+
function renderLogs(data) {
|
|
4115
|
+
if (data.logs.length === 0) return "\u672A\u627E\u5230 OMP \u90E8\u7F72\u8BB0\u5F55";
|
|
4116
|
+
return data.logs.map((log) => [
|
|
4117
|
+
`[${String(log.id ?? "-")}] ${String(log.envName ?? "-")}`,
|
|
4118
|
+
`\u90E8\u7F72\u72B6\u6001: ${String(log.status ?? "-")} \u5206\u652F: ${String(log.branch ?? "-")} \u670D\u52A1: ${String(log.services ?? "-")}`,
|
|
4119
|
+
`\u63D0\u4EA4\u4EBA: ${String(log.user ?? "-")} \u65F6\u95F4: ${String(log.createdTime ?? "-")}`
|
|
4120
|
+
].join("\n")).join("\n\n");
|
|
4121
|
+
}
|
|
4122
|
+
async function run3(name, command, action, render, dependencies) {
|
|
4123
|
+
const startedAt = Date.now();
|
|
4124
|
+
const requestId = randomUUID8();
|
|
4125
|
+
let mode = "auto";
|
|
4126
|
+
try {
|
|
4127
|
+
mode = outputMode4(command, dependencies.env);
|
|
4128
|
+
const globals = command.optsWithGlobals();
|
|
4129
|
+
const tokenCache = dependencies.tokenCache ?? new FileOmpTokenCache();
|
|
4130
|
+
const environmentUsername = dependencies.env.OMP_MCP_USERNAME;
|
|
4131
|
+
const environmentPassword = dependencies.env.OMP_MCP_PASSWORD;
|
|
4132
|
+
if ((environmentUsername || environmentPassword) && (!environmentUsername || !environmentPassword)) {
|
|
4133
|
+
throw new CliError("not_authenticated", "OMP \u73AF\u5883\u53D8\u91CF\u914D\u7F6E\u4E0D\u5B8C\u6574");
|
|
4134
|
+
}
|
|
4135
|
+
const username = environmentUsername ?? await tokenCache.getActiveUsername();
|
|
4136
|
+
if (!username) throw new CliError("not_authenticated", "OMP \u5C1A\u672A\u767B\u5F55\uFF0C\u8BF7\u6267\u884C dt auth login omp");
|
|
4137
|
+
const client = dependencies.createClient({
|
|
4138
|
+
baseUrl: globals.ompBaseUrl ?? dependencies.env.DTSTACK_OMP_BASE_URL ?? DEFAULT_OMP_BASE_URL,
|
|
4139
|
+
username,
|
|
4140
|
+
...environmentPassword ? { password: environmentPassword } : {},
|
|
4141
|
+
tokenCache
|
|
4142
|
+
});
|
|
4143
|
+
const data = await action(client);
|
|
4144
|
+
printResult(success(data, name, startedAt, requestId), mode, render, dependencies.writer);
|
|
4145
|
+
} catch (error) {
|
|
4146
|
+
printResult(failure(toCliError(error), name, startedAt, requestId), mode, render, dependencies.writer);
|
|
4147
|
+
process.exitCode = 1;
|
|
4148
|
+
}
|
|
4149
|
+
}
|
|
4150
|
+
function collectService(value, previous) {
|
|
4151
|
+
return [...previous, value];
|
|
4152
|
+
}
|
|
4153
|
+
function registerOmpCommands(program, dependencies = defaultDependencies5) {
|
|
4154
|
+
const omp = program.command("omp").description("\u67E5\u8BE2 OMP \u73AF\u5883\u3001\u63D0\u4EA4\u90E8\u7F72\u3001\u67E5\u8BE2\u90E8\u7F72\u5206\u652F\u548C\u67E5\u770B\u90E8\u7F72\u8BB0\u5F55");
|
|
4155
|
+
omp.command("list-env").description("\u67E5\u8BE2 OMP \u73AF\u5883\u5217\u8868").option("-v, --version <version>", "\u67E5\u8BE2\u7279\u5B9A\u7248\u672C").action(async (options, command) => {
|
|
4156
|
+
await run3("omp.list-env", command, (client) => client.listEnvironments(options), renderEnvironments, dependencies);
|
|
4157
|
+
});
|
|
4158
|
+
omp.command("deploy").description("\u5411\u660E\u786E\u7684 OMP \u73AF\u5883\u63D0\u4EA4\u90E8\u7F72\u4EFB\u52A1").requiredOption("--env-id <id>", "\u73AF\u5883 ID\uFF1B\u8BF7\u5148\u901A\u8FC7 list-env \u67E5\u8BE2").option("--branch <branch>", "\u90E8\u7F72\u5206\u652F\uFF0C\u9ED8\u8BA4\u8BFB\u53D6\u5F53\u524D Git \u5206\u652F").option("-s, --service <service>", "\u90E8\u7F72\u670D\u52A1\uFF0C\u53EF\u91CD\u590D\u4F20\u5165", collectService, []).option("--merge", "\u5408\u5E76\u5206\u652F\u540E\u90E8\u7F72", false).option("--new-branch <branch>", "OMP \u65B0\u5206\u652F\u540D\u79F0").action(async (options, command) => {
|
|
4159
|
+
await run3(
|
|
4160
|
+
"omp.deploy",
|
|
4161
|
+
command,
|
|
4162
|
+
async (client) => {
|
|
4163
|
+
if (options.service.length === 0) {
|
|
4164
|
+
throw new CliError("invalid_argument", "\u8BF7\u81F3\u5C11\u4F20\u5165\u4E00\u6B21 -service");
|
|
4165
|
+
}
|
|
4166
|
+
const branch = options.branch ?? await new LocalGitRepository(
|
|
4167
|
+
dependencies.gitRunner ?? defaultGitRunner,
|
|
4168
|
+
{ cwd: dependencies.cwd }
|
|
4169
|
+
).currentBranch();
|
|
4170
|
+
return client.deploy({
|
|
4171
|
+
envId: positiveInteger3("env-id", options.envId),
|
|
4172
|
+
branch,
|
|
4173
|
+
services: options.service,
|
|
4174
|
+
merge: options.merge,
|
|
4175
|
+
...options.newBranch ? { newBranch: options.newBranch } : {}
|
|
4176
|
+
});
|
|
4177
|
+
},
|
|
4178
|
+
renderDeploy,
|
|
4179
|
+
dependencies
|
|
4180
|
+
);
|
|
4181
|
+
});
|
|
4182
|
+
omp.command("list-branch").description("\u67E5\u8BE2 OMP \u73AF\u5883\u7684\u90E8\u7F72\u5206\u652F\uFF0C\u53EF\u6309\u5E94\u7528\u540D\u8FC7\u6EE4").requiredOption("-n, --namespace <name>", "\u73AF\u5883 namespace").option("-a, --app <name>", "\u6309\u5E94\u7528\u540D\u8FC7\u6EE4\uFF08\u4E0D\u533A\u5206\u5927\u5C0F\u5199\u7684\u6A21\u7CCA\u5339\u914D\uFF09").action(async (options, command) => {
|
|
4183
|
+
await run3(
|
|
4184
|
+
"omp.list-branch",
|
|
4185
|
+
command,
|
|
4186
|
+
(client) => client.listBranches({
|
|
4187
|
+
namespace: options.namespace,
|
|
4188
|
+
...options.app ? { app: options.app } : {}
|
|
4189
|
+
}),
|
|
4190
|
+
renderBranches,
|
|
4191
|
+
dependencies
|
|
4192
|
+
);
|
|
4193
|
+
});
|
|
4194
|
+
omp.command("list-log").description("\u67E5\u8BE2 OMP \u90E8\u7F72\u8BB0\u5F55\u548C\u90E8\u7F72\u72B6\u6001").option("--page <number>", "\u9875\u7801", "1").option("--limit <number>", "\u6BCF\u9875\u6570\u91CF\uFF0C\u6700\u5927 1000", "20").option("--environmentlog <name>", "\u6309\u5B8C\u6574\u73AF\u5883\u540D\u7B5B\u9009").option("--services <service>", "\u6309\u670D\u52A1\u540D\u7B5B\u9009").option("--user <name>", "\u6309\u63D0\u4EA4\u4EBA\uFF08user\uFF09\u6A21\u7CCA\u5339\u914D\u7B5B\u9009").action(async (options, command) => {
|
|
4195
|
+
await run3(
|
|
4196
|
+
"omp.list-log",
|
|
4197
|
+
command,
|
|
4198
|
+
async (client) => {
|
|
4199
|
+
const data = await client.listDeployLogs({
|
|
4200
|
+
page: positiveInteger3("page", options.page),
|
|
4201
|
+
limit: positiveInteger3("limit", options.limit, 1e3),
|
|
4202
|
+
...options.environmentlog ? { environment: options.environmentlog } : {},
|
|
4203
|
+
...options.services ? { services: options.services } : {},
|
|
4204
|
+
...options.user ? { user: options.user } : {}
|
|
4205
|
+
});
|
|
4206
|
+
if (data.truncated) {
|
|
4207
|
+
dependencies.writer.stderr(
|
|
4208
|
+
`\u26A0 \u5DF2\u626B\u63CF ${DEPLOY_LOG_SCAN_MAX_PAGES} \u9875\uFF08${DEPLOY_LOG_SCAN_MAX_PAGES * DEPLOY_LOG_SCAN_PAGE_SIZE} \u6761\uFF09\u4ECD\u672A\u8986\u76D6\u5168\u90E8\u90E8\u7F72\u8BB0\u5F55\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF1B\u8BF7\u7F29\u5C0F --environmentlog / --services \u8303\u56F4\u540E\u91CD\u8BD5\u3002`
|
|
4209
|
+
);
|
|
4210
|
+
}
|
|
4211
|
+
return data;
|
|
4212
|
+
},
|
|
4213
|
+
renderLogs,
|
|
4214
|
+
dependencies
|
|
4215
|
+
);
|
|
4216
|
+
});
|
|
4217
|
+
}
|
|
4218
|
+
|
|
4219
|
+
// src/commands/lanhu.ts
|
|
4220
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
4221
|
+
import { join as join7 } from "path";
|
|
4222
|
+
|
|
4223
|
+
// src/adapters/lanhu/prd/download.ts
|
|
4224
|
+
import { mkdir as mkdir4 } from "fs/promises";
|
|
4225
|
+
import { createRequire } from "module";
|
|
4226
|
+
import { homedir as homedir4 } from "os";
|
|
4227
|
+
import { join as join6 } from "path";
|
|
4228
|
+
var LANHU_ORIGIN2 = "https://lanhuapp.com/";
|
|
4229
|
+
var RESULT_FILE = "result.json";
|
|
4230
|
+
function sanitizedShareUrl(raw) {
|
|
4231
|
+
try {
|
|
4232
|
+
const url = new URL(raw);
|
|
4233
|
+
url.search = "";
|
|
4234
|
+
return url.href;
|
|
4235
|
+
} catch {
|
|
4236
|
+
return raw;
|
|
4237
|
+
}
|
|
4238
|
+
}
|
|
4239
|
+
function authRequiredError3() {
|
|
4240
|
+
return new LanhuError(
|
|
4241
|
+
"AUTH_REQUIRED",
|
|
4242
|
+
"No authenticated Lanhu session is available",
|
|
4243
|
+
"Run `dt auth login lanhu` to authenticate first, then retry `dt lanhu prd download`"
|
|
4244
|
+
);
|
|
4245
|
+
}
|
|
4246
|
+
function resolveExtractorPath(extractorPath, home = homedir4()) {
|
|
4247
|
+
if (extractorPath !== void 0 && extractorPath !== "") return extractorPath;
|
|
4248
|
+
return join6(home, ".claude", "skills", "lanhu-prd-extractor", "scripts", "lanhu_extractor.js");
|
|
4249
|
+
}
|
|
4250
|
+
function parseLanhuUrl(extractor, url) {
|
|
4251
|
+
try {
|
|
4252
|
+
return extractor.parseUrl(url);
|
|
4253
|
+
} catch (error) {
|
|
4254
|
+
const detail = redact(error instanceof Error ? error.message : String(error));
|
|
4255
|
+
throw new LanhuError(
|
|
4256
|
+
"USAGE_ERROR",
|
|
4257
|
+
`\u65E0\u6548\u7684\u84DD\u6E56\u94FE\u63A5\uFF1A${detail}`,
|
|
4258
|
+
"\u8BF7\u4F20\u5305\u542B pid\u3001tid \u53C2\u6570\u7684\u84DD\u6E56\u94FE\u63A5\uFF08\u4F8B\u5982 https://lanhuapp.com/web/#/item/...?pid=...&tid=...\uFF09"
|
|
4259
|
+
);
|
|
4260
|
+
}
|
|
4261
|
+
}
|
|
4262
|
+
function loadLanhuExtractor(extractorPath, cookie) {
|
|
4263
|
+
const require2 = createRequire(import.meta.url);
|
|
4264
|
+
let mod;
|
|
4265
|
+
try {
|
|
4266
|
+
mod = require2(extractorPath);
|
|
4267
|
+
} catch {
|
|
4268
|
+
throw new LanhuError(
|
|
4269
|
+
"PRD_EXTRACTOR_NOT_FOUND",
|
|
4270
|
+
`Unable to load the LanhuExtractor script at: ${extractorPath}`,
|
|
4271
|
+
"\u8BF7\u68C0\u67E5 lanhu-prd-extractor skill \u662F\u5426\u5B89\u88C5\uFF0C\u6216\u7528 --extractor-path \u6307\u5B9A lanhu_extractor.js"
|
|
4272
|
+
);
|
|
4273
|
+
}
|
|
4274
|
+
const Ctor = mod.LanhuExtractor ?? mod.default;
|
|
4275
|
+
if (typeof Ctor !== "function") {
|
|
4276
|
+
throw new LanhuError(
|
|
4277
|
+
"PROTOCOL_ERROR",
|
|
4278
|
+
`Extractor at ${extractorPath} does not export a constructable LanhuExtractor`
|
|
4279
|
+
);
|
|
4280
|
+
}
|
|
4281
|
+
return new Ctor({ cookie });
|
|
4282
|
+
}
|
|
4283
|
+
async function downloadPrd(opts) {
|
|
4284
|
+
const jar = await opts.ensureJar();
|
|
4285
|
+
const cookie = await jar.getCookieString(LANHU_ORIGIN2);
|
|
4286
|
+
if (cookie === "" || cookie === void 0) {
|
|
4287
|
+
throw authRequiredError3();
|
|
4288
|
+
}
|
|
4289
|
+
const extractor = opts.createExtractor ? opts.createExtractor(cookie) : loadLanhuExtractor(resolveExtractorPath(opts.extractorPath), cookie);
|
|
4290
|
+
const outputDir = opts.outputDir ?? "./tmp";
|
|
4291
|
+
const forceUpdate = opts.forceUpdate ?? false;
|
|
4292
|
+
const parsed = parseLanhuUrl(extractor, opts.url);
|
|
4293
|
+
const pagesList = await extractor.getPagesList(opts.url);
|
|
4294
|
+
const download = await extractor.downloadResources(opts.url, outputDir, forceUpdate);
|
|
4295
|
+
const result = {
|
|
4296
|
+
url: sanitizedShareUrl(opts.url),
|
|
4297
|
+
projectId: parsed.project_id,
|
|
4298
|
+
teamId: parsed.team_id,
|
|
4299
|
+
docId: parsed.doc_id,
|
|
4300
|
+
name: pagesList.document_name,
|
|
4301
|
+
totalPages: pagesList.total_pages,
|
|
4302
|
+
pages: pagesList.pages,
|
|
4303
|
+
download,
|
|
4304
|
+
extractedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4305
|
+
};
|
|
4306
|
+
await mkdir4(outputDir, { recursive: true });
|
|
4307
|
+
await writeJsonAtomic(join6(outputDir, RESULT_FILE), result);
|
|
4308
|
+
return result;
|
|
4309
|
+
}
|
|
4310
|
+
|
|
4311
|
+
// src/commands/lanhu.ts
|
|
4312
|
+
var defaultDependencies6 = {
|
|
4313
|
+
writer: {
|
|
4314
|
+
stdout: (value) => process.stdout.write(`${value}
|
|
4315
|
+
`),
|
|
4316
|
+
stderr: (value) => process.stderr.write(`${value}
|
|
4317
|
+
`),
|
|
4318
|
+
isTTY: () => Boolean(process.stdout.isTTY)
|
|
4319
|
+
},
|
|
4320
|
+
env: process.env,
|
|
4321
|
+
createAuthService: buildLanhuAuthService
|
|
4322
|
+
};
|
|
4323
|
+
function outputMode5(command, env) {
|
|
4324
|
+
const options = command.optsWithGlobals();
|
|
4325
|
+
const output = options.json ? "json" : options.output ?? env.DTSTACK_OUTPUT ?? "auto";
|
|
4326
|
+
if (!["auto", "human", "json"].includes(output)) {
|
|
4327
|
+
throw new CliError("invalid_argument", `\u4E0D\u652F\u6301\u7684\u8F93\u51FA\u6A21\u5F0F\uFF1A${output}`);
|
|
4328
|
+
}
|
|
4329
|
+
return output;
|
|
4330
|
+
}
|
|
4331
|
+
function renderDownload(data) {
|
|
4332
|
+
return [
|
|
4333
|
+
`\u4E0B\u8F7D\u5B8C\u6210\uFF1A${data.outputDir}`,
|
|
4334
|
+
`\u540D\u79F0\uFF1A${data.name} \u9875\u6570\uFF1A${data.totalPages}`,
|
|
4335
|
+
`\u7ED3\u679C\u6587\u4EF6\uFF1A${data.resultFile}`
|
|
4336
|
+
].join("\n");
|
|
4337
|
+
}
|
|
4338
|
+
async function run4(name, command, action, dependencies) {
|
|
4339
|
+
const startedAt = Date.now();
|
|
4340
|
+
const requestId = randomUUID9();
|
|
4341
|
+
let mode = "auto";
|
|
4342
|
+
try {
|
|
4343
|
+
mode = outputMode5(command, dependencies.env);
|
|
4344
|
+
const data = await action();
|
|
4345
|
+
printResult(success(data, name, startedAt, requestId), mode, renderDownload, dependencies.writer);
|
|
4346
|
+
} catch (error) {
|
|
4347
|
+
printResult(failure(lanhuToCliError(error), name, startedAt, requestId), mode, renderDownload, dependencies.writer);
|
|
4348
|
+
process.exitCode = 1;
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
4351
|
+
function resolveDownload(url, options, dependencies) {
|
|
4352
|
+
if (dependencies.download !== void 0) return dependencies.download(url, options);
|
|
4353
|
+
const authService = (dependencies.createAuthService ?? buildLanhuAuthService)();
|
|
4354
|
+
return downloadPrd({
|
|
4355
|
+
url,
|
|
4356
|
+
ensureJar: () => authService.authenticatedJar(),
|
|
4357
|
+
...options
|
|
4358
|
+
});
|
|
4359
|
+
}
|
|
4360
|
+
function registerLanhuCommands(program, dependencies = defaultDependencies6) {
|
|
4361
|
+
const lanhu = program.command("lanhu").description("\u84DD\u6E56 PRD / Axure \u539F\u578B\u4E0B\u8F7D");
|
|
4362
|
+
const prd = lanhu.command("prd").description("\u4E0B\u8F7D\u84DD\u6E56 PRD / Axure \u539F\u578B");
|
|
4363
|
+
prd.command("download").description("\u6839\u636E\u84DD\u6E56\u5206\u4EAB\u94FE\u63A5\u4E0B\u8F7D PRD \u9875\u9762\u8D44\u6E90").argument("<url>", "\u84DD\u6E56\u5206\u4EAB\u94FE\u63A5").option("-o, --output-dir <dir>", "\u8F93\u51FA\u76EE\u5F55\uFF08\u9ED8\u8BA4 ./tmp\uFF09", "./tmp").option("--extractor-path <path>", "LanhuExtractor \u811A\u672C\u8DEF\u5F84").option("--force-update", "\u5FFD\u7565\u7F13\u5B58\u5E76\u5F3A\u5236\u91CD\u65B0\u4E0B\u8F7D", false).action(
|
|
4364
|
+
async (url, options, command) => {
|
|
4365
|
+
await run4(
|
|
4366
|
+
"lanhu.prd.download",
|
|
4367
|
+
command,
|
|
4368
|
+
async () => {
|
|
4369
|
+
const requestOptions = {
|
|
4370
|
+
outputDir: options.outputDir,
|
|
4371
|
+
forceUpdate: options.forceUpdate
|
|
4372
|
+
};
|
|
4373
|
+
if (options.extractorPath !== void 0) {
|
|
4374
|
+
requestOptions.extractorPath = options.extractorPath;
|
|
4375
|
+
}
|
|
4376
|
+
const result = await resolveDownload(url, requestOptions, dependencies);
|
|
4377
|
+
return {
|
|
4378
|
+
outputDir: options.outputDir,
|
|
4379
|
+
resultFile: join7(options.outputDir, "result.json"),
|
|
4380
|
+
...result
|
|
4381
|
+
};
|
|
4382
|
+
},
|
|
4383
|
+
dependencies
|
|
4384
|
+
);
|
|
4385
|
+
}
|
|
4386
|
+
);
|
|
4387
|
+
}
|
|
4388
|
+
|
|
4389
|
+
// src/cli.ts
|
|
4390
|
+
function rewriteSingleDashLongFlag(arg) {
|
|
4391
|
+
return /^-[A-Za-z][A-Za-z0-9-]+$/.test(arg) ? `-${arg}` : arg;
|
|
4392
|
+
}
|
|
4393
|
+
function withSingleDashSupport(program) {
|
|
4394
|
+
const rewrite = (argv = []) => argv.map(rewriteSingleDashLongFlag);
|
|
4395
|
+
const originalParse = program.parse.bind(program);
|
|
4396
|
+
const originalParseAsync = program.parseAsync.bind(program);
|
|
4397
|
+
program.parse = ((argv, parseOptions) => originalParse(argv === void 0 ? argv : rewrite(argv), parseOptions));
|
|
4398
|
+
program.parseAsync = ((argv, parseOptions) => originalParseAsync(argv === void 0 ? argv : rewrite(argv), parseOptions));
|
|
4399
|
+
return program;
|
|
4400
|
+
}
|
|
4401
|
+
function packageVersion() {
|
|
4402
|
+
try {
|
|
4403
|
+
const raw = readFileSync(new URL("../package.json", import.meta.url), "utf8");
|
|
4404
|
+
const parsed = JSON.parse(raw);
|
|
4405
|
+
return typeof parsed.version === "string" ? parsed.version : "0.0.0";
|
|
4406
|
+
} catch {
|
|
4407
|
+
return "0.0.0";
|
|
4408
|
+
}
|
|
4409
|
+
}
|
|
4410
|
+
function createProgram(dependencies) {
|
|
4411
|
+
const program = new Command();
|
|
4412
|
+
program.name("dt").description("DTStack developer CLI").version(packageVersion()).option("--base-url <url>", "\u7985\u9053 API \u670D\u52A1\u5730\u5740").option("--omp-base-url <url>", "OMP API \u670D\u52A1\u5730\u5740").option("--output <mode>", "\u8F93\u51FA\u683C\u5F0F\uFF1Aauto\u3001human\u3001json", "auto").option("--json", "\u7B49\u4EF7\u4E8E -output json");
|
|
4413
|
+
const legacyBugDependencies = dependencies && "writer" in dependencies ? dependencies : void 0;
|
|
4414
|
+
const groupedDependencies = dependencies && !("writer" in dependencies) ? dependencies : void 0;
|
|
4415
|
+
registerAuthCommands(program, groupedDependencies?.auth);
|
|
4416
|
+
registerBugCommands(program, legacyBugDependencies ?? groupedDependencies?.bug);
|
|
4417
|
+
registerMrCommands(program, groupedDependencies?.mr);
|
|
4418
|
+
registerBranchCommands(program, groupedDependencies?.branch);
|
|
4419
|
+
registerOmpCommands(program, groupedDependencies?.omp);
|
|
4420
|
+
registerLanhuCommands(program, groupedDependencies?.lanhu);
|
|
4421
|
+
return withSingleDashSupport(program);
|
|
4422
|
+
}
|
|
4423
|
+
|
|
4424
|
+
// src/index.ts
|
|
4425
|
+
await createProgram().parseAsync(process.argv);
|