@geek-fun/serverlessinsight 0.9.2 → 0.9.4

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 (105) 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 +4 -8
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +3 -8
  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 +28 -5
  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 +20 -5
  11. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  12. package/AGENTS.md +10 -0
  13. package/CHANGELOG.md +62 -0
  14. package/README.md +256 -175
  15. package/README.zh-CN.md +249 -159
  16. package/dist/package.json +22 -19
  17. package/dist/src/commands/index.js +21 -52
  18. package/dist/src/commands/local.js +16 -3
  19. package/dist/src/commands/plan.js +35 -4
  20. package/dist/src/common/aliyunClient/apigwOperations.js +48 -9
  21. package/dist/src/common/aliyunClient/fc3Operations.js +7 -1
  22. package/dist/src/common/aliyunClient/ossOperations.js +214 -221
  23. package/dist/src/common/bucketPolicy.js +63 -0
  24. package/dist/src/common/domainUtils.js +4 -1
  25. package/dist/src/common/functionDefinition.js +25 -0
  26. package/dist/src/common/index.js +4 -0
  27. package/dist/src/common/jsonOutput.js +6 -1
  28. package/dist/src/common/nameBuilder.js +3 -1
  29. package/dist/src/common/planCapabilities.js +119 -0
  30. package/dist/src/common/planCompare.js +119 -66
  31. package/dist/src/common/planFormatter.js +22 -14
  32. package/dist/src/common/planRedaction.js +26 -0
  33. package/dist/src/common/refreshPlanner.js +66 -21
  34. package/dist/src/common/tencentClient/cosOperations.js +326 -322
  35. package/dist/src/common/tencentClient/scfOperations.js +9 -2
  36. package/dist/src/common/tencentClient/tdsqlcOperations.js +6 -11
  37. package/dist/src/common/triggerMapper.js +16 -1
  38. package/dist/src/common/volcengineClient/apigwOperations.js +82 -0
  39. package/dist/src/common/volcengineClient/iamOperations.js +27 -3
  40. package/dist/src/common/volcengineClient/tosOperations.js +62 -56
  41. package/dist/src/lang/en.js +33 -8
  42. package/dist/src/lang/index.js +28 -14
  43. package/dist/src/lang/zh-CN.js +33 -8
  44. package/dist/src/parser/eventParser.js +1 -0
  45. package/dist/src/parser/functionParser.js +1 -1
  46. package/dist/src/stack/aliyunStack/apigwDomainPlan.js +82 -0
  47. package/dist/src/stack/aliyunStack/apigwExecutor.js +4 -1
  48. package/dist/src/stack/aliyunStack/apigwPlanner.js +165 -25
  49. package/dist/src/stack/aliyunStack/apigwResource.js +172 -126
  50. package/dist/src/stack/aliyunStack/apigwTypes.js +3 -7
  51. package/dist/src/stack/aliyunStack/deployer.js +2 -0
  52. package/dist/src/stack/aliyunStack/esServerlessTypes.js +8 -4
  53. package/dist/src/stack/aliyunStack/fc3Executor.js +7 -3
  54. package/dist/src/stack/aliyunStack/fc3Planner.js +124 -155
  55. package/dist/src/stack/aliyunStack/fc3Resource.js +48 -52
  56. package/dist/src/stack/aliyunStack/fc3Types.js +30 -16
  57. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  58. package/dist/src/stack/aliyunStack/ossResource.js +113 -102
  59. package/dist/src/stack/aliyunStack/ossTypes.js +20 -20
  60. package/dist/src/stack/localStack/aliyunFc.js +1 -6
  61. package/dist/src/stack/localStack/event.js +31 -60
  62. package/dist/src/stack/localStack/function.js +24 -65
  63. package/dist/src/stack/localStack/functionRunner.js +10 -2
  64. package/dist/src/stack/localStack/httpAdapter.js +54 -0
  65. package/dist/src/stack/localStack/httpError.js +5 -0
  66. package/dist/src/stack/localStack/legacyLambda.js +26 -0
  67. package/dist/src/stack/localStack/localContext.js +29 -0
  68. package/dist/src/stack/localStack/localRoute.js +12 -0
  69. package/dist/src/stack/localStack/localRuntimes.js +22 -0
  70. package/dist/src/stack/localStack/localServer.js +8 -3
  71. package/dist/src/stack/localStack/requestBody.js +24 -0
  72. package/dist/src/stack/localStack/requestId.js +18 -0
  73. package/dist/src/stack/localStack/tencent.js +147 -0
  74. package/dist/src/stack/localStack/timer.js +23 -2
  75. package/dist/src/stack/localStack/volcengine.js +68 -0
  76. package/dist/src/stack/scfStack/cosPlanner.js +9 -14
  77. package/dist/src/stack/scfStack/cosResource.js +42 -50
  78. package/dist/src/stack/scfStack/cosTypes.js +19 -14
  79. package/dist/src/stack/scfStack/deployer.js +2 -0
  80. package/dist/src/stack/scfStack/scfExecutor.js +7 -3
  81. package/dist/src/stack/scfStack/scfHttpTrigger.js +106 -0
  82. package/dist/src/stack/scfStack/scfPlanner.js +67 -16
  83. package/dist/src/stack/scfStack/scfResource.js +170 -321
  84. package/dist/src/stack/scfStack/scfTypes.js +4 -3
  85. package/dist/src/stack/scfStack/tdsqlcPlanner.js +10 -13
  86. package/dist/src/stack/volcengineStack/apigwDomains.js +64 -0
  87. package/dist/src/stack/volcengineStack/apigwPlanner.js +71 -15
  88. package/dist/src/stack/volcengineStack/apigwResource.js +60 -24
  89. package/dist/src/stack/volcengineStack/apigwTypes.js +5 -1
  90. package/dist/src/stack/volcengineStack/deployer.js +6 -0
  91. package/dist/src/stack/volcengineStack/tosPlanner.js +8 -13
  92. package/dist/src/stack/volcengineStack/tosResource.js +22 -35
  93. package/dist/src/stack/volcengineStack/tosTypes.js +5 -8
  94. package/dist/src/stack/volcengineStack/vefaasPlanner.js +142 -49
  95. package/dist/src/stack/volcengineStack/vefaasResource.js +17 -12
  96. package/dist/src/stack/volcengineStack/vefaasTypes.js +6 -3
  97. package/dist/tsconfig.tsbuildinfo +1 -1
  98. package/package.json +22 -19
  99. package/release-notes.md +53 -0
  100. package/samples/README_TENCENT_COS.md +3 -3
  101. package/samples/README_TENCENT_SCF.md +3 -3
  102. package/samples/tencent-local/index.js +13 -0
  103. package/samples/tencent-local/serverlessinsight.yml +23 -0
  104. package/samples/volcengine-local/index.js +13 -0
  105. package/samples/volcengine-local/serverlessinsight.yml +28 -0
@@ -1,22 +1,31 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.eventsHandler = void 0;
7
4
  const types_1 = require("../../types");
8
5
  const lodash_1 = require("lodash");
6
+ const localStack_1 = require("../../types/localStack");
9
7
  const common_1 = require("../../common");
10
8
  const function_1 = require("./function");
11
9
  const aliyunFc_1 = require("./aliyunFc");
12
- const functionRunner_1 = require("./functionRunner");
13
- const node_fs_1 = __importDefault(require("node:fs"));
14
- const utils_1 = require("./utils");
10
+ const requestId_1 = require("./requestId");
15
11
  const lang_1 = require("../../lang");
16
- const matchTrigger = (req, trigger) => {
12
+ /**
13
+ * Route matching shared by every provider; the `exact` mode mirrors how the
14
+ * provider actually deploys the route:
15
+ * - Aliyun: gateway routes support `[param]` segments and a trailing `*`
16
+ * prefix wildcard, so paths are compared segment-wise after trimming
17
+ * slashes.
18
+ * - Volcengine: si creates API Gateway routes with `MatchType: 'Exact'`
19
+ * (see `createRoute` in volcengineClient/apigwOperations.ts), so the path
20
+ * is compared byte-for-byte and `[param]` / `*` carry no wildcard meaning.
21
+ */
22
+ const matchTrigger = (req, trigger, options = { exact: false }) => {
17
23
  if (trigger.method !== 'ANY' && req.method !== trigger.method) {
18
24
  return false;
19
25
  }
26
+ if (options.exact) {
27
+ return trigger.path === req.path;
28
+ }
20
29
  const normalize = (s) => s.replace(/^\/+|\/+$/g, '');
21
30
  const [pathSegments, triggerSegments] = [
22
31
  normalize(req.path).split('/'),
@@ -37,22 +46,33 @@ const matchTrigger = (req, trigger) => {
37
46
  };
38
47
  const servEvent = async (req, parsed, iac) => {
39
48
  const startTime = new Date();
40
- const requestId = (0, aliyunFc_1.generateRequestId)();
49
+ const requestId = (0, requestId_1.generateProviderRequestId)(iac.provider.name);
41
50
  const sourceIp = req.socket?.remoteAddress || '127.0.0.1';
42
51
  const isAliyun = iac.provider.name === common_1.ProviderEnum.ALIYUN;
43
- const event = iac.events?.find((event) => event.type === types_1.EventTypes.API_GATEWAY && event.key === parsed.identifier);
52
+ const event = iac.events?.find((event) => event.key === parsed.identifier &&
53
+ (event.type === types_1.EventTypes.API_GATEWAY || iac.provider.name === common_1.ProviderEnum.VOLCENGINE));
44
54
  if ((0, lodash_1.isEmpty)(event)) {
45
55
  return {
46
56
  statusCode: 404,
47
57
  body: { error: 'API Gateway event not found', event: parsed.identifier },
48
58
  };
49
59
  }
60
+ if (event.type !== types_1.EventTypes.API_GATEWAY) {
61
+ return { statusCode: 501, body: { error: lang_1.lang.__('LOCAL_EVENT_TYPE_UNSUPPORTED') } };
62
+ }
63
+ // si deploys Tencent HTTP access as a function-owned function URL, not as an
64
+ // API Gateway service, so a gateway event has no SCF-native local equivalent.
65
+ if (iac.provider.name === common_1.ProviderEnum.TENCENT) {
66
+ return { statusCode: 501, body: { error: lang_1.lang.__('LOCAL_SCF_EVENT_UNSUPPORTED') } };
67
+ }
50
68
  common_1.logger.info(lang_1.lang.__('EVENT_TRIGGER', {
51
69
  triggers: JSON.stringify(event.triggers),
52
70
  method: req.method || '',
53
71
  url: req.url || '',
54
72
  }));
55
- const matchedTrigger = event.triggers.find((trigger) => matchTrigger({ method: parsed.method, path: parsed.url }, trigger));
73
+ const matchedTrigger = event.triggers.find((trigger) => matchTrigger({ method: parsed.method, path: parsed.url }, trigger, {
74
+ exact: iac.provider.name === common_1.ProviderEnum.VOLCENGINE,
75
+ }));
56
76
  if (!matchedTrigger) {
57
77
  const endTime = new Date();
58
78
  if (isAliyun) {
@@ -72,56 +92,7 @@ const servEvent = async (req, parsed, iac) => {
72
92
  body: { error: 'Backend definition missing', backend: matchedTrigger.backend },
73
93
  };
74
94
  }
75
- // For Aliyun, handle the function execution with proper event transformation
76
- if (isAliyun && backendDef.code) {
77
- let tempDir = null;
78
- try {
79
- const { event: aliyunEvent } = await (0, aliyunFc_1.transformToAliyunEvent)(req, parsed.url, parsed.query);
80
- const { codeDir, tempDir: resolvedTempDir } = await (0, utils_1.resolveCodeDir)(backendDef.code.path);
81
- tempDir = resolvedTempDir;
82
- const funOptions = {
83
- codeDir,
84
- functionKey: backendDef.key,
85
- handler: backendDef.code.handler,
86
- servicePath: '',
87
- timeout: (backendDef.timeout ?? 3) * 1000,
88
- };
89
- const aliyunContext = (0, aliyunFc_1.createAliyunContextSerializable)(iac, backendDef.name, backendDef.code.handler, backendDef.memory ?? 128, backendDef.timeout ?? 3, requestId);
90
- const env = {
91
- ...backendDef.environment,
92
- };
93
- common_1.logger.debug(lang_1.lang.__('INVOKING_FC_FUNCTION_WITH_ALIYUN_EVENT'));
94
- const result = await (0, functionRunner_1.invokeFunction)(funOptions, env, aliyunEvent, aliyunContext);
95
- const endTime = new Date();
96
- const transformed = (0, aliyunFc_1.transformFCResponse)(result);
97
- // Log API Gateway request
98
- (0, aliyunFc_1.logApiGatewayRequest)(requestId, parsed.url, transformed.statusCode, startTime, endTime, sourceIp);
99
- return {
100
- statusCode: transformed.statusCode,
101
- headers: transformed.headers,
102
- body: transformed.body,
103
- };
104
- }
105
- catch (error) {
106
- const endTime = new Date();
107
- (0, aliyunFc_1.logApiGatewayRequest)(requestId, parsed.url, 500, startTime, endTime, sourceIp);
108
- common_1.logger.error(lang_1.lang.__('FUNCTION_EXECUTION_ERROR', { error: String(error) }));
109
- return {
110
- statusCode: 500,
111
- body: {
112
- error: 'Function execution failed',
113
- message: error instanceof Error ? error.message : String(error),
114
- },
115
- };
116
- }
117
- finally {
118
- if (tempDir && node_fs_1.default.existsSync(tempDir)) {
119
- node_fs_1.default.rmSync(tempDir, { recursive: true, force: true });
120
- }
121
- }
122
- }
123
- // For non-Aliyun or when using functionsHandler
124
- const result = await (0, function_1.functionsHandler)(req, { ...parsed, identifier: backendDef?.key }, iac);
95
+ const result = await (0, function_1.functionsHandler)(req, { ...parsed, kind: localStack_1.RouteKind.SI_EVENTS, identifier: backendDef.key }, iac, requestId);
125
96
  const endTime = new Date();
126
97
  if (isAliyun) {
127
98
  (0, aliyunFc_1.logApiGatewayRequest)(requestId, parsed.url, result.statusCode, startTime, endTime, sourceIp);
@@ -4,13 +4,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.functionsHandler = void 0;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_util_1 = require("node:util");
7
9
  const common_1 = require("../../common");
8
10
  const functionRunner_1 = require("./functionRunner");
9
- const node_fs_1 = __importDefault(require("node:fs"));
10
- const aliyunFc_1 = require("./aliyunFc");
11
+ const requestId_1 = require("./requestId");
12
+ const httpAdapter_1 = require("./httpAdapter");
11
13
  const utils_1 = require("./utils");
12
14
  const lang_1 = require("../../lang");
13
- const functionsHandler = async (req, parsed, iac) => {
15
+ const functionsHandler = async (req, parsed, iac, requestId = (0, requestId_1.generateProviderRequestId)(iac.provider.name)) => {
14
16
  common_1.logger.info(lang_1.lang.__('FUNCTION_REQUEST_RECEIVED', {
15
17
  method: req.method || '',
16
18
  identifier: parsed.identifier ?? '/',
@@ -19,17 +21,19 @@ const functionsHandler = async (req, parsed, iac) => {
19
21
  if (!fcDef) {
20
22
  return {
21
23
  statusCode: 404,
22
- body: { error: 'Function not found', functionKey: parsed.identifier },
23
- };
24
- }
25
- if (!fcDef.code) {
26
- return {
27
- statusCode: 400,
28
- body: { error: 'Function code configuration not found', functionKey: fcDef.key },
24
+ body: { error: lang_1.lang.__('LOCAL_FUNCTION_NOT_FOUND'), functionKey: parsed.identifier },
29
25
  };
30
26
  }
31
27
  let tempDir = null;
32
28
  try {
29
+ const adapter = (0, httpAdapter_1.getLocalHttpAdapter)(iac.provider.name);
30
+ adapter.validate(fcDef);
31
+ if (!fcDef.code) {
32
+ return {
33
+ statusCode: 400,
34
+ body: { error: lang_1.lang.__('LOCAL_FUNCTION_CODE_MISSING'), functionKey: fcDef.key },
35
+ };
36
+ }
33
37
  const { codeDir, tempDir: resolvedTempDir } = await (0, utils_1.resolveCodeDir)(fcDef.code.path);
34
38
  tempDir = resolvedTempDir;
35
39
  const funOptions = {
@@ -39,69 +43,24 @@ const functionsHandler = async (req, parsed, iac) => {
39
43
  servicePath: '',
40
44
  timeout: (fcDef.timeout ?? 3) * 1000,
41
45
  };
42
- // Check if provider is Aliyun to use Aliyun FC format
43
- const isAliyun = iac.provider.name === common_1.ProviderEnum.ALIYUN;
44
- let event;
45
- let fcContext;
46
- let env;
47
- if (isAliyun) {
48
- // Aliyun FC format: event is a Buffer containing JSON
49
- const requestId = (0, aliyunFc_1.generateRequestId)();
50
- const { event: aliyunEvent } = await (0, aliyunFc_1.transformToAliyunEvent)(req, parsed.url, parsed.query);
51
- event = aliyunEvent;
52
- // Use serializable context for worker thread (logger will be added inside worker)
53
- fcContext = (0, aliyunFc_1.createAliyunContextSerializable)(iac, fcDef.name, fcDef.code.handler, fcDef.memory ?? 128, fcDef.timeout ?? 3, requestId);
54
- env = {
55
- ...fcDef.environment,
56
- };
57
- }
58
- else {
59
- // AWS Lambda format (default)
60
- const rawBody = await (0, common_1.readRequestBody)(req);
61
- event = rawBody ? JSON.parse(rawBody) : {};
62
- env = {
63
- ...fcDef.environment,
64
- AWS_REGION: iac.provider.region || 'us-east-1',
65
- FUNCTION_NAME: fcDef.name,
66
- FUNCTION_MEMORY_SIZE: String(fcDef.memory),
67
- FUNCTION_TIMEOUT: String(fcDef.timeout),
68
- };
69
- fcContext = {
70
- functionName: fcDef.name,
71
- functionVersion: '$LATEST',
72
- memoryLimitInMB: fcDef.memory,
73
- logGroupName: `/aws/lambda/${fcDef.name}`,
74
- logStreamName: `${new Date().toISOString().split('T')[0]}/[$LATEST]${Math.random().toString(36).substring(7)}`,
75
- invokedFunctionArn: `arn:aws:lambda:${iac.provider.region}:000000000000:function:${fcDef.name}`,
76
- awsRequestId: Math.random().toString(36).substring(2, 15),
77
- };
78
- }
46
+ const { event, context, env } = await adapter.buildInvocation(req, parsed, iac, fcDef, requestId);
79
47
  common_1.logger.debug(lang_1.lang.__('INVOKING_WORKER_WITH_EVENT_TYPE', {
80
- eventType: isAliyun ? 'Buffer' : 'Object',
48
+ eventType: Buffer.isBuffer(event) ? 'Buffer' : 'Object',
81
49
  }));
82
50
  common_1.logger.debug(lang_1.lang.__('WORKER_CODE_DIR', { codeDir, handler: funOptions.handler }));
83
- const result = await (0, functionRunner_1.invokeFunction)(funOptions, env, event, fcContext);
84
- common_1.logger.info(lang_1.lang.__('FUNCTION_EXECUTION_RESULT', { result: JSON.stringify(result) }));
85
- // For Aliyun, transform FC response to HTTP response if needed
86
- if (isAliyun && result) {
87
- const transformed = (0, aliyunFc_1.transformFCResponse)(result);
88
- return {
89
- statusCode: transformed.statusCode,
90
- headers: transformed.headers,
91
- body: transformed.body,
92
- };
93
- }
94
- return {
95
- statusCode: 200,
96
- body: result,
97
- };
51
+ const result = await (0, functionRunner_1.invokeFunction)(funOptions, env, event, context);
52
+ common_1.logger.info(lang_1.lang.__('FUNCTION_EXECUTION_RESULT', { result: (0, node_util_1.inspect)(result) }));
53
+ return adapter.transformResponse(result, parsed.kind);
98
54
  }
99
55
  catch (error) {
100
56
  common_1.logger.error(lang_1.lang.__('FUNCTION_EXECUTION_ERROR', { error: String(error) }));
57
+ const statusCode = error instanceof Error && 'statusCode' in error && typeof error.statusCode === 'number'
58
+ ? error.statusCode
59
+ : 500;
101
60
  return {
102
- statusCode: 500,
61
+ statusCode,
103
62
  body: {
104
- error: 'Function execution failed',
63
+ error: lang_1.lang.__('LOCAL_FUNCTION_EXECUTION_FAILED'),
105
64
  message: error instanceof Error ? error.message : String(error),
106
65
  },
107
66
  };
@@ -37,6 +37,7 @@ exports.invokeFunction = exports.runFunction = void 0;
37
37
  const node_fs_1 = require("node:fs");
38
38
  const node_path_1 = __importStar(require("node:path"));
39
39
  const node_url_1 = require("node:url");
40
+ const node_util_1 = require("node:util");
40
41
  const lang_1 = require("../../lang");
41
42
  const node_worker_threads_1 = require("node:worker_threads");
42
43
  // ============================================================================
@@ -197,7 +198,7 @@ const createMessageHandler = (port, resolve, reject) => {
197
198
  return;
198
199
  resolved = true;
199
200
  port.close();
200
- return value instanceof Error ? reject(value) : resolve(value);
201
+ return node_util_1.types.isNativeError(value) ? reject(value) : resolve(value);
201
202
  };
202
203
  const handleError = (err) => {
203
204
  if (resolved)
@@ -264,10 +265,17 @@ const runFunction = (funOptions, env) => {
264
265
  exports.runFunction = runFunction;
265
266
  const invokeFunction = async (funOptions, env, event, context) => {
266
267
  const runner = (0, exports.runFunction)(funOptions, env);
268
+ let timeoutId;
269
+ const deadline = new Promise((_resolve, reject) => {
270
+ timeoutId = setTimeout(() => {
271
+ reject(new Error(lang_1.lang.__('LOCAL_EXECUTION_TIMEOUT', { timeoutMs: String(funOptions.timeout) })));
272
+ }, funOptions.timeout);
273
+ });
267
274
  try {
268
- return await runner.execute(event, context);
275
+ return await Promise.race([runner.execute(event, context), deadline]);
269
276
  }
270
277
  finally {
278
+ clearTimeout(timeoutId);
271
279
  await runner.terminate();
272
280
  }
273
281
  };
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLocalHttpAdapter = void 0;
4
+ const common_1 = require("../../common");
5
+ const lang_1 = require("../../lang");
6
+ const localStack_1 = require("../../types/localStack");
7
+ const aliyunFc_1 = require("./aliyunFc");
8
+ const legacyLambda_1 = require("./legacyLambda");
9
+ const tencent_1 = require("./tencent");
10
+ const volcengine_1 = require("./volcengine");
11
+ const httpError_1 = require("./httpError");
12
+ const aliyunHttpAdapter = {
13
+ validate: () => undefined,
14
+ buildInvocation: async (req, parsed, iac, fn, requestId) => ({
15
+ event: (await (0, aliyunFc_1.transformToAliyunEvent)(req, parsed.url, parsed.query)).event,
16
+ context: (0, aliyunFc_1.createAliyunContextSerializable)(iac, fn.name, fn.code.handler, fn.memory ?? 128, fn.timeout ?? 3, requestId),
17
+ env: { ...fn.environment },
18
+ }),
19
+ transformResponse: (result, kind) => result || kind === localStack_1.RouteKind.SI_EVENTS
20
+ ? (0, aliyunFc_1.transformFCResponse)(result)
21
+ : { statusCode: 200, body: result },
22
+ };
23
+ /**
24
+ * Generic execution for providers without a native local HTTP simulation.
25
+ * The request body is treated as an already-formed event object; this is a
26
+ * low-level invocation harness, not a provider-native simulation.
27
+ */
28
+ const genericHttpAdapter = {
29
+ validate: () => undefined,
30
+ buildInvocation: async (req, _parsed, iac, fn, requestId) => {
31
+ const rawBody = await (0, common_1.readRequestBody)(req);
32
+ return {
33
+ event: rawBody ? JSON.parse(rawBody) : {},
34
+ env: { ...fn.environment, ...(0, legacyLambda_1.createLegacyEnv)(iac, fn) },
35
+ context: (0, legacyLambda_1.createLegacyContext)(iac, fn, requestId),
36
+ };
37
+ },
38
+ transformResponse: (result) => ({ statusCode: 200, body: result }),
39
+ };
40
+ const httpAdapters = {
41
+ [common_1.ProviderEnum.ALIYUN]: aliyunHttpAdapter,
42
+ [common_1.ProviderEnum.VOLCENGINE]: volcengine_1.volcengineHttpAdapter,
43
+ [common_1.ProviderEnum.TENCENT]: tencent_1.scfHttpAdapter,
44
+ [common_1.ProviderEnum.AWS]: genericHttpAdapter,
45
+ [common_1.ProviderEnum.HUAWEI]: genericHttpAdapter,
46
+ };
47
+ const getLocalHttpAdapter = (provider) => {
48
+ const adapter = Object.hasOwn(httpAdapters, provider) ? httpAdapters[provider] : undefined;
49
+ if (!adapter) {
50
+ throw (0, httpError_1.createLocalHttpError)(501, lang_1.lang.__('LOCAL_HTTP_PROVIDER_UNSUPPORTED', { provider }));
51
+ }
52
+ return adapter;
53
+ };
54
+ exports.getLocalHttpAdapter = getLocalHttpAdapter;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLocalHttpError = void 0;
4
+ const createLocalHttpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
5
+ exports.createLocalHttpError = createLocalHttpError;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLegacyEnv = exports.createLegacyContext = void 0;
4
+ /**
5
+ * The generic execution context shared by providers without a native local HTTP
6
+ * simulation (AWS, Huawei). It is an AWS Lambda-shaped context kept only for
7
+ * backward compatibility: it is not a provider-native contract for either
8
+ * provider, and local provider-native parity is not claimed for them.
9
+ */
10
+ const createLegacyContext = (iac, fn, requestId) => ({
11
+ functionName: fn.name,
12
+ functionVersion: '$LATEST',
13
+ memoryLimitInMB: fn.memory,
14
+ logGroupName: `/aws/lambda/${fn.name}`,
15
+ logStreamName: `${new Date().toISOString().split('T')[0]}/[$LATEST]${requestId}`,
16
+ invokedFunctionArn: `arn:aws:lambda:${iac.provider.region}:000000000000:function:${fn.name}`,
17
+ awsRequestId: requestId,
18
+ });
19
+ exports.createLegacyContext = createLegacyContext;
20
+ const createLegacyEnv = (iac, fn) => ({
21
+ AWS_REGION: iac.provider.region || 'us-east-1',
22
+ FUNCTION_NAME: fn.name,
23
+ FUNCTION_MEMORY_SIZE: String(fn.memory),
24
+ FUNCTION_TIMEOUT: String(fn.timeout),
25
+ });
26
+ exports.createLegacyEnv = createLegacyEnv;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildLocalContext = void 0;
4
+ const common_1 = require("../../common");
5
+ const aliyunFc_1 = require("./aliyunFc");
6
+ const legacyLambda_1 = require("./legacyLambda");
7
+ const tencent_1 = require("./tencent");
8
+ const volcengine_1 = require("./volcengine");
9
+ /**
10
+ * The single entry point for local invocation contexts.
11
+ *
12
+ * HTTP adapters and the local timer simulation both go through it, so a
13
+ * provider is never handed another provider's context shape. Every provider
14
+ * owns its builder; AWS and Huawei share the legacy generic context and make
15
+ * no provider-native claim.
16
+ */
17
+ const buildLocalContext = (provider, iac, fn, requestId) => {
18
+ switch (provider) {
19
+ case common_1.ProviderEnum.ALIYUN:
20
+ return (0, aliyunFc_1.createAliyunContextSerializable)(iac, fn.name, fn.code?.handler ?? '', fn.memory ?? 128, fn.timeout ?? 3, requestId);
21
+ case common_1.ProviderEnum.TENCENT:
22
+ return (0, tencent_1.createScfContextSerializable)(iac, fn, requestId);
23
+ case common_1.ProviderEnum.VOLCENGINE:
24
+ return (0, volcengine_1.createVolcengineContext)(requestId);
25
+ default:
26
+ return (0, legacyLambda_1.createLegacyContext)(iac, fn, requestId);
27
+ }
28
+ };
29
+ exports.buildLocalContext = buildLocalContext;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.preservesLocalPath = void 0;
4
+ const common_1 = require("../../common");
5
+ /**
6
+ * Providers whose local HTTP routes keep the request path verbatim, including
7
+ * repeated and trailing slashes. Their simulated HTTP triggers match the path
8
+ * exactly rather than collapsing or wildcarding path segments.
9
+ */
10
+ const PRESERVES_PATH = [common_1.ProviderEnum.TENCENT, common_1.ProviderEnum.VOLCENGINE];
11
+ const preservesLocalPath = (provider) => PRESERVES_PATH.includes(provider);
12
+ exports.preservesLocalPath = preservesLocalPath;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isLocalNodeRuntime = exports.localNodeRuntimes = void 0;
4
+ const common_1 = require("../../common");
5
+ /**
6
+ * Runtimes the shared local worker can actually execute, keyed by provider.
7
+ *
8
+ * Entries use the runtime identifiers an IAC declares: the standard runtimes of
9
+ * src/common/runtimeMapper.ts for Tencent, the veFaaS runtime ids for Volcengine.
10
+ * This is a local execution capability list, not the deploy-time support list —
11
+ * the local worker runs the installed Node.js, so other languages, custom
12
+ * runtimes and container images cannot be simulated. Keep it in step with the
13
+ * provider's Node.js runtime set when that changes.
14
+ */
15
+ const LOCAL_NODE_RUNTIMES = {
16
+ [common_1.ProviderEnum.TENCENT]: ['nodejs10', 'nodejs12', 'nodejs14', 'nodejs16', 'nodejs18'],
17
+ [common_1.ProviderEnum.VOLCENGINE]: ['node14/v1', 'node20/v1'],
18
+ };
19
+ const localNodeRuntimes = (provider) => LOCAL_NODE_RUNTIMES[provider] ?? [];
20
+ exports.localNodeRuntimes = localNodeRuntimes;
21
+ const isLocalNodeRuntime = (provider, runtime) => (0, exports.localNodeRuntimes)(provider).includes(runtime);
22
+ exports.isLocalNodeRuntime = isLocalNodeRuntime;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.stopLocal = exports.servLocal = void 0;
7
7
  const localStack_1 = require("../../types/localStack");
8
8
  const common_1 = require("../../common");
9
+ const localRoute_1 = require("./localRoute");
9
10
  const node_http_1 = __importDefault(require("node:http"));
10
11
  const lang_1 = require("../../lang");
11
12
  let localServer;
@@ -21,7 +22,7 @@ const respondRaw = (res, status, body, headers = {}) => {
21
22
  res.writeHead(status, headers);
22
23
  res.end(body);
23
24
  };
24
- const parseRequest = (req) => {
25
+ const parseRequest = (req, preservePath) => {
25
26
  const url = new URL(req.url ?? '/', 'http://localhost');
26
27
  const [routeSegment, identifierSegment, ...rest] = cleanPathSegments(url.pathname);
27
28
  if (!routeSegment) {
@@ -32,7 +33,11 @@ const parseRequest = (req) => {
32
33
  if (!kind) {
33
34
  return undefined;
34
35
  }
35
- const subPath = rest.length > 0 ? `/${rest.join('/')}` : '/';
36
+ const subPath = preservePath
37
+ ? (url.pathname.match(/^\/[^/]+\/[^/]+(\/.*)?$/)?.[1] ?? '/')
38
+ : rest.length > 0
39
+ ? `/${rest.join('/')}`
40
+ : '/';
36
41
  return {
37
42
  kind,
38
43
  identifier: identifierSegment,
@@ -49,7 +54,7 @@ const servLocal = async (handlers, iac) => {
49
54
  }
50
55
  localServer = node_http_1.default.createServer(async (req, res) => {
51
56
  try {
52
- const parsed = parseRequest(req);
57
+ const parsed = parseRequest(req, (0, localRoute_1.preservesLocalPath)(iac.provider.name));
53
58
  if (!parsed) {
54
59
  respondJson(res, 404, { error: 'Route not found' });
55
60
  return;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readUtf8Body = void 0;
4
+ const consumers_1 = require("node:stream/consumers");
5
+ const node_util_1 = require("node:util");
6
+ const lang_1 = require("../../lang");
7
+ const httpError_1 = require("./httpError");
8
+ /**
9
+ * Read a request body as UTF-8 text, refusing bytes that are not valid UTF-8.
10
+ *
11
+ * The providers simulated here hand the handler a string body, so a binary
12
+ * request has no representable event. `messageKey` selects the provider's
13
+ * "binary requests are not simulated" message.
14
+ */
15
+ const readUtf8Body = async (req, messageKey) => {
16
+ const body = await (0, consumers_1.buffer)(req);
17
+ try {
18
+ return new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(body);
19
+ }
20
+ catch {
21
+ throw (0, httpError_1.createLocalHttpError)(415, lang_1.lang.__(messageKey));
22
+ }
23
+ };
24
+ exports.readUtf8Body = readUtf8Body;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateProviderRequestId = exports.generateRequestId = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const common_1 = require("../../common");
6
+ /**
7
+ * Local request ids are UUIDs. SCF (Tencent) and veFaaS (Volcengine) request ids
8
+ * keep their hyphens, matching the shape the providers document; Aliyun FC
9
+ * strips them.
10
+ */
11
+ const generateRequestId = (preserveHyphens = false) => {
12
+ const requestId = (0, node_crypto_1.randomUUID)();
13
+ return preserveHyphens ? requestId : requestId.replace(/-/g, '');
14
+ };
15
+ exports.generateRequestId = generateRequestId;
16
+ const keepsHyphens = (provider) => provider === common_1.ProviderEnum.TENCENT || provider === common_1.ProviderEnum.VOLCENGINE;
17
+ const generateProviderRequestId = (provider) => (0, exports.generateRequestId)(keepsHyphens(provider));
18
+ exports.generateProviderRequestId = generateProviderRequestId;