@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
@@ -6,12 +6,167 @@ const common_1 = require("../../common");
6
6
  const iamStatements_1 = require("../../common/iamStatements");
7
7
  const tlsOperations_1 = require("../../common/volcengineClient/tlsOperations");
8
8
  const types_1 = require("../../types");
9
+ const siCron_1 = require("../../common/siCron");
9
10
  const vefaasTypes_1 = require("./vefaasTypes");
10
11
  const logger_1 = require("../../common/logger");
11
12
  const lang_1 = require("../../lang");
12
13
  const ownershipTag_1 = require("../ownershipTag");
13
14
  const alreadyExists_1 = require("../alreadyExists");
14
15
  const sharedLogProject_1 = require("./sharedLogProject");
16
+ const TIMER_TRIGGER_INSTANCE_TYPE = 'VOLCENGINE_VEFAAS_TIMER_TRIGGER';
17
+ /** veFaaS timer dialect: unix 5-field crontab; non-zero seconds never pass. */
18
+ const buildVefaasTimerTriggerSource = (timer) => ({
19
+ cron: (0, siCron_1.translateSiCron)(timer.cron, 'volcengine'),
20
+ enable: timer.enable,
21
+ ...(timer.description !== undefined ? { description: timer.description } : {}),
22
+ ...(timer.payload !== undefined ? { payload: timer.payload } : {}),
23
+ });
24
+ const parseVefaasTimerSource = (raw) => {
25
+ if (!raw) {
26
+ return null;
27
+ }
28
+ try {
29
+ const parsed = JSON.parse(raw);
30
+ if (typeof parsed.cron !== 'string') {
31
+ return null;
32
+ }
33
+ return {
34
+ cron: parsed.cron,
35
+ enable: parsed.enable === true,
36
+ ...(typeof parsed.description === 'string' && parsed.description.length > 0
37
+ ? { description: parsed.description }
38
+ : {}),
39
+ ...(typeof parsed.payload === 'string' ? { payload: parsed.payload } : {}),
40
+ };
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ };
46
+ const vefaasTimerConfigFromAttributes = (attrs) => {
47
+ const cron = typeof attrs.cron === 'string' ? attrs.cron : undefined;
48
+ if (!cron) {
49
+ return null;
50
+ }
51
+ try {
52
+ return {
53
+ cron: (0, siCron_1.translateSiCron)(cron, 'volcengine'),
54
+ enable: attrs.enable !== false,
55
+ ...(typeof attrs.description === 'string' ? { description: attrs.description } : {}),
56
+ ...(attrs.payload !== undefined ? { payload: String(attrs.payload) } : {}),
57
+ };
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ };
63
+ const buildVefaasTimerTriggerInstance = (context, fn, timer) => ({
64
+ type: TIMER_TRIGGER_INSTANCE_TYPE,
65
+ id: timer.name,
66
+ sid: (0, common_1.buildSid)('volcengine', 'vefaas-timer-trigger', context.stage, `${fn.name}.${timer.name}`),
67
+ attributes: {
68
+ cron: timer.cron,
69
+ ...(timer.payload !== undefined ? { payload: timer.payload } : {}),
70
+ enable: timer.enable,
71
+ ...(timer.description !== undefined ? { description: timer.description } : {}),
72
+ },
73
+ });
74
+ /**
75
+ * Reconcile the function's timer triggers against the provider (issue #258).
76
+ * The live trigger list is the baseline so console edits converge on every
77
+ * deploy; state-recorded instances take over when the probe fails. Name is
78
+ * the drift key; si-cron stays stored and is translated only here.
79
+ */
80
+ const reconcileVefaasTimerTriggers = async (context, fn, functionId, previousInstances, client) => {
81
+ const desiredTimers = fn.triggers?.timer ?? [];
82
+ const previousTimers = previousInstances.filter((i) => i.type === TIMER_TRIGGER_INSTANCE_TYPE);
83
+ if (desiredTimers.length === 0 && previousTimers.length === 0) {
84
+ return [];
85
+ }
86
+ let liveTimers = [];
87
+ let liveAvailable = true;
88
+ try {
89
+ liveTimers = (await client.vefaas.listTriggers(functionId))
90
+ .filter((trigger) => trigger.sourceType?.toLowerCase() === 'timer' &&
91
+ trigger.name &&
92
+ parseVefaasTimerSource(trigger.source))
93
+ .map((trigger) => ({
94
+ id: trigger.id,
95
+ name: trigger.name,
96
+ config: parseVefaasTimerSource(trigger.source),
97
+ }));
98
+ }
99
+ catch (error) {
100
+ liveAvailable = false;
101
+ logger_1.logger.warn(lang_1.lang.__('PLAN_TIMER_TRIGGER_PROBE_FAILED', { functionName: fn.name, error: String(error) }));
102
+ }
103
+ const baseline = liveAvailable
104
+ ? liveTimers
105
+ : previousTimers.flatMap((instance) => {
106
+ const config = vefaasTimerConfigFromAttributes(instance.attributes ?? {});
107
+ return config ? [{ id: undefined, name: instance.id, config }] : [];
108
+ });
109
+ const resultingInstances = [];
110
+ for (const timer of desiredTimers) {
111
+ const desiredSource = buildVefaasTimerTriggerSource(timer);
112
+ const live = baseline.find((entry) => entry.name === timer.name);
113
+ if (!live) {
114
+ logger_1.logger.info(lang_1.lang.__('CREATING_TIMER_TRIGGER', { triggerName: timer.name, functionName: fn.name }));
115
+ }
116
+ else if (!(0, common_1.attributesEqual)(live.config, desiredSource)) {
117
+ logger_1.logger.info(lang_1.lang.__('UPDATING_TIMER_TRIGGER', { triggerName: timer.name, functionName: fn.name }));
118
+ if (live.id) {
119
+ try {
120
+ await client.vefaas.deleteTrigger(functionId, live.id);
121
+ }
122
+ catch (error) {
123
+ const errorCode = error?.code;
124
+ if (errorCode !== 'FunctionNotFound' && errorCode !== 'ResourceNotFound')
125
+ throw error;
126
+ }
127
+ }
128
+ }
129
+ else {
130
+ resultingInstances.push(buildVefaasTimerTriggerInstance(context, fn, timer));
131
+ continue;
132
+ }
133
+ try {
134
+ await client.vefaas.createTrigger({
135
+ functionId,
136
+ name: timer.name,
137
+ source: desiredSource,
138
+ });
139
+ }
140
+ catch (error) {
141
+ // a leftover trigger from an adopted function may already carry the name
142
+ if (!(0, alreadyExists_1.isResourceAlreadyExistsError)(error, VEFAAS_ALREADY_EXISTS_CODES))
143
+ throw error;
144
+ logger_1.logger.warn(lang_1.lang.__('TIMER_TRIGGER_ALREADY_ATTACHED', {
145
+ triggerName: timer.name,
146
+ functionName: fn.name,
147
+ }));
148
+ }
149
+ logger_1.logger.info(lang_1.lang.__('TIMER_TRIGGER_CREATED', { triggerName: timer.name, functionName: fn.name }));
150
+ resultingInstances.push(buildVefaasTimerTriggerInstance(context, fn, timer));
151
+ }
152
+ const desiredNames = new Set(desiredTimers.map((timer) => timer.name));
153
+ for (const stale of baseline.filter((entry) => !desiredNames.has(entry.name))) {
154
+ logger_1.logger.info(lang_1.lang.__('DELETING_TIMER_TRIGGER', { triggerName: stale.name, functionName: fn.name }));
155
+ if (stale.id) {
156
+ try {
157
+ await client.vefaas.deleteTrigger(functionId, stale.id);
158
+ logger_1.logger.info(lang_1.lang.__('TIMER_TRIGGER_DELETED', { triggerName: stale.name }));
159
+ }
160
+ catch (error) {
161
+ const errorCode = error?.code;
162
+ if (errorCode !== 'FunctionNotFound' && errorCode !== 'ResourceNotFound')
163
+ throw error;
164
+ logger_1.logger.warn(lang_1.lang.__('TIMER_TRIGGER_NOT_FOUND', { triggerName: stale.name }));
165
+ }
166
+ }
167
+ }
168
+ return resultingInstances;
169
+ };
15
170
  const RECOVERY_GET_FUNCTION_DELAY_MS = 1500;
16
171
  // volcengine role TRN format: trn:iam::{accountId}:role/{roleName}. Prefer the
17
172
  // stored TRN; else construct from the known accountId, else fetch it via STS.
@@ -402,11 +557,21 @@ const createResource = async (context, fn, state) => {
402
557
  if (releaseRecordId) {
403
558
  vefaasInstance.releaseRecordId = releaseRecordId;
404
559
  }
560
+ // Timer triggers bind to the function via FunctionId — reconcile after the
561
+ // function exists (fresh creates see an empty trigger list; adopted ones
562
+ // converge on leftovers).
563
+ const timerInstances = functionInfo.functionId
564
+ ? await reconcileVefaasTimerTriggers(context, fn, functionInfo.functionId, [], client)
565
+ : [];
405
566
  const resourceState = {
406
567
  mode: 'managed',
407
568
  region: context.region,
408
569
  definition,
409
- instances: [vefaasInstance, ...dependentInstances],
570
+ instances: [
571
+ vefaasInstance,
572
+ ...dependentInstances,
573
+ ...timerInstances,
574
+ ],
410
575
  status: 'ready',
411
576
  lastUpdated: new Date().toISOString(),
412
577
  };
@@ -653,6 +818,8 @@ const updateResource = async (context, fn, state, options) => {
653
818
  }
654
819
  const existingDependentInstances = existingInstances
655
820
  .filter((i) => i.type !== 'VOLCENGINE_VEFAAS_FUNCTION' &&
821
+ // timers are fully rebuilt from the reconcile result below
822
+ i.type !== TIMER_TRIGGER_INSTANCE_TYPE &&
656
823
  (!!fn.log || !i.type.startsWith('VOLCENGINE_TLS_')))
657
824
  .map((i) => {
658
825
  const { sid: existingSid, id: existingId, ...rest } = i;
@@ -671,11 +838,21 @@ const updateResource = async (context, fn, state, options) => {
671
838
  ...(dep.trn ? { trn: dep.trn } : {}),
672
839
  ...dep.attributes,
673
840
  }));
841
+ // Timer triggers reconcile against the live trigger list (issue #258);
842
+ // functionInfo above already carries the resolved function Id.
843
+ const timerInstances = functionInfo.functionId
844
+ ? await reconcileVefaasTimerTriggers(context, fn, functionInfo.functionId, existingInstances, client)
845
+ : [];
674
846
  const resourceState = {
675
847
  mode: 'managed',
676
848
  region: context.region,
677
849
  definition: desiredDefinition,
678
- instances: [vefaasInstance, ...existingDependentInstances, ...newDependentInstancesMapped],
850
+ instances: [
851
+ vefaasInstance,
852
+ ...existingDependentInstances,
853
+ ...newDependentInstancesMapped,
854
+ ...timerInstances,
855
+ ],
679
856
  status: 'ready',
680
857
  lastUpdated: new Date().toISOString(),
681
858
  };
@@ -688,6 +865,42 @@ const deleteResource = async (context, functionName, logicalId, state) => {
688
865
  const vefaasInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
689
866
  const functionId = vefaasInstance?.functionId;
690
867
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
868
+ // Delete timer triggers before the function (they hang off its FunctionId;
869
+ // si owns every timer on its function, so state-recorded ones all go).
870
+ const timerInstances = existingInstances.filter((i) => i.type === TIMER_TRIGGER_INSTANCE_TYPE);
871
+ if (functionId && timerInstances.length > 0) {
872
+ let liveTimerIds = [];
873
+ try {
874
+ liveTimerIds = await client.vefaas.listTriggers(functionId);
875
+ }
876
+ catch {
877
+ // probe failure must not block teardown — fall back to name lookup below
878
+ }
879
+ for (const timerInstance of timerInstances) {
880
+ logger_1.logger.info(lang_1.lang.__('DELETING_TIMER_TRIGGER', {
881
+ triggerName: timerInstance.id,
882
+ functionName,
883
+ }));
884
+ const liveId = liveTimerIds.find((t) => t.name === timerInstance.id)?.id ?? undefined;
885
+ if (!liveId) {
886
+ logger_1.logger.warn(lang_1.lang.__('TIMER_TRIGGER_NOT_FOUND', { triggerName: timerInstance.id }));
887
+ continue;
888
+ }
889
+ try {
890
+ await client.vefaas.deleteTrigger(functionId, liveId);
891
+ logger_1.logger.info(lang_1.lang.__('TIMER_TRIGGER_DELETED', { triggerName: timerInstance.id }));
892
+ }
893
+ catch (err) {
894
+ const errorCode = err?.code;
895
+ if (errorCode === 'FunctionNotFound' || errorCode === 'ResourceNotFound') {
896
+ logger_1.logger.warn(lang_1.lang.__('TIMER_TRIGGER_NOT_FOUND', { triggerName: timerInstance.id }));
897
+ }
898
+ else {
899
+ throw err;
900
+ }
901
+ }
902
+ }
903
+ }
691
904
  if (functionId) {
692
905
  try {
693
906
  await client.vefaas.deleteFunction(functionId);
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.functionSchema = void 0;
3
+ exports.functionSchema = exports.TIMER_TRIGGER_NAME_PATTERN = void 0;
4
4
  const templateRefSchema_1 = require("./templateRefSchema");
5
5
  const securityGroupRulePattern = '^[A-Za-z]+:\\d{1,3}(?:\\.\\d{1,3}){3}\\/\\d{1,2}:(?:ALL|\\d{1,5}(?:\\/\\d{1,5})?)$';
6
+ /**
7
+ * Timer trigger names become physical cloud trigger names (FC3 triggerName,
8
+ * SCF TriggerName, veFaaS Name) — all three accept letters/digits/`-`/`_`
9
+ * with a 60-char budget on the strictest provider (Tencent).
10
+ */
11
+ exports.TIMER_TRIGGER_NAME_PATTERN = '^[A-Za-z][A-Za-z0-9_-]{0,59}$';
6
12
  exports.functionSchema = {
7
13
  $id: 'https://serverlessinsight.geekfun.club/schemas/functionschema.json',
8
14
  type: 'object',
@@ -86,7 +92,7 @@ exports.functionSchema = {
86
92
  environment: {
87
93
  type: 'object',
88
94
  additionalProperties: {
89
- type: ['string', 'number', 'boolean'],
95
+ ...templateRefSchema_1.scalarValue,
90
96
  },
91
97
  },
92
98
  network: {
@@ -173,6 +179,23 @@ exports.functionSchema = {
173
179
  },
174
180
  },
175
181
  },
182
+ timer: {
183
+ type: 'array',
184
+ items: {
185
+ type: 'object',
186
+ required: ['name', 'cron'],
187
+ additionalProperties: false,
188
+ properties: {
189
+ name: (0, templateRefSchema_1.resolvableConstrained)({ pattern: exports.TIMER_TRIGGER_NAME_PATTERN }),
190
+ // si-cron syntax (issue #258); full grammar validation runs
191
+ // in semantic validation where errors can carry the reason
192
+ cron: (0, templateRefSchema_1.resolvableConstrained)({ pattern: '.+' }),
193
+ payload: { type: 'string' },
194
+ enable: templateRefSchema_1.resolvableBoolean,
195
+ description: { type: 'string' },
196
+ },
197
+ },
198
+ },
176
199
  },
177
200
  },
178
201
  domain: {
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.validateYaml = void 0;
6
+ exports.validateYaml = exports.IacSchemaErrors = void 0;
7
7
  const ajv_1 = __importDefault(require("ajv"));
8
8
  const common_1 = require("../common");
9
9
  const rootSchema_1 = require("./rootSchema");
@@ -45,6 +45,7 @@ class IacSchemaErrors extends Error {
45
45
  return this.schemaErrors;
46
46
  }
47
47
  }
48
+ exports.IacSchemaErrors = IacSchemaErrors;
48
49
  const ajv = new ajv_1.default({ allowUnionTypes: true, strict: false, allErrors: true });
49
50
  const validate = ajv
50
51
  .addSchema(functionSchema_1.functionSchema)
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateYaml = void 0;
3
+ exports.exportIacJsonSchema = exports.IacSchemaErrors = exports.validateYaml = void 0;
4
4
  var iacSchema_1 = require("./iacSchema");
5
5
  Object.defineProperty(exports, "validateYaml", { enumerable: true, get: function () { return iacSchema_1.validateYaml; } });
6
+ Object.defineProperty(exports, "IacSchemaErrors", { enumerable: true, get: function () { return iacSchema_1.IacSchemaErrors; } });
7
+ var schemaExport_1 = require("./schemaExport");
8
+ Object.defineProperty(exports, "exportIacJsonSchema", { enumerable: true, get: function () { return schemaExport_1.exportIacJsonSchema; } });
@@ -9,14 +9,18 @@ const FUNCTION_NAME_MAX_LENGTH = {
9
9
  };
10
10
  const functionNameLimitBranch = (provider, maxLength) => ({
11
11
  if: {
12
- properties: { provider: { properties: { name: { const: provider } }, required: ['name'] } },
12
+ properties: {
13
+ provider: { type: 'object', properties: { name: { const: provider } }, required: ['name'] },
14
+ },
13
15
  required: ['provider'],
14
16
  },
15
17
  then: {
16
18
  properties: {
17
19
  functions: {
20
+ type: 'object',
18
21
  patternProperties: {
19
22
  '.*': {
23
+ type: 'object',
20
24
  properties: {
21
25
  // Whole-value template references bypass the literal limit.
22
26
  name: { anyOf: [{ type: 'string', maxLength }, templateRefSchema_1.templateRefSchema] },
@@ -31,13 +35,26 @@ exports.rootSchema = {
31
35
  $id: 'https://serverlessinsight.geekfun.club/schemas/schema.json',
32
36
  type: 'object',
33
37
  properties: {
34
- version: { type: 'string', enum: ['0.0.0', '0.0.1', '0.1.0'] },
35
- app: { type: 'string', pattern: '^[a-z][a-z0-9-]*$' },
38
+ version: {
39
+ type: 'string',
40
+ enum: ['0.0.0', '0.0.1', '0.1.0'],
41
+ description: 'ServerlessInsight IaC document version.',
42
+ },
43
+ app: {
44
+ type: 'string',
45
+ pattern: '^[a-z][a-z0-9-]*$',
46
+ description: 'Application name — the top-level grouping of services. Lowercase letters, digits and hyphens, starting with a letter.',
47
+ },
36
48
  provider: {
37
49
  type: 'object',
50
+ description: 'Target cloud provider and deployment region.',
38
51
  properties: {
39
- name: { type: 'string', enum: ['huawei', 'aliyun', 'tencent', 'aws', 'volcengine'] },
40
- region: { type: 'string' },
52
+ name: {
53
+ type: 'string',
54
+ enum: ['huawei', 'aliyun', 'tencent', 'aws', 'volcengine'],
55
+ description: 'Cloud provider identifier.',
56
+ },
57
+ region: { type: 'string', description: 'Deployment region, e.g. cn-hangzhou.' },
41
58
  },
42
59
  required: ['name', 'region'],
43
60
  allOf: [
@@ -86,58 +103,70 @@ exports.rootSchema = {
86
103
  },
87
104
  ],
88
105
  },
89
- service: { type: 'string', pattern: '^[a-z][a-z0-9-]*$' },
106
+ service: {
107
+ type: 'string',
108
+ pattern: '^[a-z][a-z0-9-]*$',
109
+ description: 'Service name inside the application. Lowercase letters, digits and hyphens, starting with a letter.',
110
+ },
90
111
  // Target Console org (organizations.slug). Optional — required only when an
91
112
  // explicit SaaS state backend is declared (allOf branch below); with
92
113
  // LOCAL/BUCKET_STORE backends it is allowed but inert (decision D-6).
93
- org: { type: 'string', pattern: '^[a-z0-9][a-z0-9-]*$' },
114
+ org: {
115
+ type: 'string',
116
+ pattern: '^[a-z0-9][a-z0-9-]*$',
117
+ description: 'Target ServerlessInsight Console organization slug (required for SaaS state backend).',
118
+ },
94
119
  vars: {
95
120
  type: 'object',
96
- additionalProperties: {
97
- type: ['string', 'number', 'boolean'],
98
- },
121
+ description: 'Reusable variables referenceable as ${vars.<key>} throughout the document.',
122
+ additionalProperties: templateRefSchema_1.scalarValue,
99
123
  },
100
124
  stages: {
101
125
  type: 'object',
126
+ description: 'Per-stage variables referenceable as ${stages.<key>}, keyed by stage name.',
102
127
  patternProperties: {
103
128
  '.*': {
104
129
  type: 'object',
105
- additionalProperties: {
106
- type: ['string', 'number', 'boolean'],
107
- },
130
+ additionalProperties: templateRefSchema_1.scalarValue,
108
131
  },
109
132
  },
110
133
  },
111
134
  tags: {
112
135
  type: 'object',
113
- additionalProperties: {
114
- type: ['string', 'number', 'boolean'],
115
- },
136
+ description: 'Tags applied to every managed cloud resource.',
137
+ additionalProperties: templateRefSchema_1.scalarValue,
116
138
  },
117
139
  functions: {
140
+ description: 'Serverless function definitions keyed by logical id.',
118
141
  $ref: 'https://serverlessinsight.geekfun.club/schemas/functionschema.json',
119
142
  },
120
143
  events: {
144
+ description: 'Event definitions (e.g. API_GATEWAY) keyed by logical id.',
121
145
  $ref: 'https://serverlessinsight.geekfun.club/schemas/eventschema.json',
122
146
  },
123
147
  databases: {
148
+ description: 'Serverless database definitions keyed by logical id.',
124
149
  $ref: 'https://serverlessinsight.geekfun.club/schemas/databaseschema.json',
125
150
  },
126
151
  buckets: {
152
+ description: 'Object-storage bucket definitions keyed by logical id.',
127
153
  $ref: 'https://serverlessinsight.geekfun.club/schemas/bucketschema.json',
128
154
  },
129
155
  tables: {
156
+ description: 'Tablestore table definitions keyed by logical id.',
130
157
  $ref: 'https://serverlessinsight.geekfun.club/schemas/tableschema.json',
131
158
  },
132
159
  backend: {
133
160
  type: 'object',
161
+ description: 'Remote state backend configuration (defaults to the SaaS backend).',
134
162
  properties: {
135
163
  state_manager: {
136
164
  type: 'object',
165
+ description: 'State storage: LOCAL directory, BUCKET_STORE, or the SaaS Console.',
137
166
  properties: {
138
167
  type: { type: 'string', enum: ['LOCAL', 'BUCKET_STORE', 'SAAS'] },
139
- bucket: { type: 'string' },
140
- key: { type: 'string' },
168
+ bucket: { type: 'string', description: 'State bucket name (BUCKET_STORE only).' },
169
+ key: { type: 'string', description: 'State object key (BUCKET_STORE only).' },
141
170
  },
142
171
  required: ['type'],
143
172
  additionalProperties: false,
@@ -157,8 +186,10 @@ exports.rootSchema = {
157
186
  if: {
158
187
  properties: {
159
188
  backend: {
189
+ type: 'object',
160
190
  properties: {
161
191
  state_manager: {
192
+ type: 'object',
162
193
  properties: { type: { const: 'SAAS' } },
163
194
  required: ['type'],
164
195
  },
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exportIacJsonSchema = void 0;
4
+ const rootSchema_1 = require("./rootSchema");
5
+ const functionSchema_1 = require("./functionSchema");
6
+ const eventSchema_1 = require("./eventSchema");
7
+ const databaseSchema_1 = require("./databaseSchema");
8
+ const bucketSchema_1 = require("./bucketSchema");
9
+ const tableschema_1 = require("./tableschema");
10
+ /**
11
+ * Issue #250: export the schemas Ajv compiles against as one self-contained,
12
+ * standard JSON Schema document. The compiled stack uses draft-07 style with
13
+ * external `$ref`s by `$id`; the export bundles every referenced schema under
14
+ * `definitions` and rewrites the refs to local pointers, so the artifact
15
+ * loads in a bare Ajv (or any draft-07 validator) with zero setup — usable as
16
+ * an anchor for structured YAML generation, editor completion, and
17
+ * `si validate` loops.
18
+ */
19
+ const REF_TARGETS = {
20
+ 'https://serverlessinsight.geekfun.club/schemas/functionschema.json': 'functions',
21
+ 'https://serverlessinsight.geekfun.club/schemas/eventschema.json': 'events',
22
+ 'https://serverlessinsight.geekfun.club/schemas/databaseschema.json': 'databases',
23
+ 'https://serverlessinsight.geekfun.club/schemas/bucketschema.json': 'buckets',
24
+ 'https://serverlessinsight.geekfun.club/schemas/tableschema.json': 'tables',
25
+ };
26
+ const rewriteRefs = (node) => {
27
+ if (Array.isArray(node)) {
28
+ node.forEach(rewriteRefs);
29
+ return;
30
+ }
31
+ if (node && typeof node === 'object') {
32
+ Object.entries(node).forEach(([key, value]) => {
33
+ if (key === '$ref' && typeof value === 'string' && REF_TARGETS[value]) {
34
+ node['$ref'] = `#/definitions/${REF_TARGETS[value]}`;
35
+ return;
36
+ }
37
+ rewriteRefs(value);
38
+ });
39
+ }
40
+ };
41
+ const exportIacJsonSchema = () => {
42
+ const bundled = {
43
+ ...rootSchema_1.rootSchema,
44
+ $schema: 'http://json-schema.org/draft-07/schema#',
45
+ title: 'ServerlessInsight IaC configuration',
46
+ description: 'JSON Schema for ServerlessInsight serverless IaC YAML files. Use it to generate or ' +
47
+ 'complete `serverless-insight.yml` documents; validate results with `si validate`.',
48
+ definitions: {
49
+ functions: functionSchema_1.functionSchema,
50
+ events: eventSchema_1.eventSchema,
51
+ databases: databaseSchema_1.databaseSchema,
52
+ buckets: bucketSchema_1.bucketSchema,
53
+ tables: tableschema_1.tableSchema,
54
+ },
55
+ };
56
+ const plain = JSON.parse(JSON.stringify(bundled));
57
+ rewriteRefs(plain);
58
+ return plain;
59
+ };
60
+ exports.exportIacJsonSchema = exportIacJsonSchema;
@@ -7,8 +7,11 @@ const logger_1 = require("../common/logger");
7
7
  // drag stateManager/lockManager/fs surfaces into the validator graph and
8
8
  // recreate an import cycle with src/parser. These helpers are pure.
9
9
  const providerNames_1 = require("../common/providerNames");
10
+ const siCron_1 = require("../common/siCron");
10
11
  const FUNCTION_BACKEND_PATTERN = /^\$\{functions\.([\w.]+)\}$/;
11
12
  const TEMPLATE_REF_PATTERN = /^\$\{[^}]+\}$/;
13
+ /** Tencent SCF allows at most 10 same-type triggers per function (#212 matrix). */
14
+ const TENCENT_TIMER_TRIGGER_LIMIT = 10;
12
15
  /**
13
16
  * Stage is intentionally empty here: it is identical for every generated name
14
17
  * inside one validation run, so collision detection is unaffected while avoiding
@@ -52,6 +55,82 @@ const validateSemantics = (iacJson) => {
52
55
  message: lang_1.lang.__('SEMANTIC_FUNCTION_SOURCE_REQUIRED', { fnKey }),
53
56
  });
54
57
  }
58
+ // Timer triggers (issue #258): si-cron validity + provider capability
59
+ // matrix surface here so `si validate` fails before any deploy runs.
60
+ const triggers = fn.triggers;
61
+ const timers = Array.isArray(triggers?.timer)
62
+ ? triggers?.timer
63
+ : [];
64
+ const seenTimerNames = new Set();
65
+ timers.forEach((timer, index) => {
66
+ const timerPath = `${instancePath}/triggers/timer/${index}`;
67
+ const name = typeof timer.name === 'string' ? timer.name : '';
68
+ const cron = typeof timer.cron === 'string' ? timer.cron : '';
69
+ if (name.length === 0) {
70
+ errors.push({
71
+ instancePath: timerPath,
72
+ schemaPath: '#/semantic/timerNameRequired',
73
+ keyword: 'timerNameRequired',
74
+ params: {},
75
+ message: lang_1.lang.__('TIMER_TRIGGER_NAME_REQUIRED', { functionName: fnKey }),
76
+ });
77
+ }
78
+ else if (seenTimerNames.has(name)) {
79
+ errors.push({
80
+ instancePath: timerPath,
81
+ schemaPath: '#/semantic/duplicateTimerName',
82
+ keyword: 'duplicateTimerName',
83
+ params: {},
84
+ message: lang_1.lang.__('TIMER_TRIGGER_DUPLICATE_NAME', { name, functionName: fnKey }),
85
+ });
86
+ }
87
+ else {
88
+ seenTimerNames.add(name);
89
+ }
90
+ if (cron.length === 0) {
91
+ errors.push({
92
+ instancePath: timerPath,
93
+ schemaPath: '#/semantic/timerCronRequired',
94
+ keyword: 'timerCronRequired',
95
+ params: {},
96
+ message: lang_1.lang.__('TIMER_TRIGGER_CRON_REQUIRED', { name: name || fnKey }),
97
+ });
98
+ return;
99
+ }
100
+ // template refs resolve at runtime — grammar is checked post-resolution
101
+ if (TEMPLATE_REF_PATTERN.test(cron)) {
102
+ return;
103
+ }
104
+ const cronProblem = (0, siCron_1.checkSiCronForProvider)(cron, providerName);
105
+ if (cronProblem) {
106
+ errors.push({
107
+ instancePath: timerPath,
108
+ schemaPath: '#/semantic/invalidSiCron',
109
+ keyword: 'invalidSiCron',
110
+ params: {},
111
+ message: lang_1.lang.__('SEMANTIC_TIMER_CRON_INVALID', {
112
+ name: name || fnKey,
113
+ functionName: fnKey,
114
+ cron,
115
+ reason: cronProblem,
116
+ }),
117
+ });
118
+ }
119
+ });
120
+ if (providerName === 'tencent' && timers.length > TENCENT_TIMER_TRIGGER_LIMIT) {
121
+ errors.push({
122
+ instancePath: `${instancePath}/triggers/timer`,
123
+ schemaPath: '#/semantic/timerTriggerLimit',
124
+ keyword: 'timerTriggerLimit',
125
+ params: {},
126
+ message: lang_1.lang.__('TIMER_TRIGGER_LIMIT_EXCEEDED', {
127
+ functionName: fnKey,
128
+ count: String(timers.length),
129
+ provider: providerName,
130
+ max: String(TENCENT_TIMER_TRIGGER_LIMIT),
131
+ }),
132
+ });
133
+ }
55
134
  });
56
135
  Object.entries(events).forEach(([eventKey, rawEvent]) => {
57
136
  const triggers = Array.isArray(rawEvent.triggers)
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BUCKET_NAME_PATTERN = exports.HOST_NAME_PATTERN = exports.resolvableConstrained = exports.resolvableEnum = exports.resolvableBoolean = exports.resolvableInteger = exports.resolvableNumber = exports.templateRefSchema = void 0;
3
+ exports.BUCKET_NAME_PATTERN = exports.HOST_NAME_PATTERN = exports.resolvableConstrained = exports.resolvableEnum = exports.resolvableBoolean = exports.resolvableInteger = exports.resolvableNumber = exports.scalarValue = exports.templateRefSchema = void 0;
4
4
  // Template reference pattern that matches ${vars.xxx}, ${stages.xxx}, ${ctx.xxx}, ${functions.xxx}, ${certificates.xxx}
5
5
  // Note: ${functions.xxx} and ${certificates.xxx} references are kept as strings and resolved by the deployment engine
6
6
  // Only ${vars.xxx}, ${stages.xxx}, and ${ctx.xxx} are resolved at parse time
@@ -14,6 +14,14 @@ exports.templateRefSchema = {
14
14
  const withTemplateRef = (schema) => ({
15
15
  oneOf: [schema, exports.templateRefSchema],
16
16
  });
17
+ /**
18
+ * Scalar map values (string | number | boolean). Expressed as `anyOf` rather
19
+ * than a union `type` array so the schema stays clean under Ajv strict mode
20
+ * while remaining standard draft-07 (issue #250 schema export).
21
+ */
22
+ exports.scalarValue = {
23
+ anyOf: [{ type: 'string' }, { type: 'number' }, { type: 'boolean' }],
24
+ };
17
25
  // Common resolvable type schemas
18
26
  exports.resolvableNumber = withTemplateRef({ type: 'number' });
19
27
  exports.resolvableInteger = withTemplateRef({ type: 'integer' });