@vectorx/functions-framework 0.0.0-beta-20251112071234

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +141 -0
  2. package/bin/rcb-ff.js +153 -0
  3. package/lib/async-context.js +61 -0
  4. package/lib/config.js +10 -0
  5. package/lib/constants.js +10 -0
  6. package/lib/error.js +47 -0
  7. package/lib/framework.js +183 -0
  8. package/lib/function-loader.js +63 -0
  9. package/lib/function-registry.js +20 -0
  10. package/lib/function-wrapper.js +170 -0
  11. package/lib/index.js +23 -0
  12. package/lib/logger.js +204 -0
  13. package/lib/middlewares/index.js +19 -0
  14. package/lib/middlewares/middle-apm-injection.js +37 -0
  15. package/lib/middlewares/middle-async-context.js +27 -0
  16. package/lib/middlewares/middle-common-logger.js +67 -0
  17. package/lib/middlewares/middle-context-injection.js +33 -0
  18. package/lib/middlewares/middle-event-id.js +20 -0
  19. package/lib/middlewares/middle-function-route.js +26 -0
  20. package/lib/middlewares/middle-logs-request.js +98 -0
  21. package/lib/middlewares/middle-open-gw-request.js +29 -0
  22. package/lib/request.js +162 -0
  23. package/lib/router.js +51 -0
  24. package/lib/server.js +115 -0
  25. package/lib/sse.js +258 -0
  26. package/lib/telemetry/langfuse.js +13 -0
  27. package/lib/types.js +2 -0
  28. package/lib/unified-responder.js +64 -0
  29. package/lib/user-logger.js +54 -0
  30. package/lib/utils/apm.config.js +7 -0
  31. package/lib/utils/apm.js +140 -0
  32. package/lib/utils/common.js +5 -0
  33. package/lib/utils/console-intercept.js +58 -0
  34. package/lib/utils/error-stack.js +30 -0
  35. package/lib/utils/helper.js +88 -0
  36. package/lib/utils/machineId.js +72 -0
  37. package/package.json +76 -0
  38. package/types/async-context.d.ts +17 -0
  39. package/types/config.d.ts +1 -0
  40. package/types/constants.d.ts +2 -0
  41. package/types/error.d.ts +20 -0
  42. package/types/framework.d.ts +32 -0
  43. package/types/function-loader.d.ts +26 -0
  44. package/types/function-registry.d.ts +4 -0
  45. package/types/function-wrapper.d.ts +3 -0
  46. package/types/index.d.ts +7 -0
  47. package/types/logger.d.ts +74 -0
  48. package/types/middlewares/index.d.ts +8 -0
  49. package/types/middlewares/middle-apm-injection.d.ts +2 -0
  50. package/types/middlewares/middle-async-context.d.ts +2 -0
  51. package/types/middlewares/middle-common-logger.d.ts +2 -0
  52. package/types/middlewares/middle-context-injection.d.ts +4 -0
  53. package/types/middlewares/middle-event-id.d.ts +2 -0
  54. package/types/middlewares/middle-function-route.d.ts +4 -0
  55. package/types/middlewares/middle-logs-request.d.ts +3 -0
  56. package/types/middlewares/middle-open-gw-request.d.ts +2 -0
  57. package/types/request.d.ts +46 -0
  58. package/types/router.d.ts +15 -0
  59. package/types/server.d.ts +33 -0
  60. package/types/sse.d.ts +23 -0
  61. package/types/telemetry/langfuse.d.ts +4 -0
  62. package/types/types.d.ts +18 -0
  63. package/types/unified-responder.d.ts +15 -0
  64. package/types/user-logger.d.ts +5 -0
  65. package/types/utils/apm.config.d.ts +6 -0
  66. package/types/utils/apm.d.ts +21 -0
  67. package/types/utils/common.d.ts +2 -0
  68. package/types/utils/console-intercept.d.ts +6 -0
  69. package/types/utils/error-stack.d.ts +5 -0
  70. package/types/utils/helper.d.ts +7 -0
  71. package/types/utils/machineId.d.ts +2 -0
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.deepFreeze = deepFreeze;
7
+ exports.isPlainObject = isPlainObject;
8
+ exports.isFormData = isFormData;
9
+ exports.toQueryString = toQueryString;
10
+ exports.obj2StrRecord = obj2StrRecord;
11
+ exports.formatUrl = formatUrl;
12
+ exports.getDependencyVersion = getDependencyVersion;
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = __importDefault(require("path"));
15
+ function deepFreeze(obj) {
16
+ if (obj === null || typeof obj !== "object") {
17
+ return obj;
18
+ }
19
+ Object.keys(obj).forEach((prop) => {
20
+ const value = obj[prop];
21
+ if (typeof value === "object" && value !== null) {
22
+ deepFreeze(value);
23
+ }
24
+ });
25
+ return Object.freeze(obj);
26
+ }
27
+ function isPlainObject(obj) {
28
+ if (obj === null || typeof obj !== "object") {
29
+ return false;
30
+ }
31
+ const proto = Object.getPrototypeOf(obj);
32
+ return proto === Object.prototype || proto === null;
33
+ }
34
+ function isFormData(val) {
35
+ return Object.prototype.toString.call(val) === "[object FormData]";
36
+ }
37
+ function toQueryString(data) {
38
+ return Object.entries(data)
39
+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
40
+ .join("&");
41
+ }
42
+ function obj2StrRecord(obj) {
43
+ return Object.entries(obj).reduce((acc, cur) => {
44
+ const [key, value] = cur;
45
+ acc[key] = String(value);
46
+ return acc;
47
+ }, {});
48
+ }
49
+ function formatUrl(PROTOCOL, url, query) {
50
+ if (query === void 0) {
51
+ query = {};
52
+ }
53
+ var urlHasQuery = /\?/.test(url);
54
+ var queryString = "";
55
+ Object.keys(query).forEach((key) => {
56
+ if (queryString === "") {
57
+ !urlHasQuery && (url += "?");
58
+ }
59
+ else {
60
+ queryString += "&";
61
+ }
62
+ queryString += "".concat(key, "=").concat(encodeURIComponent(query[key]));
63
+ });
64
+ url += queryString;
65
+ if (/^http(s)?:\/\//.test(url)) {
66
+ return url;
67
+ }
68
+ return "".concat(PROTOCOL).concat(url);
69
+ }
70
+ function getDependencyVersion(packageName, searchPath) {
71
+ try {
72
+ const packagePath = require.resolve(packageName, { paths: [searchPath] });
73
+ let currentPath = path_1.default.dirname(packagePath);
74
+ let packageJsonPath = path_1.default.join(currentPath, "package.json");
75
+ while (!fs_1.default.existsSync(packageJsonPath) && currentPath !== path_1.default.parse(currentPath).root) {
76
+ currentPath = path_1.default.dirname(currentPath);
77
+ packageJsonPath = path_1.default.join(currentPath, "package.json");
78
+ }
79
+ if (fs_1.default.existsSync(packageJsonPath)) {
80
+ const pkg = require(packageJsonPath);
81
+ return pkg.version || null;
82
+ }
83
+ return null;
84
+ }
85
+ catch (e) {
86
+ return null;
87
+ }
88
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.machineIdSync = machineIdSync;
4
+ exports.machineId = machineId;
5
+ const child_process_1 = require("child_process");
6
+ const crypto_1 = require("crypto");
7
+ const { platform } = process, win32RegBinPath = {
8
+ native: "%windir%\\System32",
9
+ mixed: "%windir%\\sysnative\\cmd.exe /c %windir%\\System32",
10
+ }, guid = {
11
+ darwin: "ioreg -rd1 -c IOPlatformExpertDevice",
12
+ win32: `${win32RegBinPath[isWindowsProcessMixedOrNativeArchitecture()]}\\REG.exe ` +
13
+ "QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography " +
14
+ "/v MachineGuid",
15
+ linux: "( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",
16
+ freebsd: "kenv -q smbios.system.uuid || sysctl -n kern.hostuuid",
17
+ };
18
+ function isWindowsProcessMixedOrNativeArchitecture() {
19
+ if (process.platform !== "win32") {
20
+ return "";
21
+ }
22
+ if (process.arch === "ia32" && process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")) {
23
+ return "mixed";
24
+ }
25
+ return "native";
26
+ }
27
+ function hash(guid) {
28
+ return (0, crypto_1.createHash)("sha256").update(guid).digest("hex");
29
+ }
30
+ function expose(result) {
31
+ switch (platform) {
32
+ case "darwin":
33
+ return result
34
+ .split("IOPlatformUUID")[1]
35
+ .split("\n")[0]
36
+ .replace(/\=|\s+|\"/gi, "")
37
+ .toLowerCase();
38
+ case "win32":
39
+ return result
40
+ .toString()
41
+ .split("REG_SZ")[1]
42
+ .replace(/\r+|\n+|\s+/gi, "")
43
+ .toLowerCase();
44
+ case "linux":
45
+ return result
46
+ .toString()
47
+ .replace(/\r+|\n+|\s+/gi, "")
48
+ .toLowerCase();
49
+ case "freebsd":
50
+ return result
51
+ .toString()
52
+ .replace(/\r+|\n+|\s+/gi, "")
53
+ .toLowerCase();
54
+ default:
55
+ throw new Error(`Unsupported platform: ${process.platform}`);
56
+ }
57
+ }
58
+ function machineIdSync(original) {
59
+ const id = expose((0, child_process_1.execSync)(guid[platform]).toString());
60
+ return original ? id : hash(id);
61
+ }
62
+ function machineId(original) {
63
+ return new Promise((resolve, reject) => {
64
+ return (0, child_process_1.exec)(guid[platform], {}, (err, stdout, stderr) => {
65
+ if (err) {
66
+ return reject(new Error(`Error while obtaining machine id: ${err.stack}`));
67
+ }
68
+ const id = expose(stdout.toString());
69
+ return resolve(original ? id : hash(id));
70
+ });
71
+ });
72
+ }
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@vectorx/functions-framework",
3
+ "version": "0.0.0-beta-20251112071234",
4
+ "description": "VectorX Functions Framework",
5
+ "main": "lib/index.js",
6
+ "types": "types/index.d.ts",
7
+ "bin": {
8
+ "rcb-ff": "./bin/rcb-ff.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "lib",
13
+ "types",
14
+ "README.md"
15
+ ],
16
+ "keywords": [
17
+ "cloud-functions",
18
+ "koa",
19
+ "serverless",
20
+ "nodejs"
21
+ ],
22
+ "author": "",
23
+ "license": "ISC",
24
+ "engines": {
25
+ "node": ">=18.0.0"
26
+ },
27
+ "dependencies": {
28
+ "@vectorx/ai-types": "0.0.0-beta-20251112071234",
29
+ "async_hooks": "^1.0.0",
30
+ "chalk": "4",
31
+ "commander": "^12.1.0",
32
+ "dotenv": "^16.5.0",
33
+ "koa": "^2.14.2",
34
+ "koa-body": "^6.0.1",
35
+ "koa-bodyparser": "^4.4.1",
36
+ "koa-router": "^12.0.1",
37
+ "langfuse": "^3.38.4",
38
+ "node-fetch": "v2",
39
+ "nodemon": "^3.1.10",
40
+ "openai": "^4.103.0",
41
+ "radix3": "^1.1.2",
42
+ "raw-body": "^2.5.2",
43
+ "uuid": "^9.0.1",
44
+ "winston": "^3.11.0",
45
+ "winston-daily-rotate-file": "^4.7.1"
46
+ },
47
+ "devDependencies": {
48
+ "@types/jest": "^29.5.12",
49
+ "@types/koa": "^2.13.12",
50
+ "@types/koa-bodyparser": "^4.3.12",
51
+ "@types/koa-router": "^7.4.8",
52
+ "@types/node": "^20.11.24",
53
+ "@types/supertest": "^6.0.2",
54
+ "@types/uuid": "^9.0.8",
55
+ "@typescript-eslint/eslint-plugin": "^7.1.0",
56
+ "@typescript-eslint/parser": "^7.1.0",
57
+ "eslint": "^8.57.0",
58
+ "jest": "^29.7.0",
59
+ "rimraf": "^3.0.2",
60
+ "supertest": "^6.3.4",
61
+ "ts-jest": "^29.1.2",
62
+ "ts-node-dev": "^2.0.0",
63
+ "typescript": "^5.3.3"
64
+ },
65
+ "scripts": {
66
+ "build": "tsc",
67
+ "dev": "tsc -w",
68
+ "test": "jest",
69
+ "test:watch": "jest --watch",
70
+ "test:coverage": "jest --coverage",
71
+ "test:ci": "jest --ci --coverage",
72
+ "lint": "eslint src --ext .ts",
73
+ "run:demo": "node ./bin/rcb-ff.js"
74
+ },
75
+ "readme": "# VectorX Functions Framework\n\nVectorX Functions Framework 是一个用于构建和运行云函数的框架,提供了完整的日志系统支持。\n\n## 日志系统\n\n框架内置了完整的日志系统,支持请求日志记录和用户代码日志记录。\n\n### 配置\n\n在初始化框架时,可以配置日志系统:\n\n```typescript\nimport { createAgentServerFramework } from '@vectorx/functions-framework';\n\nconst framework = createAgentServerFramework({\n port: 3000,\n logging: {\n dirname: '/path/to/logs', // 日志存储目录\n maxSize: '20m', // 单个日志文件最大大小\n maxFiles: 14 // 保留的日志文件数量\n }\n});\n```\n\n### 日志类型\n\n框架支持两种类型的日志:\n\n- `ACCESS`: 访问日志,记录所有 HTTP 请求\n- `USERCODE`: 用户代码日志,记录用户函数中的日志\n\n### 日志查询 API\n\n框架提供了日志查询 API,用于查看和调试日志:\n\n```\nGET /@logs\n```\n\n#### 查询参数\n\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| type | string | 否 | 日志类型,可选值:ACCESS/USERCODE,默认 ACCESS |\n| limit | number | 否 | 返回的日志条数限制,默认 100 |\n| eventId | string | 否 | 按 eventId 过滤日志 |\n\n#### 示例\n\n1. 查询所有访问日志:\n```bash\ncurl 'http://localhost:3000/@logs?type=ACCESS'\n```\n\n2. 查询特定 eventId 的日志:\n```bash\ncurl 'http://localhost:3000/@logs?eventId=550e8400-e29b-41d4-a716-446655440000'\n```\n\n3. 限制返回条数:\n```bash\ncurl 'http://localhost:3000/@logs?limit=10'\n```\n\n4. 组合查询:\n```bash\ncurl 'http://localhost:3000/@logs?type=USERCODE&eventId=550e8400-e29b-41d4-a716-446655440000&limit=20'\n```\n\n#### 响应格式\n\n成功响应:\n```json\n{\n \"success\": true,\n \"data\": [\n {\n \"@timestamp\": \"2024-03-21T10:30:00.000Z\",\n \"level\": \"info\",\n \"eventId\": \"550e8400-e29b-41d4-a716-446655440000\",\n \"message\": \"Request started\",\n \"method\": \"GET\",\n \"url\": \"/api/example\"\n }\n ]\n}\n```\n\n错误响应:\n```json\n{\n \"success\": false,\n \"error\": \"错误信息\"\n}\n```\n\n### 在代码中使用日志\n\n```typescript\nimport { functionsLogger } from '@vectorx/functions-framework';\nimport { LogLevel } from '@vectorx/functions-framework';\n\n// 记录访问日志\nfunctionsLogger.logAccesslog(LogLevel.INFO, 'Custom message', {\n customField: 'value'\n});\n\n// 记录用户代码日志\nfunctionsLogger.logUserCodelog([\n { message: 'User log message', level: 'info' }\n]);\n```\n\n### 日志格式\n\n每条日志都包含以下字段:\n\n- `@timestamp`: 日志时间戳\n- `level`: 日志级别\n- `eventId`: 请求 ID\n- `message`: 日志消息\n- 其他自定义字段\n\n## 开发\n\n### 运行测试\n\n```bash\nnpm test\n```\n\n### 构建\n\n```bash\nnpm run build\n``` \n\n\n### 环境管理\n读取 .env 文件,校验 env 文件的可用性,获取当前运行环境\n"
76
+ }
@@ -0,0 +1,17 @@
1
+ import type { IUserCodeLogItem } from "./logger";
2
+ declare const CONTEXT_ID: unique symbol;
3
+ export interface ExecutionContext {
4
+ id: typeof CONTEXT_ID;
5
+ done: boolean;
6
+ eventID: string;
7
+ userCodeLogs?: Array<IUserCodeLogItem>;
8
+ userCodeLogsFlushTimer?: NodeJS.Timeout;
9
+ apmMeasurementData?: Record<string, any>;
10
+ }
11
+ export declare function newExecutionContext(eventId: string, apmData?: Record<string, any>): ExecutionContext;
12
+ export declare function getCurrentEventID(): string;
13
+ export declare function getCurrentAsyncContext(): ExecutionContext | undefined;
14
+ export declare function isInFrameworkAsyncContext(): boolean;
15
+ export declare function done(): Promise<void>;
16
+ export declare function wrapWithAsyncContext<T>(executionContext: ExecutionContext, fn: () => Promise<T>): Promise<T>;
17
+ export {};
@@ -0,0 +1 @@
1
+ export declare function getBaseUrl(): string;
@@ -0,0 +1,2 @@
1
+ import type { FrameworkOptions } from "./framework";
2
+ export declare const defaultOptions: FrameworkOptions;
@@ -0,0 +1,20 @@
1
+ export declare class AppError extends Error {
2
+ code: number;
3
+ cause: any;
4
+ constructor(code: number, message: string, options: {
5
+ cause: Error | string;
6
+ });
7
+ }
8
+ export declare enum ErrorCode {
9
+ SYS_ERR = 500,
10
+ BAD_REQUEST = 400,
11
+ TIMEOUT = 408,
12
+ TOO_MANY_REQUESTS = 429,
13
+ UNAUTHORIZED = 401
14
+ }
15
+ export declare function decorateErrorStack(err: any): any;
16
+ export declare function newSysErr(err: Error | string): AppError;
17
+ export declare function newBadRequestErr(err: Error | string): AppError;
18
+ export declare function newTimeoutErr(): AppError;
19
+ export declare function newTooManyRequestsErr(err: Error | string): AppError;
20
+ export declare function newUnauthorizedErr(err: Error | string): AppError;
@@ -0,0 +1,32 @@
1
+ declare function getDependencyVersion(packageName: string, searchPath: string): string | null;
2
+ export interface FrameworkOptions {
3
+ port: number;
4
+ timeoutMS: number;
5
+ keepAliveTimeoutMS: number;
6
+ functionsConfigFile: string;
7
+ enableCors: boolean;
8
+ allowedOrigins?: string[];
9
+ logging?: {
10
+ dirname?: string;
11
+ maxSize?: string;
12
+ maxFiles?: number;
13
+ };
14
+ kitInfo?: {
15
+ agentRuntimeVersion: string;
16
+ functionsFrameworkVersion: string;
17
+ };
18
+ redLangfuseConfig?: {
19
+ enable?: boolean;
20
+ };
21
+ }
22
+ export type FunctionName = string;
23
+ declare class AgentServerFramework {
24
+ private options;
25
+ private router;
26
+ private apmReporter;
27
+ constructor(options: FrameworkOptions);
28
+ startServer(): Promise<import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>>;
29
+ getRegisteredFunction(fnName: string): Function;
30
+ }
31
+ export { getDependencyVersion };
32
+ export declare function createAgentServerFramework(options: FrameworkOptions): AgentServerFramework;
@@ -0,0 +1,26 @@
1
+ export declare const DEFAULT_FN_NAME = "main";
2
+ export interface FunctionConfig {
3
+ name: string;
4
+ directory: string;
5
+ source: string;
6
+ triggerPath: string;
7
+ }
8
+ export interface RouteConfig {
9
+ functionName: string;
10
+ path: string;
11
+ }
12
+ export interface CloudFunctionConfig {
13
+ agentId: string;
14
+ functionsRoot: string;
15
+ functions?: FunctionConfig[];
16
+ routes?: RouteConfig[];
17
+ }
18
+ export interface ProjectConfig {
19
+ agentId: string;
20
+ version: string;
21
+ desc: string;
22
+ "@vectorx/agent-runtime": string;
23
+ "@vectorx/functions-framework": string;
24
+ }
25
+ export declare function loadFunctionsConfig(configPath: string): CloudFunctionConfig;
26
+ export declare function loadFunction(functionsRoot: string, functionConfig: FunctionConfig): any;
@@ -0,0 +1,4 @@
1
+ export declare function buildFnId(fnName: string, functionName: string): string;
2
+ export declare function registerFunction(fnName: string, fn: Function): void;
3
+ export declare function getRegisteredFunction(fnId: string): Function | undefined;
4
+ export declare function clearRegistry(): void;
@@ -0,0 +1,3 @@
1
+ import type { Context, Next } from "koa";
2
+ import type { ProjectConfig } from "./function-loader";
3
+ export declare function wrapHandlerFunction(userFunction: Function, projectConfig: ProjectConfig): (ctx: Context, next: Next) => Promise<void>;
@@ -0,0 +1,7 @@
1
+ export * from "./framework";
2
+ export * from "./router";
3
+ export * from "./function-loader";
4
+ export * from "./function-registry";
5
+ export * from "./sse";
6
+ export * from "./server";
7
+ export * from "./logger";
@@ -0,0 +1,74 @@
1
+ import type { ApmReporter } from "./utils/apm";
2
+ export declare enum LogType {
3
+ ACCESS = "ACCESS",
4
+ USERCODE = "USERCODE"
5
+ }
6
+ export interface ILog {
7
+ "@timestamp": string;
8
+ logType: LogType;
9
+ }
10
+ export interface IUserCodeLogItem {
11
+ "@timestamp"?: string;
12
+ caller?: string;
13
+ stacktraces?: string;
14
+ level?: string;
15
+ content: string | Uint8Array;
16
+ }
17
+ export interface IUserCodeLog {
18
+ "@timestamp": string;
19
+ logType: LogType;
20
+ level: "log" | "info" | "warn" | "error";
21
+ module: string;
22
+ name: string;
23
+ eventId: string;
24
+ requestId: string;
25
+ scene?: "logBeforeReturn" | "logAfterReturn";
26
+ logs: IUserCodeLogItem[];
27
+ }
28
+ export declare enum LogLevel {
29
+ ERROR = "error",
30
+ WARN = "warn",
31
+ INFO = "info",
32
+ DEBUG = "debug"
33
+ }
34
+ export interface LogEntry {
35
+ message: string;
36
+ level: string;
37
+ [key: string]: any;
38
+ }
39
+ export interface LoggerConfig {
40
+ type: LogType;
41
+ options: {
42
+ dirname?: string;
43
+ maxSize?: string;
44
+ maxFiles?: number;
45
+ };
46
+ }
47
+ declare class FunctionsLogger {
48
+ private tLoggers;
49
+ private apmReporter?;
50
+ constructor();
51
+ setApmReporter(reporter: ApmReporter): void;
52
+ init(opts: LoggerConfig[]): void;
53
+ private formatLogMessage;
54
+ logAccesslog(level: LogLevel, message: string, metadata?: any): void;
55
+ logUserCodelog(): void;
56
+ log(type: LogType, level: LogLevel, message: string, metadata?: any): void;
57
+ getLogs(type: LogType, limit?: number): Promise<LogEntry[]>;
58
+ getLogsPaginated(options: {
59
+ type: LogType;
60
+ pageNum?: number;
61
+ pageSize?: number;
62
+ }): Promise<{
63
+ logs: LogEntry[];
64
+ pageNum: number;
65
+ pageSize: number;
66
+ total: number;
67
+ hasMore: boolean;
68
+ }>;
69
+ private getAllLogs;
70
+ private createWinstonLogger;
71
+ logError(error: Error | string, metadata?: any): void;
72
+ }
73
+ export declare const functionsLogger: FunctionsLogger;
74
+ export {};
@@ -0,0 +1,8 @@
1
+ export { asyncContextMiddleware } from "./middle-async-context";
2
+ export { contextInjectionMiddleware } from "./middle-context-injection";
3
+ export { eventIdMiddleware } from "./middle-event-id";
4
+ export { functionRouteMiddleware } from "./middle-function-route";
5
+ export { loggerMiddleware } from "./middle-common-logger";
6
+ export { logsQueryMiddleware } from "./middle-logs-request";
7
+ export { openGwRequestMiddleware } from "./middle-open-gw-request";
8
+ export { apmMiddleware } from "./middle-apm-injection";
@@ -0,0 +1,2 @@
1
+ import type { Context, Next } from "koa";
2
+ export declare function apmMiddleware(): (ctx: Context, next: Next) => Promise<any>;
@@ -0,0 +1,2 @@
1
+ declare const asyncContextMiddleware: () => (ctx: any, next: any) => Promise<void>;
2
+ export { asyncContextMiddleware };
@@ -0,0 +1,2 @@
1
+ import type { Context, Next } from "koa";
2
+ export declare function loggerMiddleware(): (ctx: Context, next: Next) => Promise<void>;
@@ -0,0 +1,4 @@
1
+ import type { Context, Next } from "koa";
2
+ import type { FrameworkOptions } from "../framework";
3
+ import type { ProjectConfig } from "../function-loader";
4
+ export declare function contextInjectionMiddleware(frameworkOptions: FrameworkOptions, projectConfig: ProjectConfig): (ctx: Context, next: Next) => Promise<void>;
@@ -0,0 +1,2 @@
1
+ declare const eventIdMiddleware: () => (ctx: any, next: any) => Promise<void>;
2
+ export { eventIdMiddleware };
@@ -0,0 +1,4 @@
1
+ import type { Context, Next } from "koa";
2
+ import type { ProjectConfig } from "../function-loader";
3
+ import { type Router } from "../router";
4
+ export declare function functionRouteMiddleware(router: Router, projectConfig: ProjectConfig): (ctx: Context, next: Next) => Promise<any>;
@@ -0,0 +1,3 @@
1
+ import type { Context, Next } from "koa";
2
+ declare function logsQueryMiddleware(): (ctx: Context, next: Next) => Promise<any>;
3
+ export { logsQueryMiddleware };
@@ -0,0 +1,2 @@
1
+ import type { Context, Next } from "koa";
2
+ export declare function openGwRequestMiddleware(agentId: string): (ctx: Context, next: Next) => Promise<void>;
@@ -0,0 +1,46 @@
1
+ import type { IAbstractRequest } from "@vectorx/ai-types";
2
+ export interface IRequestConfig {
3
+ timeout?: number;
4
+ timeoutMsg?: string;
5
+ restrictedMethods?: Array<IRequestMethod>;
6
+ defaultHeaders?: Record<string, string>;
7
+ }
8
+ export type IRequestMethod = "get" | "post" | "put" | "upload" | "download";
9
+ export interface IRequestOptions {
10
+ url?: string;
11
+ headers?: Record<string, string>;
12
+ data?: any;
13
+ responseType?: string;
14
+ withCredentials?: boolean;
15
+ body?: any;
16
+ method?: string;
17
+ file?: File;
18
+ name?: string;
19
+ }
20
+ export interface IFetchOptions {
21
+ url: string;
22
+ headers?: HeadersInit;
23
+ body?: any;
24
+ method?: string;
25
+ enableAbort?: boolean;
26
+ stream?: boolean;
27
+ }
28
+ export interface ResponseObject<T = any> {
29
+ data?: T;
30
+ statusCode?: number;
31
+ [key: string]: any;
32
+ }
33
+ export declare class Request implements IAbstractRequest {
34
+ private readonly timeout;
35
+ private readonly timeoutMsg;
36
+ private readonly restrictedMethods;
37
+ private readonly defaultHeaders;
38
+ constructor(config?: IRequestConfig);
39
+ get<T = any>(options: IRequestOptions): Promise<ResponseObject<T>>;
40
+ post<T = any>(options: IRequestOptions): Promise<ResponseObject<T>>;
41
+ put<T = any>(options: IRequestOptions): Promise<ResponseObject<T>>;
42
+ upload<T = any>(options: IRequestOptions): Promise<ResponseObject<T>>;
43
+ download(options: IRequestOptions): Promise<unknown>;
44
+ protected request(options: IRequestOptions, enableAbort?: boolean): Promise<ResponseObject>;
45
+ fetch(options: IFetchOptions): Promise<ResponseObject>;
46
+ }
@@ -0,0 +1,15 @@
1
+ import type { CloudFunctionConfig, RouteConfig } from "./function-loader";
2
+ export declare class Router {
3
+ private routes;
4
+ private router;
5
+ constructor(config: CloudFunctionConfig);
6
+ private addRoute;
7
+ findRoute(path: string): RouteConfig | null;
8
+ }
9
+ export declare function routeFunction(router: Router | undefined, path: string): {
10
+ routeDefinition: RouteConfig;
11
+ handleFunction: Function;
12
+ } | {
13
+ routeDefinition?: undefined;
14
+ handleFunction?: undefined;
15
+ };
@@ -0,0 +1,33 @@
1
+ import http from "http";
2
+ import type { FrameworkOptions } from "./framework";
3
+ import type { ProjectConfig } from "./function-loader";
4
+ import type { functionsLogger } from "./logger";
5
+ import type { Request } from "./request";
6
+ import type { Router } from "./router";
7
+ declare module "koa" {
8
+ interface DefaultState {
9
+ isTimeout?: boolean;
10
+ langfuseTrace?: any;
11
+ }
12
+ interface Application {
13
+ routers: Map<string, Router>;
14
+ }
15
+ interface Context {
16
+ rawBody?: any;
17
+ extendedContext?: any;
18
+ httpContext?: any;
19
+ sse?: () => any;
20
+ }
21
+ }
22
+ export interface RcbContext {
23
+ ctxId: string;
24
+ eventID: string;
25
+ eventType: string;
26
+ timestamp: number;
27
+ httpContext: any;
28
+ request: Request;
29
+ logger: typeof functionsLogger;
30
+ baseUrl: string;
31
+ sse: () => any;
32
+ }
33
+ export declare function createServer(options: FrameworkOptions, router: Router, projectConfig: ProjectConfig): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
package/types/sse.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { EventEmitter } from "events";
2
+ import * as util from "util";
3
+ import type { Context } from "koa";
4
+ export interface SSEMessage {
5
+ id?: string;
6
+ event?: string;
7
+ data: any;
8
+ retry?: number;
9
+ comment?: string;
10
+ }
11
+ export declare class ServerSentEvent extends EventEmitter {
12
+ private ctx;
13
+ private stream;
14
+ private closed;
15
+ private encoder;
16
+ constructor(ctx: Context);
17
+ setEncoder(encoder: util.TextEncoder): void;
18
+ emitMessage(event: string, data: any): boolean;
19
+ emit(event: string | symbol, ...args: any[]): boolean;
20
+ send(event: SSEMessage | SSEMessage[] | string | Buffer): boolean;
21
+ end(msg?: SSEMessage | SSEMessage[] | string | Buffer): void;
22
+ get isClosed(): boolean;
23
+ }
@@ -0,0 +1,4 @@
1
+ import { Langfuse } from "langfuse";
2
+ export declare const langfuse: Langfuse;
3
+ export type LangfuseClient = typeof langfuse;
4
+ export default langfuse;
@@ -0,0 +1,18 @@
1
+ export interface RcbContext {
2
+ httpContext?: {
3
+ url: string;
4
+ };
5
+ request: (options: {
6
+ method: string;
7
+ url: string;
8
+ headers?: Record<string, string>;
9
+ body?: string;
10
+ stream?: boolean;
11
+ timeout?: number;
12
+ }) => Promise<{
13
+ data: any;
14
+ header?: Headers;
15
+ }>;
16
+ getBaseUrl: () => string;
17
+ eventID: string;
18
+ }
@@ -0,0 +1,15 @@
1
+ import type { Context } from "koa";
2
+ import { type AppError } from "./error";
3
+ export interface ResponseBody {
4
+ code: string;
5
+ message: string;
6
+ data?: any;
7
+ stack?: string;
8
+ requestId?: string;
9
+ }
10
+ export interface IntegrationResponse {
11
+ statusCode: number;
12
+ headers: Record<string, string>;
13
+ body: any;
14
+ }
15
+ export declare function sendResponse(ctx: Context, data?: any, error?: AppError, errStatusCode?: number, withStack?: boolean): void;
@@ -0,0 +1,5 @@
1
+ declare function takeUserCodeLogs(): import("./logger").IUserCodeLogItem[];
2
+ declare function pushUserCodeLogs(log: any): void;
3
+ declare function addUserCodeLog(log: any): void;
4
+ declare function getUserCodeLogs(): import("./logger").IUserCodeLogItem[];
5
+ export { takeUserCodeLogs, pushUserCodeLogs, addUserCodeLog, getUserCodeLogs };