@geek-fun/serverlessinsight 0.9.1 → 0.9.2

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 (58) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -1
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -2
  3. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +2 -2
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +3 -3
  5. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +4 -4
  6. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  7. package/.serverlessinsight/state-insight-poc-timer-app-insight-poc-timer.json.backup +109 -0
  8. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  9. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +3 -3
  10. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +2 -2
  11. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  12. package/CHANGELOG.md +17 -0
  13. package/README.md +76 -0
  14. package/README.zh-CN.md +67 -0
  15. package/codecov +0 -0
  16. package/codecov.SHA256SUM +1 -0
  17. package/codecov.SHA256SUM.sig +16 -0
  18. package/dist/package.json +1 -1
  19. package/dist/src/commands/index.js +75 -23
  20. package/dist/src/commands/plan.js +21 -1
  21. package/dist/src/commands/schema.js +24 -0
  22. package/dist/src/commands/show.js +64 -10
  23. package/dist/src/commands/validate.js +34 -2
  24. package/dist/src/common/aliyunClient/fc3Operations.js +32 -1
  25. package/dist/src/common/constants.js +7 -1
  26. package/dist/src/common/jsonOutput.js +77 -0
  27. package/dist/src/common/logger.js +6 -3
  28. package/dist/src/common/noColor.js +9 -0
  29. package/dist/src/common/planFormatter.js +12 -6
  30. package/dist/src/common/siCron.js +415 -0
  31. package/dist/src/common/stateBackend/saasStateBackend.js +5 -4
  32. package/dist/src/common/tencentClient/scfOperations.js +2 -0
  33. package/dist/src/common/volcengineClient/vefaasOperations.js +45 -0
  34. package/dist/src/lang/en.js +43 -0
  35. package/dist/src/lang/index.js +36 -1
  36. package/dist/src/lang/zh-CN.js +43 -0
  37. package/dist/src/parser/functionParser.js +47 -1
  38. package/dist/src/stack/aliyunStack/fc3Planner.js +26 -0
  39. package/dist/src/stack/aliyunStack/fc3Resource.js +159 -2
  40. package/dist/src/stack/localStack/event.js +2 -13
  41. package/dist/src/stack/localStack/function.js +2 -13
  42. package/dist/src/stack/localStack/index.js +8 -1
  43. package/dist/src/stack/localStack/timer.js +162 -0
  44. package/dist/src/stack/localStack/utils.js +19 -1
  45. package/dist/src/stack/scfStack/scfPlanner.js +52 -18
  46. package/dist/src/stack/scfStack/scfResource.js +170 -1
  47. package/dist/src/stack/volcengineStack/vefaasPlanner.js +49 -0
  48. package/dist/src/stack/volcengineStack/vefaasResource.js +215 -2
  49. package/dist/src/validator/functionSchema.js +25 -2
  50. package/dist/src/validator/iacSchema.js +2 -1
  51. package/dist/src/validator/index.js +4 -1
  52. package/dist/src/validator/rootSchema.js +49 -18
  53. package/dist/src/validator/schemaExport.js +60 -0
  54. package/dist/src/validator/semanticValidation.js +79 -0
  55. package/dist/src/validator/templateRefSchema.js +9 -1
  56. package/dist/tsconfig.tsbuildinfo +1 -1
  57. package/package.json +1 -1
  58. package/samples/aliyun-poc-timer.yml +39 -0
@@ -10,11 +10,13 @@ const local_1 = require("./local");
10
10
  const plan_1 = require("./plan");
11
11
  const forceUnlock_1 = require("./forceUnlock");
12
12
  const show_1 = require("./show");
13
+ const schema_1 = require("./schema");
13
14
  const login_1 = require("./login");
14
15
  const logout_1 = require("./logout");
15
16
  const whoami_1 = require("./whoami");
16
17
  const migrate_1 = require("./migrate");
17
18
  const lang_1 = require("../lang");
19
+ const jsonOutput_1 = require("../common/jsonOutput");
18
20
  const parser_1 = require("../parser");
19
21
  const MAX_ERROR_MESSAGE_LENGTH = 2000;
20
22
  const truncateErrorMessage = (message) => {
@@ -24,6 +26,27 @@ const truncateErrorMessage = (message) => {
24
26
  ? `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}… (truncated ${message.length} chars)`
25
27
  : message;
26
28
  };
29
+ /**
30
+ * Issue #250: a thrown error's stable machine code is the i18n key behind its
31
+ * message. Errors may already carry a `code` (an i18n key); otherwise the
32
+ * message is mapped back through the catalogs — locale-independent, so the
33
+ * code is identical under LANG=zh_CN and LANG=en_US.
34
+ */
35
+ const resolveErrorCode = (error) => {
36
+ if (typeof error?.code === 'string' && (0, lang_1.hasLangKey)(error.code)) {
37
+ return error.code;
38
+ }
39
+ const fromMessage = (0, lang_1.lookupErrorCode)(error?.message);
40
+ if (fromMessage) {
41
+ return fromMessage;
42
+ }
43
+ return typeof error?.code === 'string' ? error.code : undefined;
44
+ };
45
+ // Let queued stdout writes flush (async on macOS pipes) before the process
46
+ // ends, so a piped `si ... --json | jq` never sees a truncated document.
47
+ const flushStdoutAndExit = (exitCode) => {
48
+ process.stdout.write('', () => process.exit(exitCode));
49
+ };
27
50
  // Global error handler
28
51
  const handleCommandError = (error, commandName) => {
29
52
  // Skip logging if already logged by handlePartialFailure
@@ -34,30 +57,28 @@ const handleCommandError = (error, commandName) => {
34
57
  error: truncateErrorMessage(error?.message) || 'Unknown error occurred',
35
58
  }));
36
59
  }
60
+ const errorCode = resolveErrorCode(error);
61
+ if (errorCode) {
62
+ common_1.logger.error(lang_1.lang.__('ERROR_CODE', { code: errorCode }));
63
+ }
37
64
  if (error?.stack && process.env.DEBUG) {
38
65
  common_1.logger.debug(lang_1.lang.__('STACK_TRACE', { stack: error.stack }));
39
66
  }
40
- let exitCode = 1;
41
- if (error?.code) {
42
- if (typeof error.code === 'number') {
43
- exitCode = error.code;
44
- }
45
- else if (typeof error.code === 'string') {
46
- const errorCodeMap = {
47
- ENOENT: 2,
48
- EACCES: 3,
49
- VALIDATION: 4,
50
- NETWORK: 5,
51
- };
52
- exitCode = errorCodeMap[error.code] || 1;
53
- }
67
+ if ((0, jsonOutput_1.isJsonMode)()) {
68
+ (0, jsonOutput_1.writeJson)({
69
+ error: {
70
+ code: errorCode ?? 'UNKNOWN',
71
+ message: truncateErrorMessage(error?.message) || 'Unknown error occurred',
72
+ },
73
+ });
54
74
  }
55
- process.exit(exitCode);
75
+ flushStdoutAndExit(1);
56
76
  };
57
77
  const actionWrapper = (commandName, handler) => {
58
78
  // Reset context before each command execution
59
79
  (0, common_1.clearContext)();
60
80
  return async (...args) => {
81
+ (0, jsonOutput_1.setJsonMode)(false);
61
82
  try {
62
83
  await handler(...args);
63
84
  }
@@ -87,12 +108,21 @@ program
87
108
  .action(actionWrapper('whoami', async () => {
88
109
  await (0, whoami_1.whoami)();
89
110
  }));
111
+ program
112
+ .command('schema')
113
+ .description(lang_1.lang.__('CMD_SCHEMA_DESC'))
114
+ .option('-o, --output <path>', lang_1.lang.__('OPT_SCHEMA_OUTPUT'))
115
+ .action(actionWrapper('schema', async ({ output }) => {
116
+ await (0, schema_1.schema)({ output });
117
+ }));
90
118
  program
91
119
  .command('show')
92
120
  .description(lang_1.lang.__('CMD_SHOW_DESC'))
93
121
  .option('-f, --file <path>', lang_1.lang.__('OPT_FILE'))
94
122
  .option('-s, --stage <stage>', lang_1.lang.__('OPT_STAGE'))
95
- .action(actionWrapper('show', async ({ file, stage }) => {
123
+ .option('--json', lang_1.lang.__('OPT_JSON'))
124
+ .action(actionWrapper('show', async ({ file, stage, json }) => {
125
+ (0, jsonOutput_1.setJsonMode)(!!json);
96
126
  const iacLocation = (0, common_1.getIacLocation)(file);
97
127
  const rawIac = (0, parser_1.parseYaml)(iacLocation);
98
128
  await (0, common_1.setContext)({
@@ -106,16 +136,22 @@ program
106
136
  const context = (0, common_1.getContext)();
107
137
  const iac = (0, parser_1.revalYaml)(iacLocation, context);
108
138
  (0, common_1.setIac)(iac);
109
- await (0, show_1.show)({ stage, location: file, iac });
139
+ await (0, show_1.show)({ stage, location: file, iac, json: !!json });
110
140
  }));
111
141
  program
112
142
  .command('validate')
113
143
  .description(lang_1.lang.__('CMD_VALIDATE_DESC'))
114
144
  .option('-f, --file <path>', lang_1.lang.__('OPT_FILE'))
115
145
  .option('-s, --stage <stage>', lang_1.lang.__('OPT_STAGE'))
116
- .action(actionWrapper('validate', async ({ file, stage }) => {
146
+ .option('--json', lang_1.lang.__('OPT_JSON'))
147
+ .action(actionWrapper('validate', async ({ file, stage, json }) => {
148
+ (0, jsonOutput_1.setJsonMode)(!!json);
117
149
  common_1.logger.debug(lang_1.lang.__('LOG_COMMAND_INFO'));
118
- await (0, validate_1.validate)({ stage, location: file });
150
+ const result = await (0, validate_1.validate)({ stage, location: file, json: !!json });
151
+ // Issue #250 exit-code convention: 0 = valid, 1 = validation failed.
152
+ if (!result.valid) {
153
+ process.exitCode = 1;
154
+ }
119
155
  }));
120
156
  program
121
157
  .command('plan')
@@ -128,8 +164,10 @@ program
128
164
  .option('-x, --accessKeySecret <accessKeySecret>', lang_1.lang.__('OPT_ACCESS_KEY_SECRET'))
129
165
  .option('-n, --securityToken <securityToken>', lang_1.lang.__('OPT_SECURITY_TOKEN'))
130
166
  .option('--no-refresh', lang_1.lang.__('OPT_NO_REFRESH'))
131
- .action(actionWrapper('plan', async ({ stage, file, region, provider, accessKeyId, accessKeySecret, securityToken, refresh, }) => {
132
- await (0, plan_1.plan)({
167
+ .option('--json', lang_1.lang.__('OPT_JSON'))
168
+ .option('--no-color', lang_1.lang.__('OPT_NO_COLOR'))
169
+ .action(actionWrapper('plan', async ({ stage, file, region, provider, accessKeyId, accessKeySecret, securityToken, refresh, json, color, }) => {
170
+ const result = await (0, plan_1.plan)({
133
171
  stage,
134
172
  location: file,
135
173
  region,
@@ -138,7 +176,14 @@ program
138
176
  accessKeySecret,
139
177
  securityToken,
140
178
  refresh,
179
+ json: !!json,
180
+ noColor: color === false,
141
181
  });
182
+ // Issue #250 exit-code convention (terraform-compatible):
183
+ // 0 = no changes, 2 = changes present, 1 = execution error (handler).
184
+ if (result.hasChanges) {
185
+ process.exitCode = 2;
186
+ }
142
187
  }));
143
188
  // Issue #246: `diff` is the primary verb users say — it runs the same plan
144
189
  // flow; `plan` stays for compatibility.
@@ -153,8 +198,10 @@ program
153
198
  .option('-x, --accessKeySecret <accessKeySecret>', lang_1.lang.__('OPT_ACCESS_KEY_SECRET'))
154
199
  .option('-n, --securityToken <securityToken>', lang_1.lang.__('OPT_SECURITY_TOKEN'))
155
200
  .option('--no-refresh', lang_1.lang.__('OPT_NO_REFRESH'))
156
- .action(actionWrapper('diff', async ({ stage, file, region, provider, accessKeyId, accessKeySecret, securityToken, refresh, }) => {
157
- await (0, plan_1.plan)({
201
+ .option('--json', lang_1.lang.__('OPT_JSON'))
202
+ .option('--no-color', lang_1.lang.__('OPT_NO_COLOR'))
203
+ .action(actionWrapper('diff', async ({ stage, file, region, provider, accessKeyId, accessKeySecret, securityToken, refresh, json, color, }) => {
204
+ const result = await (0, plan_1.plan)({
158
205
  stage,
159
206
  location: file,
160
207
  region,
@@ -163,7 +210,12 @@ program
163
210
  accessKeySecret,
164
211
  securityToken,
165
212
  refresh,
213
+ json: !!json,
214
+ noColor: color === false,
166
215
  });
216
+ if (result.hasChanges) {
217
+ process.exitCode = 2;
218
+ }
167
219
  }));
168
220
  program
169
221
  .command('deploy')
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.plan = void 0;
4
4
  const common_1 = require("../common");
5
5
  const stateBackend_1 = require("../common/stateBackend");
6
+ const jsonOutput_1 = require("../common/jsonOutput");
7
+ const noColor_1 = require("../common/noColor");
6
8
  const parser_1 = require("../parser");
7
9
  const scfStack_1 = require("../stack/scfStack");
8
10
  const aliyunStack_1 = require("../stack/aliyunStack");
@@ -46,6 +48,24 @@ const plan = async (options) => {
46
48
  common_1.logger.error(lang_1.lang.__('PLAN_COMMAND_NOT_SUPPORTED'));
47
49
  throw new Error(lang_1.lang.__('PLAN_COMMAND_NOT_SUPPORTED'));
48
50
  }
49
- (0, scfStack_1.displayPlan)(planResult);
51
+ if (options.json) {
52
+ (0, jsonOutput_1.writeJson)((0, jsonOutput_1.buildPlanJson)(planResult, {
53
+ provider: iac.provider.name,
54
+ app: iac.app,
55
+ service: iac.service,
56
+ stage: context.stage,
57
+ }));
58
+ }
59
+ else {
60
+ const displayConfig = {
61
+ colorize: !(options.noColor ?? false) && !(0, noColor_1.isNoColorEnabled)(),
62
+ indentSize: 4,
63
+ keyAlignWidth: 12,
64
+ };
65
+ (0, scfStack_1.displayPlan)(planResult, displayConfig);
66
+ }
67
+ const summary = (0, jsonOutput_1.buildPlanSummary)(planResult.items ?? []);
68
+ const changeCount = summary.create + summary.update + summary.destroy + summary.recreate;
69
+ return { hasChanges: changeCount > 0 };
50
70
  };
51
71
  exports.plan = plan;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.schema = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const validator_1 = require("../validator");
6
+ const logger_1 = require("../common/logger");
7
+ const lang_1 = require("../lang");
8
+ /**
9
+ * Issue #250: export the JSON Schema the validator compiles against as a
10
+ * self-contained, standard draft-07 document — the anchor agents use for
11
+ * structured YAML generation, editors use for completion, and `si validate`
12
+ * loops use for pre-flight checks.
13
+ */
14
+ const schema = async (options) => {
15
+ const exported = (0, validator_1.exportIacJsonSchema)();
16
+ const payload = `${JSON.stringify(exported, null, 2)}\n`;
17
+ if (options.output) {
18
+ (0, node_fs_1.writeFileSync)(options.output, payload, 'utf8');
19
+ logger_1.logger.info(lang_1.lang.__('SCHEMA_WRITTEN_TO', { path: options.output }));
20
+ return;
21
+ }
22
+ process.stdout.write(payload);
23
+ };
24
+ exports.schema = schema;
@@ -1,14 +1,38 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.show = void 0;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
4
9
  const types_1 = require("../types");
5
10
  const backend_1 = require("../types/domains/backend");
6
11
  const common_1 = require("../common");
7
12
  const lockManager_1 = require("../common/lockManager");
8
13
  const stateBackend_1 = require("../common/stateBackend");
9
14
  const migrationMarker_1 = require("../common/migrationMarker");
15
+ const jsonOutput_1 = require("../common/jsonOutput");
10
16
  const logger_1 = require("../common/logger");
11
17
  const lang_1 = require("../lang");
18
+ /**
19
+ * The CLI passes the yaml file path as `location`; the state directory lives
20
+ * next to that file, not underneath it. A directory (or cwd) stays as-is.
21
+ */
22
+ const resolveBaseDir = (location) => {
23
+ if (!location) {
24
+ return process.cwd();
25
+ }
26
+ try {
27
+ if (node_fs_1.default.statSync(location).isFile()) {
28
+ return node_path_1.default.dirname(location);
29
+ }
30
+ }
31
+ catch {
32
+ // not an existing file — treat as a directory
33
+ }
34
+ return location;
35
+ };
12
36
  const formatTimeAgo = (dateStr) => {
13
37
  const date = new Date(dateStr);
14
38
  const now = new Date();
@@ -171,14 +195,16 @@ const getBackendLocationString = (backendConfig) => {
171
195
  const config = backendConfig;
172
196
  return `bucket://${config.bucket}/${config.key}`;
173
197
  };
198
+ const SAAS_STATE_LOCATION = 'saas';
174
199
  const show = async (options) => {
175
200
  const context = (0, common_1.getContext)();
176
201
  const stage = options.stage ?? context.stage;
177
- const baseDir = options.location ?? process.cwd();
202
+ const baseDir = resolveBaseDir(options.location);
178
203
  logger_1.logger.info(lang_1.lang.__('SHOW_LOADING_STATE', { app: context.app, service: context.service, stage }));
179
204
  let state;
180
205
  let lockInfo;
181
206
  let stateLocation;
207
+ let stateLocationDisplay;
182
208
  let usingRemoteBackend = false;
183
209
  const backendType = options.iac?.backend?.type;
184
210
  const shouldUseRemoteBackend = backendType === backend_1.StateBackendType.BUCKET_STORE ||
@@ -197,7 +223,7 @@ const show = async (options) => {
197
223
  usingRemoteBackend = true;
198
224
  stateLocation =
199
225
  backendType === backend_1.StateBackendType.SAAS || !backendType
200
- ? 'Console (SaaS state)'
226
+ ? SAAS_STATE_LOCATION
201
227
  : getBackendLocationString(options.iac.backend);
202
228
  }
203
229
  catch (error) {
@@ -216,18 +242,46 @@ const show = async (options) => {
216
242
  lockInfo = readLocalLock(context.app, context.service, baseDir);
217
243
  stateLocation = (0, common_1.getStatePath)(context.app, context.service, baseDir);
218
244
  }
245
+ stateLocationDisplay =
246
+ stateLocation === SAAS_STATE_LOCATION ? lang_1.lang.__('SHOW_BACKEND_SAAS') : stateLocation;
219
247
  }
220
248
  else {
221
249
  state = loadLocalState(context.provider, context.app, context.service, stage, baseDir);
222
250
  lockInfo = readLocalLock(context.app, context.service, baseDir);
223
251
  stateLocation = (0, common_1.getStatePath)(context.app, context.service, baseDir);
252
+ stateLocationDisplay = stateLocation;
224
253
  }
225
254
  const resources = state.resources;
226
255
  const resourceCount = Object.keys(resources).length;
256
+ if (options.json) {
257
+ const backendKind = !usingRemoteBackend
258
+ ? 'local'
259
+ : backendType === backend_1.StateBackendType.BUCKET_STORE
260
+ ? 'bucket_store'
261
+ : 'saas';
262
+ const payload = {
263
+ showVersion: jsonOutput_1.SHOW_JSON_VERSION,
264
+ provider: state.provider,
265
+ app: state.app,
266
+ service: state.service,
267
+ stage,
268
+ ...(state.serial !== undefined ? { serial: state.serial } : {}),
269
+ ...(state.lineage !== undefined ? { lineage: state.lineage } : {}),
270
+ ...(state.managedBy !== undefined ? { managedBy: state.managedBy } : {}),
271
+ stateLocation,
272
+ backend: backendKind,
273
+ locked: !!lockInfo,
274
+ lock: lockInfo ? { ...lockInfo } : null,
275
+ resources: resources,
276
+ resourceCount,
277
+ };
278
+ (0, jsonOutput_1.writeJson)(payload);
279
+ return;
280
+ }
227
281
  if (resourceCount === 0) {
228
282
  logger_1.logger.info(lang_1.lang.__('SHOW_NO_RESOURCES'));
229
283
  logger_1.logger.info('');
230
- logger_1.logger.info(lang_1.lang.__('SHOW_STATE_LOCATION', { stateLocation }));
284
+ logger_1.logger.info(lang_1.lang.__('SHOW_STATE_LOCATION', { stateLocation: stateLocationDisplay }));
231
285
  if (usingRemoteBackend) {
232
286
  logger_1.logger.info(lang_1.lang.__('SHOW_BACKEND_REMOTE'));
233
287
  }
@@ -264,12 +318,12 @@ const show = async (options) => {
264
318
  }
265
319
  const categoryOrder = ['functions', 'apiGateway', 'storage', 'databases', 'dns', 'other'];
266
320
  const categoryLabels = {
267
- functions: 'Functions',
268
- apiGateway: 'API Gateway',
269
- storage: 'Storage',
270
- databases: 'Databases',
271
- dns: 'DNS Records',
272
- other: 'Other Resources',
321
+ functions: lang_1.lang.__('SHOW_CAT_FUNCTIONS'),
322
+ apiGateway: lang_1.lang.__('SHOW_CAT_API_GATEWAY'),
323
+ storage: lang_1.lang.__('SHOW_CAT_STORAGE'),
324
+ databases: lang_1.lang.__('SHOW_CAT_DATABASES'),
325
+ dns: lang_1.lang.__('SHOW_CAT_DNS'),
326
+ other: lang_1.lang.__('SHOW_CAT_OTHER'),
273
327
  };
274
328
  for (const category of categoryOrder) {
275
329
  const resourcesInCategory = groupedResources[category];
@@ -308,7 +362,7 @@ const show = async (options) => {
308
362
  }
309
363
  }
310
364
  logger_1.logger.info('');
311
- logger_1.logger.info(lang_1.lang.__('SHOW_STATE_LOCATION', { stateLocation }));
365
+ logger_1.logger.info(lang_1.lang.__('SHOW_STATE_LOCATION', { stateLocation: stateLocationDisplay }));
312
366
  if (usingRemoteBackend) {
313
367
  logger_1.logger.info(lang_1.lang.__('SHOW_BACKEND_REMOTE'));
314
368
  }
@@ -3,13 +3,45 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validate = void 0;
4
4
  const common_1 = require("../common");
5
5
  const parser_1 = require("../parser");
6
+ const validator_1 = require("../validator");
7
+ const jsonOutput_1 = require("../common/jsonOutput");
6
8
  const lang_1 = require("../lang");
7
9
  const validate = async (options) => {
8
10
  const iacLocation = (0, common_1.getIacLocation)(options.location);
11
+ if (options.json) {
12
+ try {
13
+ await runValidation(iacLocation, options);
14
+ }
15
+ catch (error) {
16
+ if (error instanceof validator_1.IacSchemaErrors) {
17
+ (0, jsonOutput_1.writeJson)({
18
+ validateVersion: jsonOutput_1.VALIDATE_JSON_VERSION,
19
+ valid: false,
20
+ errors: error.errors.map((schemaError) => ({
21
+ path: schemaError.instancePath,
22
+ keyword: schemaError.type,
23
+ message: schemaError.message,
24
+ ...(schemaError.allowedValues && schemaError.allowedValues.length > 0
25
+ ? { allowedValues: schemaError.allowedValues }
26
+ : {}),
27
+ })),
28
+ });
29
+ return { valid: false };
30
+ }
31
+ throw error;
32
+ }
33
+ common_1.logger.info(lang_1.lang.__('YAML_VALID'));
34
+ (0, jsonOutput_1.writeJson)({ validateVersion: jsonOutput_1.VALIDATE_JSON_VERSION, valid: true, errors: [] });
35
+ return { valid: true };
36
+ }
37
+ await runValidation(iacLocation, options);
38
+ common_1.logger.info(lang_1.lang.__('YAML_VALID'));
39
+ return { valid: true };
40
+ };
41
+ exports.validate = validate;
42
+ const runValidation = async (iacLocation, options) => {
9
43
  const rawIac = (0, parser_1.parseYaml)(iacLocation);
10
44
  await (0, common_1.setContext)({ app: rawIac.app, service: rawIac.service, ...options });
11
45
  const context = (0, common_1.getContext)();
12
46
  (0, parser_1.parseYaml)(context.iacLocation);
13
- common_1.logger.info(lang_1.lang.__('YAML_VALID'));
14
47
  };
15
- exports.validate = validate;
@@ -494,18 +494,49 @@ const buildCodeLocation = (codePath, ossCode) => {
494
494
  // a subsequent create (retry) does not collide with a still-deleting function.
495
495
  await operations.waitForFunctionDeleted(functionName);
496
496
  },
497
- createTrigger: async (functionName, triggerName, triggerType, triggerConfig, qualifier) => {
497
+ createTrigger: async (functionName, triggerName, triggerType, triggerConfig, qualifier, description) => {
498
498
  const createTriggerInput = new fc.CreateTriggerInput({
499
499
  triggerName,
500
500
  triggerType,
501
501
  triggerConfig: JSON.stringify(triggerConfig),
502
502
  ...(qualifier ? { qualifier } : {}),
503
+ ...(description ? { description } : {}),
503
504
  });
504
505
  const request = new fc.CreateTriggerRequest({
505
506
  body: createTriggerInput,
506
507
  });
507
508
  await fc3Client.createTrigger(functionName, request);
508
509
  },
510
+ listTriggers: async (functionName) => {
511
+ // follow nextToken — a partial page would make the trigger reconcile
512
+ // treat every page-2 trigger as stale and delete it
513
+ const triggers = [];
514
+ let nextToken;
515
+ do {
516
+ const response = await fc3Client.listTriggers(functionName, new fc.ListTriggersRequest(nextToken ? { nextToken } : {}));
517
+ const body = (response.body ?? {});
518
+ triggers.push(...(body.triggers ?? []));
519
+ nextToken = body.nextToken;
520
+ } while (nextToken);
521
+ // the SDK models triggerConfig as a JSON string — normalize to an object
522
+ const parseConfig = (raw) => {
523
+ if (typeof raw !== 'string') {
524
+ return raw;
525
+ }
526
+ try {
527
+ return JSON.parse(raw);
528
+ }
529
+ catch {
530
+ return raw;
531
+ }
532
+ };
533
+ return triggers.map((trigger) => ({
534
+ triggerName: trigger.triggerName,
535
+ triggerType: trigger.triggerType,
536
+ triggerConfig: parseConfig(trigger.triggerConfig),
537
+ description: trigger.description,
538
+ }));
539
+ },
509
540
  deleteTrigger: async (functionName, triggerName) => {
510
541
  await fc3Client.deleteTrigger(functionName, triggerName);
511
542
  },
@@ -5,7 +5,13 @@ exports.CODE_ZIP_SIZE_LIMIT = 300 * 1000; // 300 KB - code package size limit fo
5
5
  exports.OSS_DEPLOYMENT_TIMEOUT = 3000; // in seconds
6
6
  exports.SI_BOOTSTRAP_FC_PREFIX = 'si-bootstrap-api';
7
7
  exports.SI_BOOTSTRAP_BUCKET_PREFIX = 'si-bootstrap-artifacts';
8
- exports.SI_LOCALSTACK_SERVER_PORT = 4567;
8
+ // Local dev server port. Under jest, each worker shifts its base port so
9
+ // parallel test files binding the server never collide on one fixed port
10
+ // (pre-existing flake: localServer/index/aliyunFc suites all bind 4567).
11
+ const SI_LOCALSTACK_TEST_WORKER_PORT = process.env.JEST_WORKER_ID && Number.isInteger(Number(process.env.JEST_WORKER_ID))
12
+ ? 4570 + Number(process.env.JEST_WORKER_ID)
13
+ : undefined;
14
+ exports.SI_LOCALSTACK_SERVER_PORT = Number(process.env.SI_LOCALSTACK_SERVER_PORT) || SI_LOCALSTACK_TEST_WORKER_PORT || 4567;
9
15
  exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = 120000;
10
16
  exports.ALIYUN_FC3_READ_TIMEOUT_MS = 600000;
11
17
  // Query-tier budget for synchronous management-plane RPCs (all non-fc3 aliyun
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildPlanJson = exports.buildPlanChange = exports.buildPlanSummary = exports.writeJson = exports.isJsonMode = exports.setJsonMode = exports.SHOW_JSON_VERSION = exports.VALIDATE_JSON_VERSION = exports.PLAN_JSON_VERSION = void 0;
4
+ const planFormatter_1 = require("./planFormatter");
5
+ /**
6
+ * Machine-readable output channel (issue #250): the `--json` surface of the CLI.
7
+ *
8
+ * Contract with agents:
9
+ * - logs (pino) go to stderr, JSON results go to stdout — a pipe of stdout is
10
+ * always a single JSON document (jq-parseable);
11
+ * - every envelope carries a version field (`planVersion` / `validateVersion` /
12
+ * `showVersion`) so consumers can pin a shape;
13
+ * - failures emit `{ error: { code, message } }` where `code` is the stable
14
+ * i18n key behind the message — locale changes never change the code.
15
+ */
16
+ exports.PLAN_JSON_VERSION = 1;
17
+ exports.VALIDATE_JSON_VERSION = 1;
18
+ exports.SHOW_JSON_VERSION = 1;
19
+ let jsonMode = false;
20
+ const setJsonMode = (enabled) => {
21
+ jsonMode = enabled;
22
+ };
23
+ exports.setJsonMode = setJsonMode;
24
+ const isJsonMode = () => jsonMode;
25
+ exports.isJsonMode = isJsonMode;
26
+ const writeJson = (payload) => {
27
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
28
+ };
29
+ exports.writeJson = writeJson;
30
+ const buildPlanSummary = (items) => items.reduce((summary, item) => {
31
+ if (item.action === 'noop') {
32
+ return { ...summary, unchanged: summary.unchanged + 1 };
33
+ }
34
+ if (item.action === 'create') {
35
+ return (0, planFormatter_1.isRecreate)(item)
36
+ ? { ...summary, recreate: summary.recreate + 1 }
37
+ : { ...summary, create: summary.create + 1 };
38
+ }
39
+ if (item.action === 'update') {
40
+ return { ...summary, update: summary.update + 1 };
41
+ }
42
+ return { ...summary, destroy: summary.destroy + 1 };
43
+ }, { create: 0, update: 0, destroy: 0, recreate: 0, unchanged: 0 });
44
+ exports.buildPlanSummary = buildPlanSummary;
45
+ const toPlanJsonAction = (item) => {
46
+ if (item.action === 'delete')
47
+ return 'destroy';
48
+ if (item.action === 'create' && (0, planFormatter_1.isRecreate)(item))
49
+ return 'recreate';
50
+ return item.action === 'update' ? 'update' : 'create';
51
+ };
52
+ const buildPlanChange = (item) => {
53
+ const attributes = item.changes
54
+ ? (0, planFormatter_1.computeAttributeDiffs)(item.changes.before, item.changes.after).diffs
55
+ : [];
56
+ return {
57
+ logicalId: item.logicalId,
58
+ type: item.resourceType,
59
+ action: toPlanJsonAction(item),
60
+ attributes,
61
+ ...(item.drifted ? { drifted: true } : {}),
62
+ ...(item.driftReasons && item.driftReasons.length > 0
63
+ ? { driftReasons: item.driftReasons }
64
+ : {}),
65
+ };
66
+ };
67
+ exports.buildPlanChange = buildPlanChange;
68
+ const buildPlanJson = (planResult, identity) => {
69
+ const items = planResult.items ?? [];
70
+ return {
71
+ planVersion: exports.PLAN_JSON_VERSION,
72
+ ...identity,
73
+ changes: items.filter((item) => item.action !== 'noop').map(exports.buildPlanChange),
74
+ summary: (0, exports.buildPlanSummary)(items),
75
+ };
76
+ };
77
+ exports.buildPlanJson = buildPlanJson;
@@ -9,6 +9,7 @@ const pino_pretty_1 = __importDefault(require("pino-pretty"));
9
9
  const child_process_1 = require("child_process");
10
10
  const iconv_lite_1 = __importDefault(require("iconv-lite"));
11
11
  const stream_1 = require("stream");
12
+ const noColor_1 = require("./noColor");
12
13
  const CODE_PAGE_TO_ENCODING = {
13
14
  932: 'shift_jis', // Japanese
14
15
  936: 'gbk', // Simplified Chinese
@@ -71,7 +72,7 @@ class EncodingTransformStream extends stream_1.Writable {
71
72
  super();
72
73
  this.encoding = encoding;
73
74
  this.formatLog = pino_pretty_1.default.prettyFactory({
74
- colorize: true,
75
+ colorize: !(0, noColor_1.isNoColorEnabled)(),
75
76
  translateTime: 'HH:MM:ss',
76
77
  ignore: 'pid,hostname',
77
78
  messageFormat: '{msg}',
@@ -81,11 +82,13 @@ class EncodingTransformStream extends stream_1.Writable {
81
82
  try {
82
83
  const stringChunk = typeof chunk === 'string' ? chunk : chunk.toString();
83
84
  const formattedChunk = this.formatLog(stringChunk);
85
+ // Issue #250: logs go to stderr — stdout carries only command result
86
+ // data (--json payloads), so agents can pipe stdout straight to jq.
84
87
  if (this.encoding !== 'utf8' && iconv_lite_1.default.encodingExists(this.encoding)) {
85
- process.stdout.write(iconv_lite_1.default.toEncoding(formattedChunk, 'utf8'));
88
+ process.stderr.write(iconv_lite_1.default.toEncoding(formattedChunk, 'utf8'));
86
89
  }
87
90
  else {
88
- process.stdout.write(formattedChunk);
91
+ process.stderr.write(formattedChunk);
89
92
  }
90
93
  callback();
91
94
  }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNoColorEnabled = void 0;
4
+ /**
5
+ * no-color.org convention (issue #250): a NO_COLOR environment variable that
6
+ * is present and not an empty string disables ANSI color, regardless of value.
7
+ */
8
+ const isNoColorEnabled = () => process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '';
9
+ exports.isNoColorEnabled = isNoColorEnabled;