@lark-apaas/miaoda-cli 0.1.0-alpha.3879164 → 0.1.0-alpha.4177673
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.
- package/dist/api/db/api.js +9 -47
- package/dist/api/db/client.js +10 -2
- package/dist/api/db/parsers.js +1 -4
- package/dist/api/file/client.js +0 -26
- package/dist/cli/handlers/db/schema.js +6 -6
- package/dist/cli/handlers/db/sql.js +5 -3
- package/dist/utils/output.js +5 -5
- package/dist/utils/render.js +32 -2
- package/package.json +1 -1
- package/dist/api/db/_debug_trace.js +0 -76
- package/dist/api/file/_debug_trace.js +0 -63
package/dist/api/db/api.js
CHANGED
|
@@ -5,8 +5,6 @@ exports.getSchema = getSchema;
|
|
|
5
5
|
exports.importData = importData;
|
|
6
6
|
exports.exportData = exportData;
|
|
7
7
|
const http_1 = require("../../utils/http");
|
|
8
|
-
// TODO(REMOVE-BEFORE-RELEASE): debug-only HTTP trace(详见 _debug_trace.ts)
|
|
9
|
-
const _debug_trace_1 = require("./_debug_trace");
|
|
10
8
|
const error_1 = require("../../utils/error");
|
|
11
9
|
const client_1 = require("./client");
|
|
12
10
|
// CLI 不再为 dbBranch 设默认值:
|
|
@@ -26,16 +24,7 @@ async function execSql(opts) {
|
|
|
26
24
|
const url = (0, client_1.buildInnerUrl)(opts.appId, "/db/sql", {
|
|
27
25
|
dbBranch: opts.dbBranch,
|
|
28
26
|
});
|
|
29
|
-
|
|
30
|
-
try {
|
|
31
|
-
(0, _debug_trace_1.traceRequest)("POST", url, client);
|
|
32
|
-
response = await client.post(url, { sql: opts.sql });
|
|
33
|
-
(0, _debug_trace_1.traceResponse)("POST", url, response.status, response.headers, client);
|
|
34
|
-
}
|
|
35
|
-
catch (err) {
|
|
36
|
-
(0, _debug_trace_1.traceError)("POST", url, err, client);
|
|
37
|
-
throw err;
|
|
38
|
-
}
|
|
27
|
+
const response = await client.post(url, { sql: opts.sql });
|
|
39
28
|
if (!response.ok) {
|
|
40
29
|
// 4xx / 5xx:尝试解析 body 取 status_code 映射业务错误
|
|
41
30
|
let body = null;
|
|
@@ -68,16 +57,7 @@ async function getSchema(opts) {
|
|
|
68
57
|
includeStats: opts.includeStats ? "true" : undefined,
|
|
69
58
|
dbBranch: opts.dbBranch,
|
|
70
59
|
});
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
(0, _debug_trace_1.traceRequest)("GET", url, client);
|
|
74
|
-
response = await client.get(url);
|
|
75
|
-
(0, _debug_trace_1.traceResponse)("GET", url, response.status, response.headers, client);
|
|
76
|
-
}
|
|
77
|
-
catch (err) {
|
|
78
|
-
(0, _debug_trace_1.traceError)("GET", url, err, client);
|
|
79
|
-
throw err;
|
|
80
|
-
}
|
|
60
|
+
const response = await client.get(url);
|
|
81
61
|
if (!response.ok) {
|
|
82
62
|
let body = null;
|
|
83
63
|
try {
|
|
@@ -109,21 +89,12 @@ async function importData(opts) {
|
|
|
109
89
|
});
|
|
110
90
|
const contentType = opts.format === "csv" ? "text/csv" : "application/json";
|
|
111
91
|
const ab = opts.body.buffer.slice(opts.body.byteOffset, opts.body.byteOffset + opts.body.byteLength);
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
headers: { "Content-Type": contentType },
|
|
119
|
-
body: ab,
|
|
120
|
-
});
|
|
121
|
-
(0, _debug_trace_1.traceResponse)("POST", url, response.status, response.headers, client);
|
|
122
|
-
}
|
|
123
|
-
catch (err) {
|
|
124
|
-
(0, _debug_trace_1.traceError)("POST", url, err, client);
|
|
125
|
-
throw err;
|
|
126
|
-
}
|
|
92
|
+
const response = await client.request({
|
|
93
|
+
method: "POST",
|
|
94
|
+
url,
|
|
95
|
+
headers: { "Content-Type": contentType },
|
|
96
|
+
body: ab,
|
|
97
|
+
});
|
|
127
98
|
if (!response.ok) {
|
|
128
99
|
let body = null;
|
|
129
100
|
try {
|
|
@@ -160,16 +131,7 @@ async function exportData(opts) {
|
|
|
160
131
|
dbBranch: opts.dbBranch,
|
|
161
132
|
});
|
|
162
133
|
const reqBody = { limit: opts.limit ?? 5000 };
|
|
163
|
-
|
|
164
|
-
try {
|
|
165
|
-
(0, _debug_trace_1.traceRequest)("POST", url, client);
|
|
166
|
-
response = await client.post(url, reqBody);
|
|
167
|
-
(0, _debug_trace_1.traceResponse)("POST", url, response.status, response.headers, client);
|
|
168
|
-
}
|
|
169
|
-
catch (err) {
|
|
170
|
-
(0, _debug_trace_1.traceError)("POST", url, err, client);
|
|
171
|
-
throw err;
|
|
172
|
-
}
|
|
134
|
+
const response = await client.post(url, reqBody);
|
|
173
135
|
if (!response.ok) {
|
|
174
136
|
// 错误路径:body 是 JSON envelope
|
|
175
137
|
let body = null;
|
package/dist/api/db/client.js
CHANGED
|
@@ -19,7 +19,7 @@ function ensureInnerSuccess(body) {
|
|
|
19
19
|
const code = body.status_code ?? body.ErrorCode ?? "0";
|
|
20
20
|
if (code === "0" || code === "")
|
|
21
21
|
return;
|
|
22
|
-
const message = body.error_msg ?? body.ErrorMessage ?? `dataloom API error [${code}]
|
|
22
|
+
const message = stripPgPrefix(body.error_msg ?? body.ErrorMessage ?? `dataloom API error [${code}]`);
|
|
23
23
|
// k_dl_1300002 是 PG 执行透传错误;error_msg 里常带 SQLSTATE,优先按 SQLSTATE 映射
|
|
24
24
|
if (code === "k_dl_1300002") {
|
|
25
25
|
const sqlstate = extractSqlstate(message);
|
|
@@ -35,7 +35,7 @@ function ensureInnerSuccess(body) {
|
|
|
35
35
|
if (code === "k_dl_1600000" && message.startsWith("Invalid DB Branch")) {
|
|
36
36
|
throw new error_1.AppError("MULTI_ENV_NOT_INITIALIZED", "--env is not available (multi-env not initialized)", {
|
|
37
37
|
next_actions: [
|
|
38
|
-
"Verify the --env value matches an existing dbBranch
|
|
38
|
+
"Verify the --env value matches an existing dbBranch.",
|
|
39
39
|
],
|
|
40
40
|
});
|
|
41
41
|
}
|
|
@@ -49,6 +49,14 @@ function ensureInnerSuccess(body) {
|
|
|
49
49
|
// 兜底:dataloom 未映射的 code 原样透传
|
|
50
50
|
throw new error_1.AppError(`DB_API_${code}`, message);
|
|
51
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* 剥掉 PG 透传错误的 "ERROR:" 前缀:CLI 输出本身就会前缀 "Error:",
|
|
54
|
+
* 不去掉就会变成 `Error: ERROR: relation ...` 双重前缀,PRD 不要这种冗余。
|
|
55
|
+
* 大小写敏感,只匹配 PG 标准格式。
|
|
56
|
+
*/
|
|
57
|
+
function stripPgPrefix(msg) {
|
|
58
|
+
return msg.replace(/^ERROR:\s*/, "");
|
|
59
|
+
}
|
|
52
60
|
/** 从 PG 执行错误消息里提取 "(SQLSTATE XXXXX)"。 */
|
|
53
61
|
function extractSqlstate(msg) {
|
|
54
62
|
const m = /SQLSTATE\s+([0-9A-Z]{5})/.exec(msg);
|
package/dist/api/db/parsers.js
CHANGED
|
@@ -27,7 +27,7 @@ function parseSqlResult(r) {
|
|
|
27
27
|
recordCount: r.recordCount ?? rows.length,
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
|
-
if (r.sqlType === "INSERT" || r.sqlType === "UPDATE" || r.sqlType === "DELETE") {
|
|
30
|
+
if (r.sqlType === "INSERT" || r.sqlType === "UPDATE" || r.sqlType === "DELETE" || r.sqlType === "DML") {
|
|
31
31
|
const affected = r.affectedRows ?? extractRowCount(r.data);
|
|
32
32
|
return {
|
|
33
33
|
kind: "dml",
|
|
@@ -82,7 +82,6 @@ function toSummary(t, stats) {
|
|
|
82
82
|
columns: (t.fields ?? []).length,
|
|
83
83
|
estimated_row_count: typeof stats?.estimatedRowCount === "number" ? stats.estimatedRowCount : null,
|
|
84
84
|
size_bytes: typeof stats?.sizeBytes === "number" ? stats.sizeBytes : null,
|
|
85
|
-
updated_at: t.updatedAt,
|
|
86
85
|
};
|
|
87
86
|
}
|
|
88
87
|
/**
|
|
@@ -118,8 +117,6 @@ function toDetail(t, stats) {
|
|
|
118
117
|
indexes: rawIndexes.map(toIndex),
|
|
119
118
|
estimated_row_count: typeof stats?.estimatedRowCount === "number" ? stats.estimatedRowCount : null,
|
|
120
119
|
size_bytes: typeof stats?.sizeBytes === "number" ? stats.sizeBytes : null,
|
|
121
|
-
created_at: t.createdAt,
|
|
122
|
-
updated_at: t.updatedAt,
|
|
123
120
|
};
|
|
124
121
|
}
|
|
125
122
|
function toColumn(f) {
|
package/dist/api/file/client.js
CHANGED
|
@@ -8,8 +8,6 @@ exports.doPost = doPost;
|
|
|
8
8
|
exports.doRequest = doRequest;
|
|
9
9
|
const http_1 = require("../../utils/http");
|
|
10
10
|
const error_1 = require("../../utils/error");
|
|
11
|
-
// TODO(REMOVE-BEFORE-RELEASE): debug-only HTTP trace(详见 _debug_trace.ts)
|
|
12
|
-
const _debug_trace_1 = require("./_debug_trace");
|
|
13
11
|
const http_client_1 = require("@lark-apaas/http-client");
|
|
14
12
|
/** 进程内 bucket 缓存:{appId: bucketId}。不跨进程。 */
|
|
15
13
|
const bucketCache = new Map();
|
|
@@ -133,18 +131,10 @@ async function mapHttpError(err, opts) {
|
|
|
133
131
|
*/
|
|
134
132
|
async function doGet(url, opts = {}, client = (0, http_1.getHttpClient)()) {
|
|
135
133
|
try {
|
|
136
|
-
(0, _debug_trace_1.traceRequest)("GET", url, client);
|
|
137
134
|
const response = await client.get(url);
|
|
138
|
-
(0, _debug_trace_1.traceResponse)("GET", url, response.status, response.headers, client);
|
|
139
135
|
return (await response.json());
|
|
140
136
|
}
|
|
141
137
|
catch (err) {
|
|
142
|
-
if (err instanceof http_client_1.HttpError && err.response) {
|
|
143
|
-
(0, _debug_trace_1.traceResponse)("GET", url, err.response.status, err.response.headers, client);
|
|
144
|
-
}
|
|
145
|
-
else {
|
|
146
|
-
(0, _debug_trace_1.traceError)("GET", url, err, client);
|
|
147
|
-
}
|
|
148
138
|
await mapHttpError(err, opts);
|
|
149
139
|
throw err; // 不可达,mapHttpError 必定 throw
|
|
150
140
|
}
|
|
@@ -152,18 +142,10 @@ async function doGet(url, opts = {}, client = (0, http_1.getHttpClient)()) {
|
|
|
152
142
|
/** 包一层 client.post + HttpError 统一映射。默认 admin innerapi,可显式切 runtime。 */
|
|
153
143
|
async function doPost(url, body, opts = {}, client = (0, http_1.getHttpClient)()) {
|
|
154
144
|
try {
|
|
155
|
-
(0, _debug_trace_1.traceRequest)("POST", url, client);
|
|
156
145
|
const response = await client.post(url, body);
|
|
157
|
-
(0, _debug_trace_1.traceResponse)("POST", url, response.status, response.headers, client);
|
|
158
146
|
return (await response.json());
|
|
159
147
|
}
|
|
160
148
|
catch (err) {
|
|
161
|
-
if (err instanceof http_client_1.HttpError && err.response) {
|
|
162
|
-
(0, _debug_trace_1.traceResponse)("POST", url, err.response.status, err.response.headers, client);
|
|
163
|
-
}
|
|
164
|
-
else {
|
|
165
|
-
(0, _debug_trace_1.traceError)("POST", url, err, client);
|
|
166
|
-
}
|
|
167
149
|
await mapHttpError(err, opts);
|
|
168
150
|
throw err;
|
|
169
151
|
}
|
|
@@ -171,18 +153,10 @@ async function doPost(url, body, opts = {}, client = (0, http_1.getHttpClient)()
|
|
|
171
153
|
/** 包一层 client.request + HttpError 统一映射(DELETE 带 body 的场景)。 */
|
|
172
154
|
async function doRequest(cfg, opts = {}, client = (0, http_1.getHttpClient)()) {
|
|
173
155
|
try {
|
|
174
|
-
(0, _debug_trace_1.traceRequest)(cfg.method, cfg.url, client);
|
|
175
156
|
const response = await client.request(cfg);
|
|
176
|
-
(0, _debug_trace_1.traceResponse)(cfg.method, cfg.url, response.status, response.headers, client);
|
|
177
157
|
return (await response.json());
|
|
178
158
|
}
|
|
179
159
|
catch (err) {
|
|
180
|
-
if (err instanceof http_client_1.HttpError && err.response) {
|
|
181
|
-
(0, _debug_trace_1.traceResponse)(cfg.method, cfg.url, err.response.status, err.response.headers, client);
|
|
182
|
-
}
|
|
183
|
-
else {
|
|
184
|
-
(0, _debug_trace_1.traceError)(cfg.method, cfg.url, err, client);
|
|
185
|
-
}
|
|
186
160
|
await mapHttpError(err, opts);
|
|
187
161
|
throw err;
|
|
188
162
|
}
|
|
@@ -55,14 +55,14 @@ async function handleDbSchemaList(opts) {
|
|
|
55
55
|
return;
|
|
56
56
|
}
|
|
57
57
|
const tty = (0, render_1.isStdoutTty)();
|
|
58
|
-
// PRD 对齐:TTY 表头用 `size`(友好格式),non-TTY 用 `size_bytes
|
|
58
|
+
// PRD 对齐:TTY 表头用 `size`(友好格式),non-TTY 用 `size_bytes`(原始整数)。
|
|
59
|
+
// updated_at 暂时不展示——PG pg_catalog 不存真实表时间,详见 renderDetail 注释。
|
|
59
60
|
const headers = [
|
|
60
61
|
"name",
|
|
61
62
|
"description",
|
|
62
63
|
"estimated_row_count",
|
|
63
64
|
tty ? "size" : "size_bytes",
|
|
64
65
|
"columns",
|
|
65
|
-
"updated_at",
|
|
66
66
|
];
|
|
67
67
|
const rows = tables.map((t) => [
|
|
68
68
|
t.name,
|
|
@@ -70,7 +70,6 @@ async function handleDbSchemaList(opts) {
|
|
|
70
70
|
t.estimated_row_count === null ? "—" : String(t.estimated_row_count),
|
|
71
71
|
t.size_bytes === null ? "—" : (tty ? (0, render_1.formatSize)(t.size_bytes) : String(t.size_bytes)),
|
|
72
72
|
String(t.columns),
|
|
73
|
-
(0, render_1.formatTime)(t.updated_at, tty),
|
|
74
73
|
]);
|
|
75
74
|
(0, output_1.emit)(tty ? (0, render_1.renderAlignedTable)(headers, rows) : (0, render_1.renderTsv)(headers, rows));
|
|
76
75
|
}
|
|
@@ -123,7 +122,10 @@ async function handleDbSchemaGet(table, opts) {
|
|
|
123
122
|
function renderDetail(d, tty) {
|
|
124
123
|
const systemFields = d.columns.filter((c) => c.name.startsWith("_"));
|
|
125
124
|
const userFields = d.columns.filter((c) => !c.name.startsWith("_"));
|
|
126
|
-
//
|
|
125
|
+
// header 布局:Name / Description / Columns(含"+ N system") / Estimated Rows / Size。
|
|
126
|
+
// 不展示 Created / Updated:PG pg_catalog 不存表创建时间,dataloom 用 OID
|
|
127
|
+
// 构造的伪时间戳(baseTime=2020-01-01 + OID 秒偏移),仅保排序意义、绝对值
|
|
128
|
+
// 误导性强,先去掉。后续如果接 ddl_change_log 取真实时间再加回。
|
|
127
129
|
const header = [
|
|
128
130
|
["Name", d.name],
|
|
129
131
|
["Description", d.description ?? "—"],
|
|
@@ -135,8 +137,6 @@ function renderDetail(d, tty) {
|
|
|
135
137
|
],
|
|
136
138
|
["Estimated Rows", d.estimated_row_count === null ? "—" : String(d.estimated_row_count)],
|
|
137
139
|
["Size", d.size_bytes === null ? "—" : (0, render_1.formatSize)(d.size_bytes)],
|
|
138
|
-
["Created", (0, render_1.formatTime)(d.created_at, tty)],
|
|
139
|
-
["Updated", (0, render_1.formatTime)(d.updated_at, tty)],
|
|
140
140
|
];
|
|
141
141
|
const colHeaders = ["column", "type", "nullable", "default", "comment"];
|
|
142
142
|
const colRows = userFields.map((c) => [
|
|
@@ -133,20 +133,22 @@ function toJson(parsed) {
|
|
|
133
133
|
return { data: parsed.rows };
|
|
134
134
|
}
|
|
135
135
|
if (parsed.kind === "dml") {
|
|
136
|
+
// PRD:DML 时 data = {command: "UPDATE", rows_affected: 3}
|
|
136
137
|
return {
|
|
137
138
|
data: {
|
|
138
|
-
|
|
139
|
-
|
|
139
|
+
command: parsed.sqlType,
|
|
140
|
+
rows_affected: parsed.affectedRows,
|
|
140
141
|
},
|
|
141
142
|
};
|
|
142
143
|
}
|
|
143
|
-
return { data: {
|
|
144
|
+
return { data: { command: "DDL" } };
|
|
144
145
|
}
|
|
145
146
|
function dmlVerb(type) {
|
|
146
147
|
switch (type) {
|
|
147
148
|
case "INSERT": return "inserted";
|
|
148
149
|
case "UPDATE": return "updated";
|
|
149
150
|
case "DELETE": return "deleted";
|
|
151
|
+
case "DML": return "affected"; // MERGE / 未识别子类的兜底
|
|
150
152
|
}
|
|
151
153
|
}
|
|
152
154
|
/** 从第一行收集列顺序;缺失列保留空白(兼容稀疏行)。 */
|
package/dist/utils/output.js
CHANGED
|
@@ -32,19 +32,19 @@ function emit(data) {
|
|
|
32
32
|
/**
|
|
33
33
|
* 输出错误(写入 stderr)
|
|
34
34
|
* - pretty 模式:Error: message\n hint: ...
|
|
35
|
-
* - json 模式:{
|
|
35
|
+
* - json 模式:PRD 约定 envelope 为 `{error: {code, message, hint?}}`
|
|
36
36
|
*/
|
|
37
37
|
function emitError(err) {
|
|
38
38
|
const info = toErrorInfo(err);
|
|
39
39
|
if (isJsonMode()) {
|
|
40
|
-
const
|
|
41
|
-
|
|
40
|
+
const errObj = {
|
|
41
|
+
code: info.code,
|
|
42
42
|
message: info.message,
|
|
43
43
|
};
|
|
44
44
|
if (info.next_actions && info.next_actions.length > 0) {
|
|
45
|
-
|
|
45
|
+
errObj.hint = info.next_actions.join(" ");
|
|
46
46
|
}
|
|
47
|
-
process.stderr.write(JSON.stringify(
|
|
47
|
+
process.stderr.write(JSON.stringify({ error: errObj }) + "\n");
|
|
48
48
|
}
|
|
49
49
|
else {
|
|
50
50
|
process.stderr.write(`Error: ${info.message}\n`);
|
package/dist/utils/render.js
CHANGED
|
@@ -71,9 +71,39 @@ function formatTime(iso, isTty) {
|
|
|
71
71
|
* 算进列宽(比如 dim "NULL" 实际占 4 字符但 .length=11),导致表格对齐错位。
|
|
72
72
|
*/
|
|
73
73
|
const ANSI_SGR_RE = /\[[0-9;]*m/g;
|
|
74
|
-
/**
|
|
74
|
+
/**
|
|
75
|
+
* 单字符的终端列宽:CJK 全角字符(汉字/假名/全角符号等)占 2 列,其它占 1 列。
|
|
76
|
+
* 对齐 Unicode East Asian Width 的 W/F 类,等价于 wcwidth 简化版。
|
|
77
|
+
* 不实现合字 / 零宽字符(ZWJ / 变体选择符)等极端情况,CLI 表格场景够用。
|
|
78
|
+
*/
|
|
79
|
+
function charWidth(cp) {
|
|
80
|
+
if ((cp >= 0x1100 && cp <= 0x115F) || // Hangul Jamo
|
|
81
|
+
cp === 0x2329 || cp === 0x232A ||
|
|
82
|
+
(cp >= 0x2E80 && cp <= 0x303E) || // CJK Radicals / Punctuation
|
|
83
|
+
(cp >= 0x3041 && cp <= 0x33FF) || // Hiragana / Katakana / CJK Symbols
|
|
84
|
+
(cp >= 0x3400 && cp <= 0x4DBF) || // CJK Ext A
|
|
85
|
+
(cp >= 0x4E00 && cp <= 0x9FFF) || // CJK Unified
|
|
86
|
+
(cp >= 0xA000 && cp <= 0xA4CF) || // Yi
|
|
87
|
+
(cp >= 0xAC00 && cp <= 0xD7A3) || // Hangul Syllables
|
|
88
|
+
(cp >= 0xF900 && cp <= 0xFAFF) || // CJK Compat Ideographs
|
|
89
|
+
(cp >= 0xFE30 && cp <= 0xFE4F) || // CJK Compat Forms
|
|
90
|
+
(cp >= 0xFF00 && cp <= 0xFF60) || // Fullwidth Forms
|
|
91
|
+
(cp >= 0xFFE0 && cp <= 0xFFE6) ||
|
|
92
|
+
(cp >= 0x20000 && cp <= 0x2FFFD) || // CJK Ext B-F
|
|
93
|
+
(cp >= 0x30000 && cp <= 0x3FFFD) // CJK Ext G-H
|
|
94
|
+
) {
|
|
95
|
+
return 2;
|
|
96
|
+
}
|
|
97
|
+
return 1;
|
|
98
|
+
}
|
|
99
|
+
/** cell 可见字符宽度:剥离 ANSI 转义后按终端列宽逐字符累加(CJK 算 2 列)。 */
|
|
75
100
|
function visibleWidth(s) {
|
|
76
|
-
|
|
101
|
+
const stripped = s.replace(ANSI_SGR_RE, "");
|
|
102
|
+
let w = 0;
|
|
103
|
+
for (const c of stripped) {
|
|
104
|
+
w += charWidth(c.codePointAt(0) ?? 0);
|
|
105
|
+
}
|
|
106
|
+
return w;
|
|
77
107
|
}
|
|
78
108
|
function padVisibleEnd(s, targetWidth) {
|
|
79
109
|
const w = visibleWidth(s);
|
package/package.json
CHANGED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.traceRequest = traceRequest;
|
|
4
|
-
exports.traceResponse = traceResponse;
|
|
5
|
-
exports.traceError = traceError;
|
|
6
|
-
const config_1 = require("../../utils/config");
|
|
7
|
-
const logger_1 = require("../../utils/logger");
|
|
8
|
-
/**
|
|
9
|
-
* 从 HttpClient 实例抠出 baseURL,用于把相对 path 拼成完整 URL 输出。
|
|
10
|
-
* defaultConfig.baseURL 在 http-client 0.1.4 d.ts 里没声明但运行时可访问;
|
|
11
|
-
* 找不到时返回空串(trace 仍能输出 path,只是不完整)。
|
|
12
|
-
*/
|
|
13
|
-
function clientBaseURL(client) {
|
|
14
|
-
return client?.defaultConfig?.baseURL ?? "";
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* 给 client 注册一个最后的 request interceptor:等 platform plugin / canary
|
|
18
|
-
* 等其它拦截器把 JWT / AK/SK / X-Miaoda-Client-Token / x-tt-env 注入 cfg.headers
|
|
19
|
-
* 之后,用注入完毕的 cfg 拼一行可直接复制运行的 curl 命令打到 stderr。
|
|
20
|
-
*
|
|
21
|
-
* 拦截器只装一次(用 client 实例的 Symbol 标记),verbose 关闭时拦截器内
|
|
22
|
-
* 直接 return(零开销)。
|
|
23
|
-
*/
|
|
24
|
-
function installCurlTrace(client) {
|
|
25
|
-
const c = client;
|
|
26
|
-
if (c.__miaoda_curl_trace_installed__)
|
|
27
|
-
return;
|
|
28
|
-
// 单测里的 mock client 没有 interceptors,直接 noop 避免炸测试。
|
|
29
|
-
const interceptors = client.interceptors;
|
|
30
|
-
if (!interceptors)
|
|
31
|
-
return;
|
|
32
|
-
c.__miaoda_curl_trace_installed__ = true;
|
|
33
|
-
interceptors.request.use((cfg) => {
|
|
34
|
-
if (!(0, config_1.getConfig)().verbose)
|
|
35
|
-
return cfg;
|
|
36
|
-
const method = (cfg.method ?? "GET").toUpperCase();
|
|
37
|
-
const url = `${cfg.baseURL ?? ""}${cfg.url ?? ""}`;
|
|
38
|
-
const parts = [`curl -i -X ${method} '${url}'`];
|
|
39
|
-
const headers = cfg.headers instanceof Headers
|
|
40
|
-
? cfg.headers
|
|
41
|
-
: new Headers(cfg.headers ?? {});
|
|
42
|
-
headers.forEach((v, k) => parts.push(` -H '${k}: ${v}'`));
|
|
43
|
-
if (cfg.body !== undefined && cfg.body !== null) {
|
|
44
|
-
let body;
|
|
45
|
-
if (typeof cfg.body === "string")
|
|
46
|
-
body = cfg.body;
|
|
47
|
-
else if (cfg.body instanceof ArrayBuffer || cfg.body instanceof Uint8Array)
|
|
48
|
-
body = "<binary>";
|
|
49
|
-
else
|
|
50
|
-
body = JSON.stringify(cfg.body);
|
|
51
|
-
const escaped = body.replace(/'/g, "'\\''");
|
|
52
|
-
parts.push(` -d '${escaped}'`);
|
|
53
|
-
}
|
|
54
|
-
(0, logger_1.debug)(`curl:\n${parts.join(" \\\n")}`);
|
|
55
|
-
return cfg;
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
/** 请求前打 method + 完整 URL;同时懒装 curl-trace 拦截器(idempotent)。 */
|
|
59
|
-
function traceRequest(method, url, client) {
|
|
60
|
-
if (client)
|
|
61
|
-
installCurlTrace(client);
|
|
62
|
-
(0, logger_1.debug)(`http → ${method} ${clientBaseURL(client)}${url}`);
|
|
63
|
-
}
|
|
64
|
-
/** 响应后打 status + x-tt-logid。 */
|
|
65
|
-
function traceResponse(method, url, status, headers, client) {
|
|
66
|
-
const logId = headers?.get("x-tt-logid") ?? headers?.get("X-Tt-Logid") ?? "(none)";
|
|
67
|
-
(0, logger_1.debug)(`http ← ${method} ${clientBaseURL(client)}${url} status=${String(status)} x-tt-logid=${logId}`);
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* 网络层错误(fetch failed / DNS / TLS / 连接拒绝)兜底:response 没回来,
|
|
71
|
-
* 没有 logid,但要把错误原因记到 trace,避免用户只看到 "Error: fetch failed"。
|
|
72
|
-
*/
|
|
73
|
-
function traceError(method, url, err, client) {
|
|
74
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
75
|
-
(0, logger_1.debug)(`http ✗ ${method} ${clientBaseURL(client)}${url} (no response, network-level error: ${msg})`);
|
|
76
|
-
}
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.traceRequest = traceRequest;
|
|
4
|
-
exports.traceResponse = traceResponse;
|
|
5
|
-
exports.traceError = traceError;
|
|
6
|
-
const config_1 = require("../../utils/config");
|
|
7
|
-
const logger_1 = require("../../utils/logger");
|
|
8
|
-
function clientBaseURL(client) {
|
|
9
|
-
return client?.defaultConfig?.baseURL ?? "";
|
|
10
|
-
}
|
|
11
|
-
function installCurlTrace(client) {
|
|
12
|
-
const c = client;
|
|
13
|
-
if (c.__miaoda_curl_trace_installed__)
|
|
14
|
-
return;
|
|
15
|
-
// 单测里的 mock client 没有 interceptors,直接 noop 避免炸测试。
|
|
16
|
-
const interceptors = client.interceptors;
|
|
17
|
-
if (!interceptors)
|
|
18
|
-
return;
|
|
19
|
-
c.__miaoda_curl_trace_installed__ = true;
|
|
20
|
-
interceptors.request.use((cfg) => {
|
|
21
|
-
if (!(0, config_1.getConfig)().verbose)
|
|
22
|
-
return cfg;
|
|
23
|
-
const method = (cfg.method ?? "GET").toUpperCase();
|
|
24
|
-
const url = `${cfg.baseURL ?? ""}${cfg.url ?? ""}`;
|
|
25
|
-
const parts = [`curl -i -X ${method} '${url}'`];
|
|
26
|
-
const headers = cfg.headers instanceof Headers
|
|
27
|
-
? cfg.headers
|
|
28
|
-
: new Headers(cfg.headers ?? {});
|
|
29
|
-
headers.forEach((v, k) => parts.push(` -H '${k}: ${v}'`));
|
|
30
|
-
if (cfg.body !== undefined && cfg.body !== null) {
|
|
31
|
-
let body;
|
|
32
|
-
if (typeof cfg.body === "string")
|
|
33
|
-
body = cfg.body;
|
|
34
|
-
else if (cfg.body instanceof ArrayBuffer || cfg.body instanceof Uint8Array)
|
|
35
|
-
body = "<binary>";
|
|
36
|
-
else
|
|
37
|
-
body = JSON.stringify(cfg.body);
|
|
38
|
-
const escaped = body.replace(/'/g, "'\\''");
|
|
39
|
-
parts.push(` -d '${escaped}'`);
|
|
40
|
-
}
|
|
41
|
-
(0, logger_1.debug)(`curl:\n${parts.join(" \\\n")}`);
|
|
42
|
-
return cfg;
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
/** 请求前打 method + 完整 URL;同时懒装 curl-trace 拦截器(idempotent)。 */
|
|
46
|
-
function traceRequest(method, url, client) {
|
|
47
|
-
if (client)
|
|
48
|
-
installCurlTrace(client);
|
|
49
|
-
(0, logger_1.debug)(`http → ${method} ${clientBaseURL(client)}${url}`);
|
|
50
|
-
}
|
|
51
|
-
/** 响应后打 status + x-tt-logid。 */
|
|
52
|
-
function traceResponse(method, url, status, headers, client) {
|
|
53
|
-
const logId = headers?.get("x-tt-logid") ?? headers?.get("X-Tt-Logid") ?? "(none)";
|
|
54
|
-
(0, logger_1.debug)(`http ← ${method} ${clientBaseURL(client)}${url} status=${String(status)} x-tt-logid=${logId}`);
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* 网络层错误(fetch failed / DNS / TLS / 连接拒绝)兜底:response 没回来,
|
|
58
|
-
* 没有 logid,但要把错误原因记到 trace,避免用户只看到 "Error: fetch failed"。
|
|
59
|
-
*/
|
|
60
|
-
function traceError(method, url, err, client) {
|
|
61
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
62
|
-
(0, logger_1.debug)(`http ✗ ${method} ${clientBaseURL(client)}${url} (no response, network-level error: ${msg})`);
|
|
63
|
-
}
|