@lark-apaas/miaoda-cli 0.1.2-alpha.d0d2ae1 → 0.1.2-alpha.f0d7c45

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 (66) hide show
  1. package/README.md +8 -7
  2. package/dist/api/app/api.js +25 -0
  3. package/dist/api/app/index.js +15 -0
  4. package/dist/api/app/schemas.js +79 -0
  5. package/dist/api/app/types.js +58 -0
  6. package/dist/api/db/api.js +6 -250
  7. package/dist/api/db/client.js +0 -36
  8. package/dist/api/db/index.js +1 -9
  9. package/dist/api/deploy/api.js +60 -0
  10. package/dist/api/deploy/index.js +16 -0
  11. package/dist/api/deploy/schemas.js +105 -0
  12. package/dist/api/deploy/types.js +22 -0
  13. package/dist/api/file/api.js +0 -15
  14. package/dist/api/file/index.js +1 -2
  15. package/dist/api/index.js +7 -1
  16. package/dist/api/observability/api.js +52 -0
  17. package/dist/api/observability/index.js +16 -0
  18. package/dist/api/observability/schemas.js +60 -0
  19. package/dist/api/observability/types.js +27 -0
  20. package/dist/cli/commands/app/index.js +62 -0
  21. package/dist/cli/commands/db/index.js +6 -142
  22. package/dist/cli/commands/deploy/index.js +155 -0
  23. package/dist/cli/commands/file/index.js +6 -12
  24. package/dist/cli/commands/index.js +10 -6
  25. package/dist/cli/commands/observability/index.js +240 -0
  26. package/dist/cli/commands/shared.js +83 -7
  27. package/dist/cli/handlers/app/get.js +47 -0
  28. package/dist/cli/handlers/app/index.js +7 -0
  29. package/dist/cli/handlers/{db/quota.js → app/update.js} +20 -29
  30. package/dist/cli/handlers/db/data.js +3 -4
  31. package/dist/cli/handlers/db/index.js +1 -17
  32. package/dist/cli/handlers/db/schema.js +2 -3
  33. package/dist/cli/handlers/db/sql.js +1 -2
  34. package/dist/cli/handlers/deploy/deploy.js +84 -0
  35. package/dist/cli/handlers/{file/quota.js → deploy/error-log.js} +21 -27
  36. package/dist/cli/handlers/deploy/format.js +39 -0
  37. package/dist/cli/handlers/deploy/get.js +71 -0
  38. package/dist/cli/handlers/deploy/helpers.js +41 -0
  39. package/dist/cli/handlers/deploy/history.js +70 -0
  40. package/dist/cli/handlers/deploy/index.js +14 -0
  41. package/dist/cli/handlers/deploy/polling.js +162 -0
  42. package/dist/cli/handlers/file/cp.js +1 -2
  43. package/dist/cli/handlers/file/index.js +1 -3
  44. package/dist/cli/handlers/file/ls.js +1 -2
  45. package/dist/cli/handlers/file/rm.js +1 -2
  46. package/dist/cli/handlers/file/sign.js +1 -2
  47. package/dist/cli/handlers/file/stat.js +1 -2
  48. package/dist/cli/handlers/observability/analytics.js +212 -0
  49. package/dist/cli/handlers/observability/helpers.js +66 -0
  50. package/dist/cli/handlers/observability/index.js +12 -0
  51. package/dist/cli/handlers/observability/log.js +94 -0
  52. package/dist/cli/handlers/observability/metric.js +208 -0
  53. package/dist/cli/handlers/observability/trace.js +102 -0
  54. package/dist/main.js +6 -2
  55. package/dist/utils/args.js +8 -0
  56. package/dist/utils/devops-error.js +28 -0
  57. package/dist/utils/git.js +29 -0
  58. package/dist/utils/http.js +118 -0
  59. package/dist/utils/index.js +13 -1
  60. package/dist/utils/output.js +338 -29
  61. package/dist/utils/time.js +203 -0
  62. package/package.json +7 -5
  63. package/dist/cli/handlers/db/audit.js +0 -285
  64. package/dist/cli/handlers/db/changelog.js +0 -117
  65. package/dist/cli/handlers/db/migration.js +0 -213
  66. package/dist/cli/handlers/db/recovery.js +0 -228
@@ -1,285 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.handleDbAuditStatus = handleDbAuditStatus;
37
- exports.handleDbAuditEnable = handleDbAuditEnable;
38
- exports.handleDbAuditDisable = handleDbAuditDisable;
39
- exports.handleDbAuditList = handleDbAuditList;
40
- const api = __importStar(require("../../../api/index"));
41
- const index_1 = require("../../../api/file/index");
42
- const shared_1 = require("../../../cli/commands/shared");
43
- const colors_1 = require("../../../utils/colors");
44
- const error_1 = require("../../../utils/error");
45
- const output_1 = require("../../../utils/output");
46
- const render_1 = require("../../../utils/render");
47
- const VALID_RETENTION = new Set(["7d", "30d", "180d", "360d", "forever"]);
48
- async function handleDbAuditStatus(table, opts) {
49
- const appId = (0, shared_1.resolveAppId)(opts);
50
- const items = await api.db.getAuditStatus({ appId, table, dbBranch: opts.env });
51
- const rows = items.map(toAuditStatus);
52
- // 单表查询但后端没记录 → 占位 enabled=false
53
- if (table !== undefined && table !== "" && rows.length === 0) {
54
- rows.push({ table, enabled: false, enabled_at: null, retention: null });
55
- }
56
- // PRD JSON:单表返 object,多表返 array
57
- if ((0, output_1.isJsonMode)()) {
58
- if (table !== undefined && rows.length === 1) {
59
- (0, output_1.emitOk)((0, output_1.snakeCaseKeys)(rows[0]));
60
- }
61
- else {
62
- (0, output_1.emitOk)((0, output_1.snakeCaseKeys)(rows));
63
- }
64
- return;
65
- }
66
- if (rows.length === 0) {
67
- (0, output_1.emit)("No audit configuration found.");
68
- return;
69
- }
70
- const tty = (0, render_1.isStdoutTty)();
71
- // 单表 → key:value 形态
72
- if (table !== undefined && rows.length === 1) {
73
- const it = rows[0];
74
- (0, output_1.emit)((0, render_1.renderKeyValue)([
75
- ["Table", it.table],
76
- ["Enabled", boolToYesNo(it.enabled)],
77
- ["Enabled at", it.enabled_at ? (0, render_1.formatTime)(it.enabled_at, tty) : "—"],
78
- ["Retention", it.retention ?? "—"],
79
- ], tty));
80
- return;
81
- }
82
- // 列表 → table 形态
83
- const headers = ["table", "enabled", "enabled_at", "retention"];
84
- const out = rows.map((it) => [
85
- it.table,
86
- boolToYesNo(it.enabled),
87
- it.enabled_at ? (0, render_1.formatTime)(it.enabled_at, tty) : "—",
88
- it.retention ?? "—",
89
- ]);
90
- (0, output_1.emit)(tty ? (0, render_1.renderAlignedTable)(headers, out) : (0, render_1.renderTsv)(headers, out));
91
- }
92
- function toAuditStatus(s) {
93
- return {
94
- table: s.table,
95
- enabled: s.enabled,
96
- enabled_at: s.enabledAt ?? null,
97
- retention: s.retention ?? null,
98
- };
99
- }
100
- async function handleDbAuditEnable(table, opts) {
101
- if (!table) {
102
- throw new error_1.AppError("ARGS_INVALID", "table name is required", {
103
- next_actions: [
104
- "Usage: miaoda db audit enable <table> [--retention 7d|30d|180d|360d|forever]",
105
- ],
106
- });
107
- }
108
- const retention = opts.retention ?? "7d";
109
- if (!VALID_RETENTION.has(retention)) {
110
- throw new error_1.AppError("INVALID_RETENTION", `Invalid retention '${retention}'`, {
111
- next_actions: ["Allowed values: 7d, 30d, 180d, 360d, forever."],
112
- });
113
- }
114
- const appId = (0, shared_1.resolveAppId)(opts);
115
- let status;
116
- try {
117
- status = await api.db.setAuditConfig({
118
- appId,
119
- table,
120
- enabled: true,
121
- retention,
122
- dbBranch: opts.env,
123
- });
124
- }
125
- catch (err) {
126
- // PRD: 重复 enable 报错时附带 hint,引导用户去 status 看 retention 或换值更新
127
- if (err instanceof error_1.AppError && err.code === "DB_API_k_dl_1300030") {
128
- throw new error_1.AppError(err.code, err.message, {
129
- next_actions: [
130
- `Use \`miaoda db audit status ${table}\` to check current retention, or run this command with a different --retention to update.`,
131
- ],
132
- });
133
- }
134
- throw err;
135
- }
136
- // PRD JSON:{"data": {"table": "...", "enabled": true, "retention": "..."}}
137
- if ((0, output_1.isJsonMode)()) {
138
- (0, output_1.emitOk)((0, output_1.snakeCaseKeys)({
139
- table: status.table,
140
- enabled: status.enabled,
141
- retention: status.retention ?? retention,
142
- }));
143
- return;
144
- }
145
- const tty = (0, render_1.isStdoutTty)();
146
- const prefix = tty ? "✓" : "OK";
147
- // c.highlight 内部按 TTY/NO_COLOR/FORCE_COLOR 自动决定是否染色,无需再判 tty
148
- const tableLabel = colors_1.c.highlight(`'${status.table}'`);
149
- (0, output_1.emit)(`${prefix} Audit enabled for table ${tableLabel} (retention: ${status.retention ?? retention})`);
150
- }
151
- async function handleDbAuditDisable(table, opts) {
152
- if (!table) {
153
- throw new error_1.AppError("ARGS_INVALID", "table name is required", {
154
- next_actions: ["Usage: miaoda db audit disable <table>"],
155
- });
156
- }
157
- const appId = (0, shared_1.resolveAppId)(opts);
158
- let status;
159
- try {
160
- status = await api.db.setAuditConfig({
161
- appId,
162
- table,
163
- enabled: false,
164
- dbBranch: opts.env,
165
- });
166
- }
167
- catch (err) {
168
- // PRD: 重复 disable / 未启用就 disable 报错时附带 hint,引导用户去看哪些表已开启
169
- if (err instanceof error_1.AppError && err.code === "DB_API_k_dl_1300031") {
170
- throw new error_1.AppError(err.code, err.message, {
171
- next_actions: ["Use `miaoda db audit status` to see which tables have audit enabled."],
172
- });
173
- }
174
- throw err;
175
- }
176
- if ((0, output_1.isJsonMode)()) {
177
- (0, output_1.emitOk)((0, output_1.snakeCaseKeys)({
178
- table: status.table,
179
- enabled: status.enabled,
180
- }));
181
- return;
182
- }
183
- const tty = (0, render_1.isStdoutTty)();
184
- const prefix = tty ? "✓" : "OK";
185
- (0, output_1.emit)(`${prefix} Audit disabled for table ${colors_1.c.highlight(`'${status.table}'`)}`);
186
- }
187
- async function handleDbAuditList(tables, opts) {
188
- if (tables.length === 0) {
189
- throw new error_1.AppError("ARGS_INVALID", "at least one table is required", {
190
- next_actions: [
191
- "Usage: miaoda db audit list <table> [<table>...] [--since ...] [--until ...]",
192
- ],
193
- });
194
- }
195
- const appId = (0, shared_1.resolveAppId)(opts);
196
- const limit = opts.limit ?? 20;
197
- // 时间字段归一化为 ISO 8601 UTC(服务端按 event_time 字段比较)。cursor 由
198
- // 后端管理(本质也是 ISO 时间),CLI 不再混用 cursor/since。
199
- const since = normalizeTime(opts.since, "--since");
200
- const until = normalizeTime(opts.until, "--until");
201
- const result = await api.db.listAuditLog({
202
- appId,
203
- tables,
204
- since,
205
- until,
206
- limit,
207
- cursor: opts.cursor,
208
- dbBranch: opts.env,
209
- });
210
- const visible = result.items;
211
- const skipped = result.skipped;
212
- // PRD JSON:data 是数组,元素是事件对象(snake_case),分页信封 next_cursor / has_more
213
- if ((0, output_1.isJsonMode)()) {
214
- const items = visible.map((it) => ({
215
- event_id: it.eventId,
216
- event_time: it.eventTime,
217
- target_table: it.targetTable,
218
- type: it.type,
219
- operator: it.operator,
220
- summary: it.summary,
221
- // before/after 服务端是 JSON 字符串,反序列化回结构化对象供下游消费
222
- ...(it.before !== undefined ? { before: safeParseJson(it.before) } : {}),
223
- ...(it.after !== undefined ? { after: safeParseJson(it.after) } : {}),
224
- }));
225
- (0, output_1.emitPaged)(items, result.nextCursor, result.hasMore);
226
- if (skipped.length > 0) {
227
- process.stderr.write(`(${String(skipped.length)} table(s) skipped: ${skipped.join(", ")})\n`);
228
- }
229
- if (visible.length === 0)
230
- process.exitCode = 1;
231
- return;
232
- }
233
- if (visible.length === 0) {
234
- (0, output_1.emit)("No audit log entries found.");
235
- if (skipped.length > 0) {
236
- process.stderr.write(`(${String(skipped.length)} table(s) skipped: ${skipped.join(", ")})\n`);
237
- }
238
- process.exitCode = 1;
239
- return;
240
- }
241
- const tty = (0, render_1.isStdoutTty)();
242
- // PRD:多表渲染时第一列是 target_table,单表时去掉这一列
243
- const isMultiTable = tables.length > 1;
244
- const headers = isMultiTable
245
- ? ["target_table", "event_time", "type", "event_id", "operator", "summary"]
246
- : ["event_time", "type", "event_id", "operator", "summary"];
247
- const rows = visible.map((it) => {
248
- const eventTime = (0, render_1.formatTime)(it.eventTime, tty);
249
- // event_id 完整透传——PRD 截图里的 "..." 只是文档省略写法,不是 CLI 行为
250
- const cells = [eventTime, it.type, it.eventId, it.operator || "—", it.summary];
251
- return isMultiTable ? [it.targetTable, ...cells] : cells;
252
- });
253
- (0, output_1.emit)(tty ? (0, render_1.renderAlignedTable)(headers, rows) : (0, render_1.renderTsv)(headers, rows));
254
- if (skipped.length > 0) {
255
- process.stderr.write(`(${String(skipped.length)} table(s) skipped: ${skipped.join(", ")})\n`);
256
- }
257
- if (result.hasMore && result.nextCursor) {
258
- process.stderr.write(`(more results; use --cursor '${result.nextCursor}')\n`);
259
- }
260
- }
261
- // ── helpers ──
262
- function normalizeTime(input, flagName) {
263
- if (input === undefined || input === "")
264
- return undefined;
265
- // ISO 8601 直接透传,避免 parseTimeFilterMs 在严格 ISO 上重做一次损精度
266
- if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/.test(input)) {
267
- return new Date(input).toISOString();
268
- }
269
- const ms = (0, index_1.parseTimeFilterMs)(input, flagName);
270
- return new Date(ms).toISOString();
271
- }
272
- // 服务端 before/after 是 JSON 字符串透传,CLI JSON 输出再反序列化回对象,
273
- // 给下游 jq 等工具消费。失败时透传原始字符串避免数据丢失。
274
- function safeParseJson(s) {
275
- try {
276
- return JSON.parse(s);
277
- }
278
- catch {
279
- return s;
280
- }
281
- }
282
- // PRD 输出 enabled 列用 yes/no 而非 true/false
283
- function boolToYesNo(b) {
284
- return b ? "yes" : "no";
285
- }
@@ -1,117 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.handleDbChangelog = handleDbChangelog;
37
- const api = __importStar(require("../../../api/index"));
38
- const index_1 = require("../../../api/file/index");
39
- const shared_1 = require("../../../cli/commands/shared");
40
- const output_1 = require("../../../utils/output");
41
- const render_1 = require("../../../utils/render");
42
- function toRow(it) {
43
- return {
44
- change_id: it.changeId,
45
- changed_at: it.changedAt,
46
- operator: it.operator,
47
- target_table: it.targetTable,
48
- change_type: it.changeType,
49
- summary: it.summary,
50
- statement: it.statement,
51
- };
52
- }
53
- /** 把用户传入的 since/until 归一成 ISO 8601 UTC 字符串;空串返 undefined。 */
54
- function normalizeTime(input, flagName) {
55
- if (input === undefined || input === "")
56
- return undefined;
57
- const ms = (0, index_1.parseTimeFilterMs)(input, flagName);
58
- return new Date(ms).toISOString();
59
- }
60
- async function handleDbChangelog(opts) {
61
- const appId = (0, shared_1.resolveAppId)(opts);
62
- const since = normalizeTime(opts.since, "--since");
63
- const until = normalizeTime(opts.until, "--until");
64
- const allItems = [];
65
- let cursor = opts.cursor;
66
- let lastCursor = null;
67
- let lastHasMore = false;
68
- // --all:循环到 hasMore=false;否则只拉一页
69
- // 没传 --all 时翻页由调用方自己用 --cursor 串
70
- for (;;) {
71
- const page = await api.db.listDDLChangelog({
72
- appId,
73
- table: opts.table,
74
- since,
75
- until,
76
- limit: opts.limit,
77
- cursor,
78
- dbBranch: opts.env,
79
- });
80
- allItems.push(...page.items);
81
- lastCursor = page.nextCursor;
82
- lastHasMore = page.hasMore;
83
- if (!opts.all || !page.hasMore || !page.nextCursor)
84
- break;
85
- cursor = page.nextCursor;
86
- }
87
- if ((0, output_1.isJsonMode)()) {
88
- const rows = allItems.map(toRow);
89
- // --all 时已经把所有页合一起返,has_more=false / next_cursor=null
90
- if (opts.all) {
91
- (0, output_1.emitPaged)((0, output_1.snakeCaseKeys)(rows), null, false);
92
- }
93
- else {
94
- (0, output_1.emitPaged)((0, output_1.snakeCaseKeys)(rows), lastCursor, lastHasMore);
95
- }
96
- return;
97
- }
98
- if (allItems.length === 0) {
99
- (0, output_1.emit)("No DDL changes found.");
100
- return;
101
- }
102
- const tty = (0, render_1.isStdoutTty)();
103
- // PRD: change_id / changed_at / operator / target_table / change_type / summary
104
- const headers = ["change_id", "changed_at", "operator", "target_table", "change_type", "summary"];
105
- const rows = allItems.map((it) => [
106
- it.changeId,
107
- (0, render_1.formatTime)(it.changedAt, tty),
108
- it.operator || "—",
109
- it.targetTable || "—",
110
- it.changeType,
111
- it.summary || "—",
112
- ]);
113
- (0, output_1.emit)(tty ? (0, render_1.renderAlignedTable)(headers, rows) : (0, render_1.renderTsv)(headers, rows));
114
- if (!opts.all && lastHasMore && lastCursor) {
115
- process.stderr.write(`(more results; use --cursor ${lastCursor} or --all)\n`);
116
- }
117
- }
@@ -1,213 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.handleDbMigrationInit = handleDbMigrationInit;
40
- exports.handleDbMigrationDiff = handleDbMigrationDiff;
41
- exports.handleDbMigrationApply = handleDbMigrationApply;
42
- const node_readline_1 = __importDefault(require("node:readline"));
43
- const api = __importStar(require("../../../api/index"));
44
- const shared_1 = require("../../../cli/commands/shared");
45
- const error_1 = require("../../../utils/error");
46
- const output_1 = require("../../../utils/output");
47
- const render_1 = require("../../../utils/render");
48
- async function handleDbMigrationInit(opts) {
49
- const appId = (0, shared_1.resolveAppId)(opts);
50
- // 不可逆操作,TTY 默认要求 y/N;--yes 跳过
51
- if (!opts.yes && !(0, output_1.isJsonMode)()) {
52
- // 文案对齐 PRD:先讲不可逆,再问是否初始化;syncData 时追加一句而不是塞进同一句话
53
- const suffix = opts.syncData ? " (existing data will be copied to dev)" : "";
54
- const ok = await confirm(`? This action is irreversible. Initialize multi-env (dev / online)${suffix}? (y/N) `);
55
- if (!ok) {
56
- (0, output_1.emit)("Aborted.");
57
- return;
58
- }
59
- }
60
- let result;
61
- try {
62
- result = await api.db.migrationInit({ appId, syncData: opts.syncData });
63
- }
64
- catch (err) {
65
- // PRD: 重复 init 报错带 hint,引导用户去 diff 看待发布变更
66
- if (err instanceof error_1.AppError && err.code === "DB_API_k_dl_1300034") {
67
- throw new error_1.AppError(err.code, err.message, {
68
- next_actions: ["Run `miaoda db migration diff` to view pending changes."],
69
- });
70
- }
71
- throw err;
72
- }
73
- if ((0, output_1.isJsonMode)()) {
74
- (0, output_1.emitOk)((0, output_1.snakeCaseKeys)(result));
75
- return;
76
- }
77
- // PRD 单行格式(不用 key:value 表格):
78
- // 默认 ✓ / OK: "Multi-env initialized (dev / online)"
79
- // --sync-data: "Multi-env initialized, data synced to dev"
80
- const tty = (0, render_1.isStdoutTty)();
81
- const prefix = tty ? "✓" : "OK";
82
- const body = result.dataSynced
83
- ? "Multi-env initialized, data synced to dev"
84
- : `Multi-env initialized (${result.environments.join(" / ")})`;
85
- (0, output_1.emit)(`${prefix} ${body}`);
86
- }
87
- async function handleDbMigrationDiff(opts) {
88
- const appId = (0, shared_1.resolveAppId)(opts);
89
- let result;
90
- try {
91
- result = await api.db.migrate({ appId, dryRun: true });
92
- }
93
- catch (err) {
94
- throw decorateMigrationError(err);
95
- }
96
- // PRD: diff 在无待发布变更时报错带 hint,而不是渲染空列表
97
- if (result.changes.length === 0) {
98
- throw new error_1.AppError("DB_API_k_dl_1300035", `No pending changes between ${result.from} and ${result.to}`, {
99
- next_actions: [
100
- 'Make schema changes in dev first (e.g. `miaoda db sql "ALTER TABLE ..." --env dev`)',
101
- ],
102
- });
103
- }
104
- renderDiff(result);
105
- }
106
- async function handleDbMigrationApply(opts) {
107
- const appId = (0, shared_1.resolveAppId)(opts);
108
- // TTY 下先 diff 给用户审;--yes 直接打到 online
109
- if (!opts.yes && !(0, output_1.isJsonMode)()) {
110
- let preview;
111
- try {
112
- preview = await api.db.migrate({ appId, dryRun: true });
113
- }
114
- catch (err) {
115
- throw decorateMigrationError(err);
116
- }
117
- if (preview.changes.length === 0) {
118
- // PRD 文案 + hint
119
- throw new error_1.AppError("DB_API_k_dl_1300035", `No pending changes between ${preview.from} and ${preview.to}`, {
120
- next_actions: [
121
- 'Make schema changes in dev first (e.g. `miaoda db sql "ALTER TABLE ..." --env dev`)',
122
- ],
123
- });
124
- }
125
- renderDiff(preview);
126
- const ok = await confirm(`? Apply ${String(preview.changes.length)} change(s) to ${preview.to}? (y/N) `);
127
- if (!ok) {
128
- (0, output_1.emit)("Aborted.");
129
- return;
130
- }
131
- }
132
- let result;
133
- try {
134
- result = await api.db.migrate({ appId, dryRun: false });
135
- }
136
- catch (err) {
137
- throw decorateMigrationError(err);
138
- }
139
- if ((0, output_1.isJsonMode)()) {
140
- // PRD:{"status": "applied", "from": "dev", "to": "online", "changes_applied": 2}
141
- (0, output_1.emitOk)((0, output_1.snakeCaseKeys)({
142
- status: result.status ?? "applied",
143
- from: result.from,
144
- to: result.to,
145
- changesApplied: result.changesApplied ?? result.changes.length,
146
- }));
147
- return;
148
- }
149
- const tty = (0, render_1.isStdoutTty)();
150
- const prefix = tty ? "✓" : "OK";
151
- const arrow = tty ? "→" : "->";
152
- const applied = result.changesApplied ?? result.changes.length;
153
- (0, output_1.emit)(`${prefix} Applied ${result.from} ${arrow} ${result.to} (${String(applied)} changes)`);
154
- }
155
- // ── helpers ──
156
- // PRD diff 输出:
157
- // dev → online (2 changes):
158
- //
159
- // ALTER TABLE users ADD COLUMN avatar_url text;
160
- // CREATE INDEX idx_users_avatar ON users(avatar_url);
161
- function renderDiff(result) {
162
- if ((0, output_1.isJsonMode)()) {
163
- (0, output_1.emitOk)((0, output_1.snakeCaseKeys)({
164
- from: result.from,
165
- to: result.to,
166
- changes: result.changes.map((c) => ({
167
- type: c.type,
168
- table: c.table,
169
- statement: c.statement,
170
- })),
171
- }));
172
- return;
173
- }
174
- const tty = (0, render_1.isStdoutTty)();
175
- if (result.changes.length === 0) {
176
- (0, output_1.emit)(`No pending changes from ${result.from} to ${result.to}.`);
177
- return;
178
- }
179
- const arrow = tty ? "→" : "->";
180
- (0, output_1.emit)(`${result.from} ${arrow} ${result.to} (${String(result.changes.length)} changes):\n\n` +
181
- result.changes.map((c) => ` ${c.statement}`).join("\n"));
182
- }
183
- // decorateMigrationError 给 migration / recovery 路径上的几个错误码补 PRD 规定的 hint。
184
- // dataloom 后端只返 message + code,hint 由 CLI 端按错误码映射;其它错误码原样透传。
185
- function decorateMigrationError(err) {
186
- if (!(err instanceof error_1.AppError))
187
- return err;
188
- switch (err.code) {
189
- case "DB_API_k_dl_1300039":
190
- // 多环境未初始化:引导先 init
191
- return new error_1.AppError(err.code, err.message, {
192
- next_actions: ["Run `miaoda db migration init` to set up multi-env first."],
193
- });
194
- case "DB_API_k_dl_1300035":
195
- // 无待发布变更:引导先在 dev 改 schema
196
- return new error_1.AppError(err.code, err.message, {
197
- next_actions: [
198
- 'Make schema changes in dev first (e.g. `miaoda db sql "ALTER TABLE ..." --env dev`)',
199
- ],
200
- });
201
- default:
202
- return err;
203
- }
204
- }
205
- async function confirm(prompt) {
206
- const rl = node_readline_1.default.createInterface({ input: process.stdin, output: process.stderr });
207
- return new Promise((resolve) => {
208
- rl.question(prompt, (answer) => {
209
- rl.close();
210
- resolve(answer.trim().toLowerCase() === "y");
211
- });
212
- });
213
- }