@lark-apaas/miaoda-cli 0.1.3-alpha.67da0bb → 0.1.3-alpha.6e2a705

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.
Files changed (71) hide show
  1. package/README.md +5 -4
  2. package/dist/api/app/api.js +3 -3
  3. package/dist/api/app/schemas.js +43 -43
  4. package/dist/api/db/api.js +54 -361
  5. package/dist/api/db/client.js +24 -60
  6. package/dist/api/db/index.js +1 -11
  7. package/dist/api/db/parsers.js +20 -20
  8. package/dist/api/db/sql-keywords.js +87 -87
  9. package/dist/api/deploy/api.js +5 -5
  10. package/dist/api/deploy/schemas.js +32 -32
  11. package/dist/api/file/api.js +87 -89
  12. package/dist/api/file/client.js +22 -22
  13. package/dist/api/file/detect.js +3 -3
  14. package/dist/api/file/index.js +1 -2
  15. package/dist/api/file/parsers.js +7 -18
  16. package/dist/api/observability/api.js +16 -6
  17. package/dist/api/observability/index.js +2 -1
  18. package/dist/api/observability/schemas.js +14 -14
  19. package/dist/api/plugin/api.js +31 -31
  20. package/dist/cli/commands/app/index.js +12 -12
  21. package/dist/cli/commands/db/index.js +54 -593
  22. package/dist/cli/commands/deploy/index.js +28 -28
  23. package/dist/cli/commands/file/index.js +57 -84
  24. package/dist/cli/commands/observability/index.js +128 -72
  25. package/dist/cli/commands/plugin/index.js +27 -27
  26. package/dist/cli/commands/shared.js +15 -10
  27. package/dist/cli/handlers/app/update.js +2 -2
  28. package/dist/cli/handlers/db/data.js +31 -32
  29. package/dist/cli/handlers/db/index.js +1 -17
  30. package/dist/cli/handlers/db/schema.js +33 -33
  31. package/dist/cli/handlers/db/sql.js +69 -69
  32. package/dist/cli/handlers/deploy/deploy.js +4 -4
  33. package/dist/cli/handlers/deploy/error-log.js +1 -1
  34. package/dist/cli/handlers/deploy/get.js +3 -3
  35. package/dist/cli/handlers/deploy/polling.js +11 -11
  36. package/dist/cli/handlers/file/cp.js +30 -30
  37. package/dist/cli/handlers/file/index.js +1 -3
  38. package/dist/cli/handlers/file/ls.js +5 -5
  39. package/dist/cli/handlers/file/rm.js +24 -24
  40. package/dist/cli/handlers/file/sign.js +3 -3
  41. package/dist/cli/handlers/file/stat.js +9 -10
  42. package/dist/cli/handlers/observability/analytics.js +47 -47
  43. package/dist/cli/handlers/observability/helpers.js +6 -2
  44. package/dist/cli/handlers/observability/index.js +3 -1
  45. package/dist/cli/handlers/observability/log.js +15 -9
  46. package/dist/cli/handlers/observability/metric.js +26 -26
  47. package/dist/cli/handlers/observability/source-stack.js +353 -0
  48. package/dist/cli/handlers/observability/trace.js +11 -5
  49. package/dist/cli/handlers/plugin/plugin-local.js +53 -53
  50. package/dist/cli/handlers/plugin/plugin.js +15 -15
  51. package/dist/cli/help.js +16 -16
  52. package/dist/main.js +12 -12
  53. package/dist/utils/args.js +1 -1
  54. package/dist/utils/colors.js +2 -2
  55. package/dist/utils/config.js +2 -2
  56. package/dist/utils/devops-error.js +9 -9
  57. package/dist/utils/error.js +2 -2
  58. package/dist/utils/git.js +4 -4
  59. package/dist/utils/http.js +19 -19
  60. package/dist/utils/index.js +1 -3
  61. package/dist/utils/output.js +45 -67
  62. package/dist/utils/render.js +27 -27
  63. package/dist/utils/time.js +42 -47
  64. package/package.json +1 -1
  65. package/dist/cli/handlers/db/audit.js +0 -294
  66. package/dist/cli/handlers/db/changelog.js +0 -130
  67. package/dist/cli/handlers/db/migration.js +0 -235
  68. package/dist/cli/handlers/db/quota.js +0 -68
  69. package/dist/cli/handlers/db/recovery.js +0 -357
  70. package/dist/cli/handlers/file/quota.js +0 -66
  71. package/dist/utils/poll.js +0 -27
@@ -8,10 +8,8 @@ exports.uploadFile = uploadFile;
8
8
  exports.signDownload = signDownload;
9
9
  exports.downloadFile = downloadFile;
10
10
  exports.deleteFiles = deleteFiles;
11
- exports.getStorageQuota = getStorageQuota;
12
11
  const error_1 = require("../../utils/error");
13
12
  const logger_1 = require("../../utils/logger");
14
- const time_1 = require("../../utils/time");
15
13
  const client_1 = require("./client");
16
14
  const detect_1 = require("./detect");
17
15
  const parsers_1 = require("./parsers");
@@ -21,18 +19,18 @@ const parsers_1 = require("./parsers");
21
19
  * 所有进入 API 层的 path 都要 strip 前导 `/`。
22
20
  */
23
21
  function toApiPath(filePath) {
24
- return filePath.replace(/^\/+/, '');
22
+ return filePath.replace(/^\/+/, "");
25
23
  }
26
24
  function encodePath(filePath) {
27
25
  return toApiPath(filePath)
28
- .split('/')
26
+ .split("/")
29
27
  .map((seg) => encodeURIComponent(seg))
30
- .join('/');
28
+ .join("/");
31
29
  }
32
30
  function extractEnvelope(body) {
33
31
  (0, client_1.ensureSuccess)(body);
34
32
  if (!body.data) {
35
- throw new error_1.AppError('INTERNAL_FILE_API_ERROR', 'API returned empty data');
33
+ throw new error_1.AppError("INTERNAL_FILE_API_ERROR", "API returned empty data");
36
34
  }
37
35
  return body.data;
38
36
  }
@@ -51,7 +49,7 @@ async function listOnce(appId, bucketId, opts) {
51
49
  if (opts.sortBy && opts.sortBy.length > 0)
52
50
  reqBody.sortBy = opts.sortBy;
53
51
  const body = await (0, client_1.doPost)(url, reqBody, {
54
- errorContext: 'list files',
52
+ errorContext: "list files",
55
53
  });
56
54
  return extractEnvelope(body);
57
55
  }
@@ -72,29 +70,29 @@ function buildFilterExpr(opts) {
72
70
  return opts.filterExpr;
73
71
  const conds = [];
74
72
  if (opts.name) {
75
- conds.push({ field: 'name', operator: 'eq', value: opts.name });
73
+ conds.push({ field: "name", operator: "eq", value: opts.name });
76
74
  }
77
75
  if (opts.type) {
78
- conds.push({ field: 'type', operator: 'eq', value: opts.type });
76
+ conds.push({ field: "type", operator: "eq", value: opts.type });
79
77
  }
80
78
  if (opts.sizeGt !== undefined) {
81
- conds.push({ field: 'size', operator: 'gt', value: String(opts.sizeGt) });
79
+ conds.push({ field: "size", operator: "gt", value: String(opts.sizeGt) });
82
80
  }
83
81
  if (opts.sizeLt !== undefined) {
84
- conds.push({ field: 'size', operator: 'lt', value: String(opts.sizeLt) });
82
+ conds.push({ field: "size", operator: "lt", value: String(opts.sizeLt) });
85
83
  }
86
84
  if (opts.uploadedSince) {
87
85
  // 后端期望毫秒 timestamp(strconv.ParseInt → time.UnixMilli)
88
- const ms = parseTimeFilterMs(opts.uploadedSince, '--uploaded-since');
89
- conds.push({ field: 'createdAt', operator: 'gte', value: String(ms) });
86
+ const ms = parseTimeFilterMs(opts.uploadedSince, "--uploaded-since");
87
+ conds.push({ field: "createdAt", operator: "gte", value: String(ms) });
90
88
  }
91
89
  if (opts.uploadedUntil) {
92
- const ms = parseTimeFilterMs(opts.uploadedUntil, '--uploaded-until');
93
- conds.push({ field: 'createdAt', operator: 'lte', value: String(ms) });
90
+ const ms = parseTimeFilterMs(opts.uploadedUntil, "--uploaded-until");
91
+ conds.push({ field: "createdAt", operator: "lte", value: String(ms) });
94
92
  }
95
93
  if (conds.length === 0)
96
94
  return undefined;
97
- return { logic: 'and', groups: [{ conditions: conds }] };
95
+ return { logic: "and", groups: [{ conditions: conds }] };
98
96
  }
99
97
  /**
100
98
  * 解析时间过滤参数(--uploaded-since / --uploaded-until)的三种输入格式
@@ -109,17 +107,31 @@ function buildFilterExpr(opts) {
109
107
  * flagName 用于错误信息,调用方传 "--uploaded-since" 或 "--uploaded-until"。
110
108
  */
111
109
  function parseTimeFilterMs(input, flagName) {
112
- try {
113
- return (0, time_1.parseTimeToMs)(input);
114
- }
115
- catch (err) {
116
- if (err instanceof error_1.AppError) {
117
- throw new error_1.AppError(err.code, `${flagName}: ${err.message}`, {
118
- next_actions: err.next_actions,
119
- });
110
+ // 相对时间:<positive int><unit>,单位 s/m/h/d/w
111
+ const RELATIVE = /^(\d+)([smhdw])$/;
112
+ const rel = RELATIVE.exec(input);
113
+ if (rel) {
114
+ const n = parseInt(rel[1], 10);
115
+ if (n <= 0) {
116
+ throw new error_1.AppError("ARGS_INVALID", `${flagName} "${input}" 必须是正整数 + 单位(s / m / h / d / w)`);
120
117
  }
121
- throw err;
118
+ const UNIT_MS = {
119
+ s: 1_000,
120
+ m: 60_000,
121
+ h: 3_600_000,
122
+ d: 86_400_000,
123
+ w: 604_800_000,
124
+ };
125
+ return Date.now() - n * UNIT_MS[rel[2]];
126
+ }
127
+ // 绝对时间:date / ISO 8601。Date.parse 对 "YYYY-MM-DD" 按 UTC 00:00:00 解析,
128
+ // 对带 Z 的 ISO 8601 也直接出 UTC ms。
129
+ const ms = Date.parse(input);
130
+ if (Number.isNaN(ms)) {
131
+ throw new error_1.AppError("ARGS_INVALID", `${flagName} "${input}" 格式无法识别。支持:` +
132
+ `相对时间(如 1h / 2d / 1w)、日期(YYYY-MM-DD)、ISO 8601(如 2026-04-01T10:00:00Z)`);
122
133
  }
134
+ return ms;
123
135
  }
124
136
  /**
125
137
  * 列出文件:所有过滤下推到后端 FilterExpression,纯精确匹配,无 glob。
@@ -135,7 +147,7 @@ async function listFiles(opts) {
135
147
  let hasMore = false;
136
148
  // 分页 cursor 用 raw attachment.id(后端 continuationToken 语义);
137
149
  // CLI 对外不暴露 attachment.id,所以这里单独追踪最后一页的 raw id
138
- let lastRawId = '';
150
+ let lastRawId = "";
139
151
  for (;;) {
140
152
  const fetchLimit = opts.all ? 200 : pageSize;
141
153
  const data = await listOnce(opts.appId, bucketId, {
@@ -147,7 +159,7 @@ async function listFiles(opts) {
147
159
  const rawItems = data.attachments ?? [];
148
160
  hasMore = Boolean(data.hasMore);
149
161
  if (rawItems.length > 0) {
150
- lastRawId = rawItems[rawItems.length - 1].id ?? '';
162
+ lastRawId = rawItems[rawItems.length - 1].id ?? "";
151
163
  }
152
164
  for (const raw of rawItems) {
153
165
  const info = (0, parsers_1.parseAttachment)(raw);
@@ -196,8 +208,8 @@ async function resolveInputs(opts) {
196
208
  if (opts.inputs.length === 0)
197
209
  return [];
198
210
  return Promise.all(opts.inputs.map((input) => {
199
- const kind = opts.forceAs ?? ((0, detect_1.looksLikePath)(input) ? 'path' : 'name');
200
- return kind === 'path' ? resolveByPath(opts.appId, input) : resolveByName(opts.appId, input);
211
+ const kind = opts.forceAs ?? ((0, detect_1.looksLikePath)(input) ? "path" : "name");
212
+ return kind === "path" ? resolveByPath(opts.appId, input) : resolveByName(opts.appId, input);
201
213
  }));
202
214
  }
203
215
  /** path 输入:HEAD 判存在性,path 在 bucket 内 unique 无需反查。 */
@@ -206,17 +218,17 @@ async function resolveByPath(appId, input) {
206
218
  const filePath = (0, detect_1.toAbsolutePath)(input);
207
219
  try {
208
220
  const info = await statFile({ appId, filePath });
209
- return { status: 'ok', input, file: info };
221
+ return { status: "ok", input, file: info };
210
222
  }
211
223
  catch (err) {
212
- if (err instanceof error_1.AppError && err.code === 'FILE_NOT_FOUND') {
224
+ if (err instanceof error_1.AppError && err.code === "FILE_NOT_FOUND") {
213
225
  return {
214
- status: 'error',
226
+ status: "error",
215
227
  input,
216
228
  error: {
217
- code: 'FILE_NOT_FOUND',
229
+ code: "FILE_NOT_FOUND",
218
230
  message: `File '${input}' does not exist`,
219
- hint: 'Run `miaoda file ls` to see available files.',
231
+ hint: "Run `miaoda file ls` to see available files.",
220
232
  },
221
233
  };
222
234
  }
@@ -226,38 +238,38 @@ async function resolveByPath(appId, input) {
226
238
  /** file_name 输入:list + FilterExpression `name eq X`,多匹配 AMBIGUOUS。 */
227
239
  async function resolveByName(appId, input) {
228
240
  const filterExpr = {
229
- logic: 'and',
230
- groups: [{ conditions: [{ field: 'name', operator: 'eq', value: input }] }],
241
+ logic: "and",
242
+ groups: [{ conditions: [{ field: "name", operator: "eq", value: input }] }],
231
243
  };
232
244
  const result = await listFiles({ appId, filterExpr, limit: 200 });
233
245
  // 后端返 name 精确匹配的所有 attachments。basename fallback 防御(后端某些场景 name 可能为空)
234
246
  const matches = result.items.filter((i) => {
235
- const basename = i.path.split('/').pop() ?? i.path;
247
+ const basename = i.path.split("/").pop() ?? i.path;
236
248
  return i.file_name === input || basename === input;
237
249
  });
238
250
  if (matches.length === 0) {
239
251
  return {
240
- status: 'error',
252
+ status: "error",
241
253
  input,
242
254
  error: {
243
- code: 'FILE_NOT_FOUND',
255
+ code: "FILE_NOT_FOUND",
244
256
  message: `File '${input}' does not exist`,
245
- hint: 'Run `miaoda file ls` to see available files.',
257
+ hint: "Run `miaoda file ls` to see available files.",
246
258
  },
247
259
  };
248
260
  }
249
261
  if (matches.length > 1) {
250
262
  return {
251
- status: 'error',
263
+ status: "error",
252
264
  input,
253
265
  error: {
254
- code: 'AMBIGUOUS_FILE_NAME',
266
+ code: "AMBIGUOUS_FILE_NAME",
255
267
  message: `Multiple files match name '${input}' (${String(matches.length)} found)`,
256
268
  hint: `Use path instead. Run \`miaoda file ls --name ${input}\` to see candidates.`,
257
269
  },
258
270
  };
259
271
  }
260
- return { status: 'ok', input, file: matches[0] };
272
+ return { status: "ok", input, file: matches[0] };
261
273
  }
262
274
  // ── stat ──
263
275
  /**
@@ -269,10 +281,10 @@ async function statFile(opts) {
269
281
  // 对齐 file-storage-skill Py 版:URL 顺序是 .../object/{bucket}/head/{path}
270
282
  const url = `/v1/storage/app/${encodeURIComponent(opts.appId)}/object/${encodeURIComponent(bucketId)}/head/${encodePath(opts.filePath)}`;
271
283
  const body = await (0, client_1.doGet)(url, {
272
- notFoundCode: 'FILE_NOT_FOUND',
284
+ notFoundCode: "FILE_NOT_FOUND",
273
285
  notFoundMessage: `File '${opts.filePath}' does not exist`,
274
- notFoundHint: 'Run `miaoda file ls` to see available files.',
275
- errorContext: 'stat file',
286
+ notFoundHint: "Run `miaoda file ls` to see available files.",
287
+ errorContext: "stat file",
276
288
  });
277
289
  return (0, parsers_1.parseHead)(extractEnvelope(body), opts.filePath);
278
290
  }
@@ -280,7 +292,7 @@ async function statFile(opts) {
280
292
  async function preUpload(appId, req) {
281
293
  const bucketId = await (0, client_1.getDefaultBucketId)(appId);
282
294
  const url = `/v1/storage/app/${encodeURIComponent(appId)}/bucket/${encodeURIComponent(bucketId)}/preUpload`;
283
- const body = await (0, client_1.doPost)(url, { bucketID: bucketId, appID: appId, ...req }, { errorContext: 'pre-upload' });
295
+ const body = await (0, client_1.doPost)(url, { bucketID: bucketId, appID: appId, ...req }, { errorContext: "pre-upload" });
284
296
  return extractEnvelope(body);
285
297
  }
286
298
  /**
@@ -296,14 +308,14 @@ async function preUpload(appId, req) {
296
308
  async function uploadCallback(appId, req) {
297
309
  const url = `/v1/storage/app/${encodeURIComponent(appId)}/object/callback`;
298
310
  const body = await (0, client_1.doPost)(url, req, {
299
- errorContext: 'upload callback',
311
+ errorContext: "upload callback",
300
312
  });
301
313
  const data = extractEnvelope(body);
302
314
  const metadata = data.metadata;
303
315
  if (!metadata) {
304
316
  return {};
305
317
  }
306
- if (typeof metadata === 'object') {
318
+ if (typeof metadata === "object") {
307
319
  return metadata;
308
320
  }
309
321
  // string 形态兜底
@@ -330,10 +342,10 @@ async function uploadFile(opts) {
330
342
  filePath: opts.remotePath ? toApiPath(opts.remotePath) : undefined,
331
343
  });
332
344
  if (!pre.uploadURL || !pre.uploadID) {
333
- throw new error_1.AppError('FILE_UPLOAD_FAILED', 'preUpload did not return uploadURL/uploadID');
345
+ throw new error_1.AppError("FILE_UPLOAD_FAILED", "preUpload did not return uploadURL/uploadID");
334
346
  }
335
347
  const body = await opts.readFile();
336
- let etag = '';
348
+ let etag = "";
337
349
  try {
338
350
  // Node 20+ 内置 fetch 运行时接受 Buffer,但 TS 的 BodyInit 要求更严格的类型;
339
351
  // 这里复制到独立 ArrayBuffer 以满足 lib.dom.d.ts 的 BodyInit 约束
@@ -343,27 +355,27 @@ async function uploadFile(opts) {
343
355
  // header 作为对象 metadata 存住,服务端 callback 阶段 HeadObject 读回并解析
344
356
  // filename 写入 DB。我们要不传 header,服务端走兜底会把 storage key 当文件名。
345
357
  const res = await fetch(pre.uploadURL, {
346
- method: 'PUT',
358
+ method: "PUT",
347
359
  headers: {
348
- 'Content-Type': opts.contentType,
349
- 'Content-Length': String(opts.fileSize),
350
- 'Content-Disposition': `attachment; filename="${sanitizeFileName(opts.fileName)}"`,
360
+ "Content-Type": opts.contentType,
361
+ "Content-Length": String(opts.fileSize),
362
+ "Content-Disposition": `attachment; filename="${sanitizeFileName(opts.fileName)}"`,
351
363
  },
352
364
  body: ab,
353
365
  });
354
366
  (0, logger_1.debug)(`http PUT <upload-cdn> ${String(res.status)} cost=${String(Date.now() - uploadStart)}ms size=${String(opts.fileSize)}`);
355
367
  if (!res.ok) {
356
- throw new error_1.AppError('FILE_UPLOAD_FAILED', `Upload PUT failed with status ${String(res.status)}`);
368
+ throw new error_1.AppError("FILE_UPLOAD_FAILED", `Upload PUT failed with status ${String(res.status)}`);
357
369
  }
358
- etag = res.headers.get('ETag') ?? '';
370
+ etag = res.headers.get("ETag") ?? "";
359
371
  }
360
372
  catch (err) {
361
373
  if (err instanceof error_1.AppError)
362
374
  throw err;
363
- throw new error_1.AppError('FILE_UPLOAD_FAILED', `Upload PUT failed: ${err instanceof Error ? err.message : String(err)}`);
375
+ throw new error_1.AppError("FILE_UPLOAD_FAILED", `Upload PUT failed: ${err instanceof Error ? err.message : String(err)}`);
364
376
  }
365
377
  if (!etag) {
366
- throw new error_1.AppError('FILE_UPLOAD_FAILED', 'Upload PUT returned no ETag');
378
+ throw new error_1.AppError("FILE_UPLOAD_FAILED", "Upload PUT returned no ETag");
367
379
  }
368
380
  // callback 返回服务端实际生成的对象元数据(filePath / file_name / download_url)。
369
381
  // path 末段是平台生成的 16 位 GID,CLI 无法靠本地信息推断;callback 失败 /
@@ -377,20 +389,20 @@ async function uploadFile(opts) {
377
389
  }
378
390
  catch (err) {
379
391
  const reason = err instanceof Error ? err.message : String(err);
380
- throw new error_1.AppError('FILE_UPLOAD_CALLBACK_INCOMPLETE', `Upload callback failed: ${reason}; file may already exist in storage`, {
392
+ throw new error_1.AppError("FILE_UPLOAD_CALLBACK_INCOMPLETE", `Upload callback failed: ${reason}; file may already exist in storage`, {
381
393
  next_actions: [
382
394
  `Run \`miaoda file ls --name ${opts.fileName}\` to locate the uploaded file.`,
383
395
  ],
384
396
  });
385
397
  }
386
398
  if (!metadata.filePath) {
387
- throw new error_1.AppError('FILE_UPLOAD_CALLBACK_INCOMPLETE', 'Upload callback returned no filePath; file may already exist in storage', {
399
+ throw new error_1.AppError("FILE_UPLOAD_CALLBACK_INCOMPLETE", "Upload callback returned no filePath; file may already exist in storage", {
388
400
  next_actions: [
389
401
  `Run \`miaoda file ls --name ${opts.fileName}\` to locate the uploaded file.`,
390
402
  ],
391
403
  });
392
404
  }
393
- const path = metadata.filePath.startsWith('/') ? metadata.filePath : '/' + metadata.filePath;
405
+ const path = metadata.filePath.startsWith("/") ? metadata.filePath : "/" + metadata.filePath;
394
406
  const result = {
395
407
  // 优先取服务端 ObjectVO.name(来自 PUT 时带的 Content-Disposition),
396
408
  // 与后续 file ls / file stat 返回的展示名保持一致;缺失时降级用本地 fileName。
@@ -413,7 +425,7 @@ async function uploadFile(opts) {
413
425
  */
414
426
  function sanitizeFileName(fileName) {
415
427
  const illegalChars = /[:"\\/*?<>|,;]/g;
416
- return encodeURIComponent(fileName.replace(illegalChars, '')) || 'download_file';
428
+ return encodeURIComponent(fileName.replace(illegalChars, "")) || "download_file";
417
429
  }
418
430
  // ── 预签下载 URL ──
419
431
  /**
@@ -429,15 +441,15 @@ async function signDownload(opts) {
429
441
  expiresIn: opts.expiresIn,
430
442
  };
431
443
  const body = await (0, client_1.doPost)(url, reqBody, {
432
- errorContext: 'sign download URL',
444
+ errorContext: "sign download URL",
433
445
  });
434
446
  // 后端对不存在文件走业务 ErrorCode(status_code=k_img_ec_000034),
435
447
  // 由 ensureSuccess → BIZ_ERR_MAP 统一抛出 FILE_NOT_FOUND,此处无需兜底
436
448
  const data = extractEnvelope(body);
437
- const signed = data.signedURL ?? '';
449
+ const signed = data.signedURL ?? "";
438
450
  const expiresAt = new Date(Date.now() + opts.expiresIn * 1000).toISOString();
439
- const displayPath = opts.filePath.startsWith('/') ? opts.filePath : `/${opts.filePath}`;
440
- const fileName = displayPath.split('/').pop() ?? displayPath;
451
+ const displayPath = opts.filePath.startsWith("/") ? opts.filePath : `/${opts.filePath}`;
452
+ const fileName = displayPath.split("/").pop() ?? displayPath;
441
453
  return {
442
454
  file_name: fileName,
443
455
  path: displayPath,
@@ -456,11 +468,11 @@ async function downloadFile(opts) {
456
468
  }
457
469
  catch (err) {
458
470
  (0, logger_1.debug)(`http GET <download-cdn> 0 cost=${String(Date.now() - downloadStart)}ms err=${err instanceof Error ? err.message : String(err)}`);
459
- throw new error_1.AppError('FILE_DOWNLOAD_FAILED', `Download GET failed: ${err instanceof Error ? err.message : String(err)}`);
471
+ throw new error_1.AppError("FILE_DOWNLOAD_FAILED", `Download GET failed: ${err instanceof Error ? err.message : String(err)}`);
460
472
  }
461
473
  (0, logger_1.debug)(`http GET <download-cdn> ${String(res.status)} cost=${String(Date.now() - downloadStart)}ms`);
462
474
  if (!res.ok) {
463
- throw new error_1.AppError('FILE_DOWNLOAD_FAILED', `Download failed with status ${String(res.status)}`);
475
+ throw new error_1.AppError("FILE_DOWNLOAD_FAILED", `Download failed with status ${String(res.status)}`);
464
476
  }
465
477
  const array = new Uint8Array(await res.arrayBuffer());
466
478
  const buf = Buffer.from(array);
@@ -480,17 +492,17 @@ async function deleteFiles(opts) {
480
492
  filePaths: opts.filePaths.map(toApiPath),
481
493
  };
482
494
  const body = await (0, client_1.doRequest)({
483
- method: 'DELETE',
495
+ method: "DELETE",
484
496
  url,
485
- headers: { 'Content-Type': 'application/json' },
497
+ headers: { "Content-Type": "application/json" },
486
498
  body: JSON.stringify(reqBody),
487
- }, { errorContext: 'delete files' });
499
+ }, { errorContext: "delete files" });
488
500
  const data = extractEnvelope(body);
489
501
  // 后端响应里只给出被删除成功的 attachments(无前导 /),没删掉的靠对比输入判断
490
- const toDisplay = (p) => (p.startsWith('/') ? p : `/${p}`);
502
+ const toDisplay = (p) => (p.startsWith("/") ? p : `/${p}`);
491
503
  const deletedSet = new Set();
492
504
  for (const att of data.attachments ?? []) {
493
- const p = att.filePath ?? att.name ?? '';
505
+ const p = att.filePath ?? att.name ?? "";
494
506
  if (p)
495
507
  deletedSet.add(toApiPath(p));
496
508
  }
@@ -502,22 +514,8 @@ async function deleteFiles(opts) {
502
514
  deleted.push(toDisplay(normalized));
503
515
  }
504
516
  else {
505
- failed.push({ path: toDisplay(normalized), error: 'file not found or not deleted' });
517
+ failed.push({ path: toDisplay(normalized), error: "file not found or not deleted" });
506
518
  }
507
519
  }
508
520
  return { deleted, failed };
509
521
  }
510
- // ── storage quota ──
511
- /**
512
- * 后端:GET /v1/storage/app/{appId}/bucket/{bucketId}/quota
513
- * 单 bucket 用量;StorageQuotaBytes 暂未对接,CLI 拿到 0 时按 "—" 渲染。
514
- * bucketId 缺省时走默认 bucket(与 ls / stat / cp 等一致)。
515
- */
516
- async function getStorageQuota(opts) {
517
- const bucketId = opts.bucketId ?? (await (0, client_1.getDefaultBucketId)(opts.appId));
518
- const url = `/v1/storage/app/${encodeURIComponent(opts.appId)}/bucket/${encodeURIComponent(bucketId)}/quota`;
519
- const body = await (0, client_1.doGet)(url, {
520
- errorContext: `fetch storage quota for app '${opts.appId}' bucket '${bucketId}'`,
521
- });
522
- return extractEnvelope(body);
523
- }
@@ -20,9 +20,9 @@ function traceHttp(method, url, start, response, err) {
20
20
  try {
21
21
  const cost = Date.now() - start;
22
22
  const status = response?.status ?? 0;
23
- const logid = response?.headers?.get?.('x-tt-logid') ?? '-';
23
+ const logid = response?.headers?.get?.("x-tt-logid") ?? "-";
24
24
  if (err !== undefined) {
25
- const errMsg = err instanceof Error ? err.message : typeof err === 'string' ? err : JSON.stringify(err);
25
+ const errMsg = err instanceof Error ? err.message : typeof err === "string" ? err : JSON.stringify(err);
26
26
  (0, logger_1.debug)(`http ${method} ${url} ${String(status)} cost=${String(cost)}ms x-tt-logid=${logid} err=${errMsg}`);
27
27
  return;
28
28
  }
@@ -51,7 +51,7 @@ async function getDefaultBucketId(appId) {
51
51
  ensureSuccess(body);
52
52
  const bucketId = body.data?.app_runtime_extra?.bucket?.default_bucket_id;
53
53
  if (!bucketId) {
54
- throw new error_1.AppError('BUCKET_NOT_FOUND', `No default bucket for app '${appId}'`);
54
+ throw new error_1.AppError("BUCKET_NOT_FOUND", `No default bucket for app '${appId}'`);
55
55
  }
56
56
  bucketCache.set(appId, bucketId);
57
57
  return bucketId;
@@ -81,25 +81,25 @@ function resetBucketCache() {
81
81
  */
82
82
  const BIZ_ERR_MAP = new Map(Object.entries({
83
83
  k_img_ec_000034: {
84
- code: 'FILE_NOT_FOUND',
85
- message: 'File does not exist',
86
- hint: 'Run `miaoda file ls` to see available files.',
84
+ code: "FILE_NOT_FOUND",
85
+ message: "File does not exist",
86
+ hint: "Run `miaoda file ls` to see available files.",
87
87
  },
88
88
  k_img_ec_000035: {
89
- code: 'FILE_ALREADY_EXISTS',
90
- message: 'A file at this path already exists',
91
- hint: 'Rename the target or delete the existing file first (`miaoda file rm`).',
89
+ code: "FILE_ALREADY_EXISTS",
90
+ message: "A file at this path already exists",
91
+ hint: "Rename the target or delete the existing file first (`miaoda file rm`).",
92
92
  },
93
93
  }));
94
94
  function ensureSuccess(body) {
95
95
  // 后端 envelope 字段历史遗留多种命名:
96
96
  // - ErrorCode / error_code: 部分接口
97
97
  // - status_code: delete / sign / head / preUpload 等新接口
98
- const code = body.ErrorCode ?? body.error_code ?? body.status_code ?? '0';
99
- if (code === '0' || code === '')
98
+ const code = body.ErrorCode ?? body.error_code ?? body.status_code ?? "0";
99
+ if (code === "0" || code === "")
100
100
  return;
101
101
  // 错误 message 字段同样散:ErrorMessage / error_message / error_msg / Message
102
- const backendMsg = body.ErrorMessage ?? body.error_message ?? body.error_msg ?? body.Message ?? 'unknown error';
102
+ const backendMsg = body.ErrorMessage ?? body.error_message ?? body.error_msg ?? body.Message ?? "unknown error";
103
103
  const mapped = BIZ_ERR_MAP.get(code);
104
104
  if (mapped) {
105
105
  throw new error_1.AppError(mapped.code, mapped.message ?? backendMsg, {
@@ -128,22 +128,22 @@ async function mapHttpError(err, opts) {
128
128
  const body = await extractBody(err.response);
129
129
  // 1. 先看后端业务 ErrorCode(优先级最高)
130
130
  if (body) {
131
- const code = body.ErrorCode ?? body.error_code ?? '';
132
- if (code && code !== '0') {
131
+ const code = body.ErrorCode ?? body.error_code ?? "";
132
+ if (code && code !== "0") {
133
133
  const msg = body.ErrorMessage ?? body.error_message ?? body.Message ?? err.message;
134
134
  throw new error_1.AppError(`FILE_API_${code}`, `File API error [${code}]: ${msg}`);
135
135
  }
136
136
  }
137
137
  // 2. 404 常见情况 —— 路径不存在,映射到业务语义
138
138
  if (status === 404 && opts.notFoundCode) {
139
- throw new error_1.AppError(opts.notFoundCode, opts.notFoundMessage ?? 'resource not found', {
139
+ throw new error_1.AppError(opts.notFoundCode, opts.notFoundMessage ?? "resource not found", {
140
140
  next_actions: opts.notFoundHint ? [opts.notFoundHint] : undefined,
141
141
  });
142
142
  }
143
143
  // 3. 兜底:保留原始 status 的 HttpError(给上层看到真实状态码)
144
- const ctx = opts.errorContext ?? 'HTTP request failed';
145
- const statusText = err.response?.statusText ?? '';
146
- throw new error_1.HttpError(status, err.config.url ?? '', `${ctx}: ${String(status)} ${statusText}`.trim());
144
+ const ctx = opts.errorContext ?? "HTTP request failed";
145
+ const statusText = err.response?.statusText ?? "";
146
+ throw new error_1.HttpError(status, err.config.url ?? "", `${ctx}: ${String(status)} ${statusText}`.trim());
147
147
  }
148
148
  throw err;
149
149
  }
@@ -156,11 +156,11 @@ async function doGet(url, opts = {}, client = (0, http_1.getHttpClient)()) {
156
156
  const start = Date.now();
157
157
  try {
158
158
  const response = await client.get(url);
159
- traceHttp('GET', url, start, response);
159
+ traceHttp("GET", url, start, response);
160
160
  return (await response.json());
161
161
  }
162
162
  catch (err) {
163
- traceHttp('GET', url, start, err instanceof http_client_1.HttpError ? err.response : undefined, err);
163
+ traceHttp("GET", url, start, err instanceof http_client_1.HttpError ? err.response : undefined, err);
164
164
  await mapHttpError(err, opts);
165
165
  throw err; // 不可达,mapHttpError 必定 throw
166
166
  }
@@ -170,11 +170,11 @@ async function doPost(url, body, opts = {}, client = (0, http_1.getHttpClient)()
170
170
  const start = Date.now();
171
171
  try {
172
172
  const response = await client.post(url, body);
173
- traceHttp('POST', url, start, response);
173
+ traceHttp("POST", url, start, response);
174
174
  return (await response.json());
175
175
  }
176
176
  catch (err) {
177
- traceHttp('POST', url, start, err instanceof http_client_1.HttpError ? err.response : undefined, err);
177
+ traceHttp("POST", url, start, err instanceof http_client_1.HttpError ? err.response : undefined, err);
178
178
  await mapHttpError(err, opts);
179
179
  throw err;
180
180
  }
@@ -41,9 +41,9 @@ const BACKEND_KEY_PATTERN = /^\d{16,}(?:\.[a-zA-Z0-9]{1,10}){0,2}$/;
41
41
  function looksLikePath(input) {
42
42
  if (!input)
43
43
  return false;
44
- if (input.startsWith('/'))
44
+ if (input.startsWith("/"))
45
45
  return true;
46
- if (input.includes('/'))
46
+ if (input.includes("/"))
47
47
  return true;
48
48
  return BACKEND_KEY_PATTERN.test(input);
49
49
  }
@@ -52,5 +52,5 @@ function looksLikePath(input) {
52
52
  * 便于从 auto-detected 的 "abc123...xyz.txt" 回到统一的 `/abc123...xyz.txt`。
53
53
  */
54
54
  function toAbsolutePath(input) {
55
- return input.startsWith('/') ? input : `/${input}`;
55
+ return input.startsWith("/") ? input : `/${input}`;
56
56
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toAbsolutePath = exports.looksLikePath = exports.resetBucketCache = exports.getDefaultBucketId = exports.getStorageQuota = exports.parseTimeFilterMs = exports.resolveInputs = exports.deleteFiles = exports.downloadFile = exports.signDownload = exports.uploadFile = exports.statFile = exports.listFiles = void 0;
3
+ exports.toAbsolutePath = exports.looksLikePath = exports.resetBucketCache = exports.getDefaultBucketId = exports.parseTimeFilterMs = exports.resolveInputs = exports.deleteFiles = exports.downloadFile = exports.signDownload = exports.uploadFile = exports.statFile = exports.listFiles = void 0;
4
4
  var api_1 = require("./api");
5
5
  Object.defineProperty(exports, "listFiles", { enumerable: true, get: function () { return api_1.listFiles; } });
6
6
  Object.defineProperty(exports, "statFile", { enumerable: true, get: function () { return api_1.statFile; } });
@@ -10,7 +10,6 @@ Object.defineProperty(exports, "downloadFile", { enumerable: true, get: function
10
10
  Object.defineProperty(exports, "deleteFiles", { enumerable: true, get: function () { return api_1.deleteFiles; } });
11
11
  Object.defineProperty(exports, "resolveInputs", { enumerable: true, get: function () { return api_1.resolveInputs; } });
12
12
  Object.defineProperty(exports, "parseTimeFilterMs", { enumerable: true, get: function () { return api_1.parseTimeFilterMs; } });
13
- Object.defineProperty(exports, "getStorageQuota", { enumerable: true, get: function () { return api_1.getStorageQuota; } });
14
13
  var client_1 = require("./client");
15
14
  Object.defineProperty(exports, "getDefaultBucketId", { enumerable: true, get: function () { return client_1.getDefaultBucketId; } });
16
15
  Object.defineProperty(exports, "resetBucketCache", { enumerable: true, get: function () { return client_1.resetBucketCache; } });
@@ -3,12 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseAttachment = parseAttachment;
4
4
  exports.parseHead = parseHead;
5
5
  /** 安全读取字符串字段(空字符串回退为默认值) */
6
- function str(value, fallback = '') {
7
- return typeof value === 'string' && value.length > 0 ? value : fallback;
6
+ function str(value, fallback = "") {
7
+ return typeof value === "string" && value.length > 0 ? value : fallback;
8
8
  }
9
9
  /** 安全读取数字字段(非正值回退到 0) */
10
10
  function int(value) {
11
- if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {
11
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
12
12
  return Math.trunc(value);
13
13
  }
14
14
  return 0;
@@ -26,7 +26,7 @@ function readSize(meta) {
26
26
  function toDisplayPath(p) {
27
27
  if (!p)
28
28
  return p;
29
- return p.startsWith('/') ? p : `/${p}`;
29
+ return p.startsWith("/") ? p : `/${p}`;
30
30
  }
31
31
  /** 将后端 attachment 结构映射为 CLI FileInfo(用于 ls) */
32
32
  function parseAttachment(att) {
@@ -41,9 +41,8 @@ function parseAttachment(att) {
41
41
  const downloadUrl = str(att.downloadURL);
42
42
  if (downloadUrl)
43
43
  info.download_url = downloadUrl;
44
- // uploaded_by 输出 {id, name} 对象:后端 createdBy: {userID, name, email, ...},
45
- // 任一非空都建对象;JSON 用对象、pretty 渲染只取 name。
46
- const uploader = toUploaderRef(att.createdBy);
44
+ // uploaded_by 从 createdBy.name 映射(后端返 {userID, name, email, ...},空代表匿名)
45
+ const uploader = str(att.createdBy?.name);
47
46
  if (uploader)
48
47
  info.uploaded_by = uploader;
49
48
  return info;
@@ -62,18 +61,8 @@ function parseHead(data, filePath) {
62
61
  const downloadUrl = str(outer.downloadURL);
63
62
  if (downloadUrl)
64
63
  info.download_url = downloadUrl;
65
- const uploader = toUploaderRef(outer.createdBy);
64
+ const uploader = str(outer.createdBy?.name);
66
65
  if (uploader)
67
66
  info.uploaded_by = uploader;
68
67
  return info;
69
68
  }
70
- /** 把后端 UserRef 归一成 CLI 暴露的 {id, name};id / name 全空时返 undefined 略过字段。 */
71
- function toUploaderRef(user) {
72
- if (!user)
73
- return undefined;
74
- const id = str(user.userID);
75
- const name = str(user.name);
76
- if (id === '' && name === '')
77
- return undefined;
78
- return { id, name };
79
- }