@bleedingdev/modern-js-bff-core 3.2.0-ultramodern.0
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.
- package/LICENSE +21 -0
- package/README.md +26 -0
- package/dist/cjs/api.js +88 -0
- package/dist/cjs/client/generateClient.js +136 -0
- package/dist/cjs/client/index.js +58 -0
- package/dist/cjs/client/result.js +56 -0
- package/dist/cjs/compatible.js +18 -0
- package/dist/cjs/contracts/eventContracts.js +68 -0
- package/dist/cjs/errors/http.js +50 -0
- package/dist/cjs/index.js +229 -0
- package/dist/cjs/operators/http.js +220 -0
- package/dist/cjs/router/constants.js +68 -0
- package/dist/cjs/router/index.js +284 -0
- package/dist/cjs/router/types.js +18 -0
- package/dist/cjs/router/utils.js +97 -0
- package/dist/cjs/security/crossProjectPolicy.js +137 -0
- package/dist/cjs/security/operationContracts.js +100 -0
- package/dist/cjs/types.js +88 -0
- package/dist/cjs/utils/alias.js +108 -0
- package/dist/cjs/utils/debug.js +37 -0
- package/dist/cjs/utils/index.js +101 -0
- package/dist/cjs/utils/meta.js +48 -0
- package/dist/cjs/utils/storage.js +64 -0
- package/dist/cjs/utils/validate.js +82 -0
- package/dist/esm/api.mjs +44 -0
- package/dist/esm/client/generateClient.mjs +99 -0
- package/dist/esm/client/index.mjs +1 -0
- package/dist/esm/client/result.mjs +19 -0
- package/dist/esm/compatible.mjs +0 -0
- package/dist/esm/contracts/eventContracts.mjs +28 -0
- package/dist/esm/errors/http.mjs +13 -0
- package/dist/esm/index.mjs +10 -0
- package/dist/esm/operators/http.mjs +135 -0
- package/dist/esm/router/constants.mjs +19 -0
- package/dist/esm/router/index.mjs +192 -0
- package/dist/esm/router/types.mjs +0 -0
- package/dist/esm/router/utils.mjs +41 -0
- package/dist/esm/security/crossProjectPolicy.mjs +94 -0
- package/dist/esm/security/operationContracts.mjs +57 -0
- package/dist/esm/types.mjs +39 -0
- package/dist/esm/utils/alias.mjs +57 -0
- package/dist/esm/utils/debug.mjs +3 -0
- package/dist/esm/utils/index.mjs +5 -0
- package/dist/esm/utils/meta.mjs +5 -0
- package/dist/esm/utils/storage.mjs +30 -0
- package/dist/esm/utils/validate.mjs +32 -0
- package/dist/esm-node/api.mjs +45 -0
- package/dist/esm-node/client/generateClient.mjs +101 -0
- package/dist/esm-node/client/index.mjs +2 -0
- package/dist/esm-node/client/result.mjs +20 -0
- package/dist/esm-node/compatible.mjs +1 -0
- package/dist/esm-node/contracts/eventContracts.mjs +29 -0
- package/dist/esm-node/errors/http.mjs +14 -0
- package/dist/esm-node/index.mjs +11 -0
- package/dist/esm-node/operators/http.mjs +136 -0
- package/dist/esm-node/router/constants.mjs +20 -0
- package/dist/esm-node/router/index.mjs +193 -0
- package/dist/esm-node/router/types.mjs +1 -0
- package/dist/esm-node/router/utils.mjs +42 -0
- package/dist/esm-node/security/crossProjectPolicy.mjs +95 -0
- package/dist/esm-node/security/operationContracts.mjs +58 -0
- package/dist/esm-node/types.mjs +40 -0
- package/dist/esm-node/utils/alias.mjs +58 -0
- package/dist/esm-node/utils/debug.mjs +4 -0
- package/dist/esm-node/utils/index.mjs +6 -0
- package/dist/esm-node/utils/meta.mjs +6 -0
- package/dist/esm-node/utils/storage.mjs +31 -0
- package/dist/esm-node/utils/validate.mjs +33 -0
- package/dist/types/api.d.ts +6 -0
- package/dist/types/client/generateClient.d.ts +21 -0
- package/dist/types/client/index.d.ts +1 -0
- package/dist/types/client/result.d.ts +15 -0
- package/dist/types/compatible.d.ts +9 -0
- package/dist/types/contracts/eventContracts.d.ts +22 -0
- package/dist/types/errors/http.d.ts +8 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/types/operators/http.d.ts +44 -0
- package/dist/types/router/constants.d.ts +6 -0
- package/dist/types/router/index.d.ts +49 -0
- package/dist/types/router/types.d.ts +18 -0
- package/dist/types/router/utils.d.ts +10 -0
- package/dist/types/security/crossProjectPolicy.d.ts +30 -0
- package/dist/types/security/operationContracts.d.ts +28 -0
- package/dist/types/types.d.ts +64 -0
- package/dist/types/utils/alias.d.ts +7 -0
- package/dist/types/utils/debug.d.ts +1 -0
- package/dist/types/utils/index.d.ts +5 -0
- package/dist/types/utils/meta.d.ts +4 -0
- package/dist/types/utils/storage.d.ts +5 -0
- package/dist/types/utils/validate.d.ts +5 -0
- package/package.json +68 -0
- package/rslib.config.mts +4 -0
- package/rstest.config.mts +10 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const Err = (value)=>{
|
|
2
|
+
const err = {
|
|
3
|
+
kind: 'Err',
|
|
4
|
+
value,
|
|
5
|
+
isErr: true,
|
|
6
|
+
isOk: false
|
|
7
|
+
};
|
|
8
|
+
return err;
|
|
9
|
+
};
|
|
10
|
+
const Ok = (value)=>{
|
|
11
|
+
const ok = {
|
|
12
|
+
kind: 'Ok',
|
|
13
|
+
value,
|
|
14
|
+
isErr: false,
|
|
15
|
+
isOk: true
|
|
16
|
+
};
|
|
17
|
+
return ok;
|
|
18
|
+
};
|
|
19
|
+
export { Err, Ok };
|
|
File without changes
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const defineEventContract = (input)=>{
|
|
2
|
+
const normalizedName = input.name.trim();
|
|
3
|
+
if (!normalizedName) throw new Error('Event contract name must be non-empty');
|
|
4
|
+
if (!Number.isFinite(input.version) || input.version <= 0) throw new Error('Event contract version must be a positive number');
|
|
5
|
+
if (!input.schemaHash || !input.schemaHash.trim()) throw new Error('Event contract schemaHash must be non-empty');
|
|
6
|
+
return {
|
|
7
|
+
name: normalizedName,
|
|
8
|
+
version: Math.floor(input.version),
|
|
9
|
+
schemaHash: input.schemaHash.trim(),
|
|
10
|
+
description: input.description
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
const createEventEnvelope = (contract, payload, meta)=>({
|
|
14
|
+
name: contract.name,
|
|
15
|
+
version: contract.version,
|
|
16
|
+
schemaHash: contract.schemaHash,
|
|
17
|
+
timestamp: Date.now(),
|
|
18
|
+
payload,
|
|
19
|
+
...meta ? {
|
|
20
|
+
meta
|
|
21
|
+
} : {}
|
|
22
|
+
});
|
|
23
|
+
const isEventEnvelope = (value)=>{
|
|
24
|
+
if (!value || 'object' != typeof value || Array.isArray(value)) return false;
|
|
25
|
+
const candidate = value;
|
|
26
|
+
return 'string' == typeof candidate.name && candidate.name.length > 0 && 'number' == typeof candidate.version && candidate.version > 0 && 'string' == typeof candidate.schemaHash && candidate.schemaHash.length > 0 && 'number' == typeof candidate.timestamp && Number.isFinite(candidate.timestamp) && 'payload' in candidate;
|
|
27
|
+
};
|
|
28
|
+
export { createEventEnvelope, defineEventContract, isEventEnvelope };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
class HttpError extends Error {
|
|
2
|
+
constructor(status, message){
|
|
3
|
+
super(message);
|
|
4
|
+
this.status = status;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
class ValidationError extends HttpError {
|
|
8
|
+
constructor(status, message){
|
|
9
|
+
super(status, message);
|
|
10
|
+
this.code = 'VALIDATION_ERROR';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export { HttpError, ValidationError };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from "./client/index.mjs";
|
|
2
|
+
export * from "./contracts/eventContracts.mjs";
|
|
3
|
+
export * from "./operators/http.mjs";
|
|
4
|
+
export * from "./router/index.mjs";
|
|
5
|
+
export * from "./security/crossProjectPolicy.mjs";
|
|
6
|
+
export * from "./security/operationContracts.mjs";
|
|
7
|
+
export * from "./types.mjs";
|
|
8
|
+
export { Api } from "./api.mjs";
|
|
9
|
+
export { HttpError, ValidationError } from "./errors/http.mjs";
|
|
10
|
+
export { HANDLER_WITH_META, INPUT_PARAMS_DECIDER, createStorage, getRelativeRuntimePath, isInputParamsDeciderHandler, isWithMetaHandler, registerPaths } from "./utils/index.mjs";
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { ValidationError } from "../errors/http.mjs";
|
|
2
|
+
import { HttpMetadata, HttpMethod, OperatorType, ResponseMetaType, TriggerType } from "../types.mjs";
|
|
3
|
+
const validateInput = async (schema, input)=>{
|
|
4
|
+
try {
|
|
5
|
+
return await schema.parseAsync(input);
|
|
6
|
+
} catch (error) {
|
|
7
|
+
if ('name' in error && 'ZodError' === error.name) throw new ValidationError(400, error.message);
|
|
8
|
+
throw error;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
const createHttpOperator = (method)=>(urlPath)=>({
|
|
12
|
+
name: method,
|
|
13
|
+
metadata ({ setMetadata }) {
|
|
14
|
+
setMetadata(OperatorType.Trigger, {
|
|
15
|
+
type: TriggerType.Http,
|
|
16
|
+
path: urlPath,
|
|
17
|
+
method
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
const Get = createHttpOperator(HttpMethod.Get);
|
|
22
|
+
const Post = createHttpOperator(HttpMethod.Post);
|
|
23
|
+
const Put = createHttpOperator(HttpMethod.Put);
|
|
24
|
+
const Delete = createHttpOperator(HttpMethod.Delete);
|
|
25
|
+
const Connect = createHttpOperator(HttpMethod.Connect);
|
|
26
|
+
const Trace = createHttpOperator(HttpMethod.Trace);
|
|
27
|
+
const Patch = createHttpOperator(HttpMethod.Patch);
|
|
28
|
+
const Options = createHttpOperator(HttpMethod.Options);
|
|
29
|
+
const Head = createHttpOperator(HttpMethod.Head);
|
|
30
|
+
const Data = (schema)=>({
|
|
31
|
+
name: HttpMetadata.Data,
|
|
32
|
+
metadata ({ setMetadata }) {
|
|
33
|
+
setMetadata(HttpMetadata.Data, schema);
|
|
34
|
+
},
|
|
35
|
+
async validate (helper, next) {
|
|
36
|
+
const { inputs: { data } } = helper;
|
|
37
|
+
helper.inputs = {
|
|
38
|
+
...helper.inputs,
|
|
39
|
+
data: await validateInput(schema, data)
|
|
40
|
+
};
|
|
41
|
+
return next();
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
const Query = (schema)=>({
|
|
45
|
+
name: HttpMetadata.Query,
|
|
46
|
+
metadata ({ setMetadata }) {
|
|
47
|
+
setMetadata(HttpMetadata.Query, schema);
|
|
48
|
+
},
|
|
49
|
+
async validate (helper, next) {
|
|
50
|
+
const { inputs: { query } } = helper;
|
|
51
|
+
helper.inputs = {
|
|
52
|
+
...helper.inputs,
|
|
53
|
+
query: await validateInput(schema, query)
|
|
54
|
+
};
|
|
55
|
+
return next();
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
const Params = (schema)=>({
|
|
59
|
+
name: HttpMetadata.Params,
|
|
60
|
+
metadata ({ setMetadata }) {
|
|
61
|
+
setMetadata(HttpMetadata.Params, schema);
|
|
62
|
+
},
|
|
63
|
+
async validate (helper, next) {
|
|
64
|
+
const { inputs: { params } } = helper;
|
|
65
|
+
helper.inputs = {
|
|
66
|
+
...helper.inputs,
|
|
67
|
+
params: await validateInput(schema, params)
|
|
68
|
+
};
|
|
69
|
+
return next();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
const Headers = (schema)=>({
|
|
73
|
+
name: HttpMetadata.Headers,
|
|
74
|
+
metadata ({ setMetadata }) {
|
|
75
|
+
setMetadata(HttpMetadata.Headers, schema);
|
|
76
|
+
},
|
|
77
|
+
async validate (helper, next) {
|
|
78
|
+
const { inputs: { headers } } = helper;
|
|
79
|
+
helper.inputs = {
|
|
80
|
+
...helper.inputs,
|
|
81
|
+
headers: await validateInput(schema, headers)
|
|
82
|
+
};
|
|
83
|
+
return next();
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
const setResponseMeta = (helper, type, value)=>{
|
|
87
|
+
const responseMetaData = helper.getMetadata(HttpMetadata.Response) || [];
|
|
88
|
+
helper.setMetadata(HttpMetadata.Response, [
|
|
89
|
+
...responseMetaData,
|
|
90
|
+
{
|
|
91
|
+
type,
|
|
92
|
+
value
|
|
93
|
+
}
|
|
94
|
+
]);
|
|
95
|
+
};
|
|
96
|
+
const HttpCode = (statusCode)=>({
|
|
97
|
+
name: 'HttpCode',
|
|
98
|
+
metadata (helper) {
|
|
99
|
+
setResponseMeta(helper, ResponseMetaType.StatusCode, statusCode);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
const SetHeaders = (headers)=>({
|
|
103
|
+
name: 'SetHeaders',
|
|
104
|
+
metadata (helper) {
|
|
105
|
+
setResponseMeta(helper, ResponseMetaType.Headers, headers);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
const Redirect = (url)=>({
|
|
109
|
+
name: 'Redirect',
|
|
110
|
+
metadata (helper) {
|
|
111
|
+
setResponseMeta(helper, ResponseMetaType.Redirect, url);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
const Upload = (urlPath, schema)=>({
|
|
115
|
+
name: 'Upload',
|
|
116
|
+
metadata ({ setMetadata }) {
|
|
117
|
+
setMetadata(OperatorType.Trigger, {
|
|
118
|
+
type: TriggerType.Http,
|
|
119
|
+
path: urlPath,
|
|
120
|
+
method: HttpMethod.Post,
|
|
121
|
+
action: 'upload'
|
|
122
|
+
});
|
|
123
|
+
setMetadata(HttpMetadata.Files, schema);
|
|
124
|
+
},
|
|
125
|
+
async validate (helper, next) {
|
|
126
|
+
if (!schema) return next();
|
|
127
|
+
const { inputs: { formData: files } } = helper;
|
|
128
|
+
helper.inputs = {
|
|
129
|
+
...helper.inputs,
|
|
130
|
+
files: await validateInput(schema, files)
|
|
131
|
+
};
|
|
132
|
+
return next();
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
export { Connect, Data, Delete, Get, Head, Headers, HttpCode, Options, Params, Patch, Post, Put, Query, Redirect, SetHeaders, Trace, Upload, createHttpOperator };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { HttpMethod } from "../types.mjs";
|
|
2
|
+
const AllHttpMethods = Object.values(HttpMethod);
|
|
3
|
+
const FRAMEWORK_MODE_LAMBDA_DIR = 'lambda';
|
|
4
|
+
const FRAMEWORK_MODE_APP_DIR = 'app';
|
|
5
|
+
const INDEX_SUFFIX = 'index';
|
|
6
|
+
const API_DIR = 'api';
|
|
7
|
+
const API_FILE_RULES = [
|
|
8
|
+
'**/*.[tj]s',
|
|
9
|
+
'!**/_*',
|
|
10
|
+
'!**/_*/**/*.[tj]s',
|
|
11
|
+
'!**/*.test.js',
|
|
12
|
+
'!**/*.test.ts',
|
|
13
|
+
'!**/*.d.ts',
|
|
14
|
+
'!__test__/*.ts',
|
|
15
|
+
'!__tests__/*.ts',
|
|
16
|
+
'!node_modules/**',
|
|
17
|
+
'!bootstrap.jsx'
|
|
18
|
+
];
|
|
19
|
+
export { API_DIR, API_FILE_RULES, AllHttpMethods, FRAMEWORK_MODE_APP_DIR, FRAMEWORK_MODE_LAMBDA_DIR, INDEX_SUFFIX };
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { fs, logger } from "@modern-js/utils";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import "reflect-metadata";
|
|
4
|
+
import { HttpMethod, OperatorType, TriggerType, httpMethods } from "../types.mjs";
|
|
5
|
+
import { INPUT_PARAMS_DECIDER, debug } from "../utils/index.mjs";
|
|
6
|
+
import { API_FILE_RULES, FRAMEWORK_MODE_LAMBDA_DIR } from "./constants.mjs";
|
|
7
|
+
import { getFiles, getPathFromFilename, requireHandlerModule, sortRoutes } from "./utils.mjs";
|
|
8
|
+
export * from "./constants.mjs";
|
|
9
|
+
export * from "./types.mjs";
|
|
10
|
+
class ApiRouter {
|
|
11
|
+
isExistLambda() {
|
|
12
|
+
return this.existLambdaDir;
|
|
13
|
+
}
|
|
14
|
+
getLambdaDir() {
|
|
15
|
+
return this.lambdaDir;
|
|
16
|
+
}
|
|
17
|
+
isApiFile(filename) {
|
|
18
|
+
if (this.apiFiles.includes(filename)) return true;
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
async getSingleModuleHandlers(filename) {
|
|
22
|
+
const moduleInfo = await this.getModuleInfo(filename);
|
|
23
|
+
if (moduleInfo) return this.getModuleHandlerInfos(moduleInfo);
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
getHandlerInfo(filename, originFuncName, handler) {
|
|
27
|
+
const httpMethod = this.getHttpMethod(originFuncName, handler);
|
|
28
|
+
const routeName = this.getRouteName(filename, handler);
|
|
29
|
+
const action = this.getAction(handler);
|
|
30
|
+
const responseObj = {
|
|
31
|
+
handler,
|
|
32
|
+
name: originFuncName,
|
|
33
|
+
httpMethod,
|
|
34
|
+
routeName,
|
|
35
|
+
filename,
|
|
36
|
+
routePath: this.getRoutePath(this.prefix, routeName)
|
|
37
|
+
};
|
|
38
|
+
if (action) responseObj.action = action;
|
|
39
|
+
if (httpMethod && routeName) return responseObj;
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
getSafeRoutePath(filename, handler) {
|
|
43
|
+
this.loadApiFiles();
|
|
44
|
+
this.validateValidApifile(filename);
|
|
45
|
+
return this.getRouteName(filename, handler);
|
|
46
|
+
}
|
|
47
|
+
getRouteName(filename, handler) {
|
|
48
|
+
if (handler) {
|
|
49
|
+
const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
|
|
50
|
+
if (trigger && trigger.type === TriggerType.Http) {
|
|
51
|
+
if (!trigger.path) throw new Error(`The http trigger ${trigger.name} needs to specify a path`);
|
|
52
|
+
return trigger.path;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
let routePath = getPathFromFilename(this.lambdaDir, filename);
|
|
56
|
+
if ('inputParams' === this.httpMethodDecider) if (routePath.endsWith('/')) routePath += `${handler?.name}`;
|
|
57
|
+
else routePath += `/${handler?.name}`;
|
|
58
|
+
return routePath;
|
|
59
|
+
}
|
|
60
|
+
getHttpMethod(originHandlerName, handler) {
|
|
61
|
+
if (handler) {
|
|
62
|
+
const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
|
|
63
|
+
if (trigger && httpMethods.includes(trigger.method)) return trigger.method;
|
|
64
|
+
}
|
|
65
|
+
if ('functionName' === this.httpMethodDecider) {
|
|
66
|
+
const upperName = originHandlerName.toUpperCase();
|
|
67
|
+
switch(upperName){
|
|
68
|
+
case 'GET':
|
|
69
|
+
return HttpMethod.Get;
|
|
70
|
+
case 'POST':
|
|
71
|
+
return HttpMethod.Post;
|
|
72
|
+
case 'PUT':
|
|
73
|
+
return HttpMethod.Put;
|
|
74
|
+
case 'DELETE':
|
|
75
|
+
case 'DEL':
|
|
76
|
+
return HttpMethod.Delete;
|
|
77
|
+
case 'CONNECT':
|
|
78
|
+
return HttpMethod.Connect;
|
|
79
|
+
case 'TRACE':
|
|
80
|
+
return HttpMethod.Trace;
|
|
81
|
+
case 'PATCH':
|
|
82
|
+
return HttpMethod.Patch;
|
|
83
|
+
case 'OPTIONS':
|
|
84
|
+
return HttpMethod.Options;
|
|
85
|
+
case 'DEFAULT':
|
|
86
|
+
return HttpMethod.Get;
|
|
87
|
+
default:
|
|
88
|
+
if ('test' !== process.env.NODE_ENV) logger.warn(`Only api handlers are allowd to be exported, please remove the function ${originHandlerName} from exports`);
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (!handler) return null;
|
|
93
|
+
if ('function' == typeof handler && handler.length > 0) return HttpMethod.Post;
|
|
94
|
+
return HttpMethod.Get;
|
|
95
|
+
}
|
|
96
|
+
getAction(handler) {
|
|
97
|
+
if (handler) {
|
|
98
|
+
const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
|
|
99
|
+
if (trigger?.action) return trigger.action;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
loadApiFiles() {
|
|
103
|
+
if (!this.existLambdaDir) return [];
|
|
104
|
+
const apiFiles = this.apiFiles = getFiles(this.lambdaDir, API_FILE_RULES);
|
|
105
|
+
return apiFiles;
|
|
106
|
+
}
|
|
107
|
+
getApiFiles() {
|
|
108
|
+
if (!this.existLambdaDir) return [];
|
|
109
|
+
if (this.apiFiles.length > 0) return this.apiFiles;
|
|
110
|
+
return this.loadApiFiles();
|
|
111
|
+
}
|
|
112
|
+
async getApiHandlers() {
|
|
113
|
+
const filenames = this.getApiFiles();
|
|
114
|
+
const moduleInfos = await this.getModuleInfos(filenames);
|
|
115
|
+
const apiHandlers = this.getHandlerInfos(moduleInfos);
|
|
116
|
+
debug('apiHandlers', apiHandlers.length, apiHandlers);
|
|
117
|
+
return apiHandlers;
|
|
118
|
+
}
|
|
119
|
+
initPrefix(prefix) {
|
|
120
|
+
if ('/' === prefix) return '';
|
|
121
|
+
return prefix || '/api';
|
|
122
|
+
}
|
|
123
|
+
validateAbsolute(filename, paramsName) {
|
|
124
|
+
if ('string' == typeof filename && !path.isAbsolute(filename)) throw new Error(`The ${paramsName} ${filename} is not a abolute path`);
|
|
125
|
+
}
|
|
126
|
+
async getModuleInfos(filenames) {
|
|
127
|
+
const moduleInfos = await Promise.all(filenames.map((filename)=>this.getModuleInfo(filename)));
|
|
128
|
+
return moduleInfos.filter(Boolean);
|
|
129
|
+
}
|
|
130
|
+
async getModuleInfo(filename) {
|
|
131
|
+
try {
|
|
132
|
+
const module = await requireHandlerModule(filename);
|
|
133
|
+
return {
|
|
134
|
+
filename,
|
|
135
|
+
module
|
|
136
|
+
};
|
|
137
|
+
} catch (err) {
|
|
138
|
+
if ('production' === process.env.NODE_ENV) {
|
|
139
|
+
const error = new Error(`Failed to load BFF module '${filename}': ${err.message}`, {
|
|
140
|
+
cause: err
|
|
141
|
+
});
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
console.error(`Failed to load BFF module '${filename}':`, err);
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
getHandlerInfos(moduleInfos) {
|
|
149
|
+
let apiHandlers = [];
|
|
150
|
+
moduleInfos.forEach((moduleInfo)=>{
|
|
151
|
+
const handlerInfos = this.getModuleHandlerInfos(moduleInfo);
|
|
152
|
+
if (handlerInfos) apiHandlers = apiHandlers.concat(handlerInfos);
|
|
153
|
+
});
|
|
154
|
+
const sortedHandlers = sortRoutes(apiHandlers);
|
|
155
|
+
return sortedHandlers;
|
|
156
|
+
}
|
|
157
|
+
getModuleHandlerInfos(moduleInfo) {
|
|
158
|
+
const { module, filename } = moduleInfo;
|
|
159
|
+
const { httpMethodDecider } = this;
|
|
160
|
+
return Object.entries(module).filter(([, handler])=>'function' == typeof handler).map(([key])=>{
|
|
161
|
+
const handler = module[key];
|
|
162
|
+
if ('inputParams' === httpMethodDecider) Object.assign(handler, {
|
|
163
|
+
[INPUT_PARAMS_DECIDER]: true
|
|
164
|
+
});
|
|
165
|
+
const handlerInfo = this.getHandlerInfo(filename, key, handler);
|
|
166
|
+
return handlerInfo;
|
|
167
|
+
}).filter((handlerInfo)=>Boolean(handlerInfo));
|
|
168
|
+
}
|
|
169
|
+
validateValidApifile(filename) {
|
|
170
|
+
if (!this.apiFiles.includes(filename)) throw new Error(`The ${filename} is not a valid api file.`);
|
|
171
|
+
}
|
|
172
|
+
getRoutePath(prefix, routeName) {
|
|
173
|
+
const finalRouteName = '/' === routeName ? '' : routeName;
|
|
174
|
+
if ('' === prefix && '' === finalRouteName) return '/';
|
|
175
|
+
return `${prefix}${finalRouteName}`;
|
|
176
|
+
}
|
|
177
|
+
constructor({ appDir, apiDir, lambdaDir, prefix, isBuild, httpMethodDecider = 'functionName' }){
|
|
178
|
+
this.apiFiles = [];
|
|
179
|
+
this.getExactLambdaDir = (apiDir, originLambdaDir)=>originLambdaDir || path.join(apiDir, FRAMEWORK_MODE_LAMBDA_DIR);
|
|
180
|
+
this.validateAbsolute(apiDir, 'apiDir');
|
|
181
|
+
this.validateAbsolute(lambdaDir, 'lambdaDir');
|
|
182
|
+
this.prefix = this.initPrefix(prefix);
|
|
183
|
+
this.appDir = appDir;
|
|
184
|
+
this.apiDir = apiDir;
|
|
185
|
+
this.httpMethodDecider = httpMethodDecider;
|
|
186
|
+
this.isBuild = isBuild;
|
|
187
|
+
this.lambdaDir = this.getExactLambdaDir(this.apiDir, lambdaDir);
|
|
188
|
+
this.existLambdaDir = fs.existsSync(this.lambdaDir);
|
|
189
|
+
debug("apiDir:", this.apiDir, "lambdaDir:", this.lambdaDir);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
export { ApiRouter };
|
|
File without changes
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { compatibleRequire, globby } from "@modern-js/utils";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { INDEX_SUFFIX } from "./constants.mjs";
|
|
4
|
+
const getFiles = (lambdaDir, rules)=>globby.sync(rules, {
|
|
5
|
+
cwd: lambdaDir,
|
|
6
|
+
gitignore: true
|
|
7
|
+
}).map((file)=>path.resolve(lambdaDir, file));
|
|
8
|
+
const getPathFromFilename = (baseDir, filename)=>{
|
|
9
|
+
const relativeName = filename.substring(baseDir.length);
|
|
10
|
+
const relativePath = relativeName.split('.').slice(0, -1).join('.');
|
|
11
|
+
const nameSplit = relativePath.split(path.sep).map((item)=>{
|
|
12
|
+
if (item.length > 2) {
|
|
13
|
+
if (item.startsWith('[') && item.endsWith(']')) return `:${item.substring(1, item.length - 1)}`;
|
|
14
|
+
}
|
|
15
|
+
return item;
|
|
16
|
+
});
|
|
17
|
+
const name = nameSplit.join('/');
|
|
18
|
+
const finalName = name.endsWith(INDEX_SUFFIX) ? name.substring(0, name.length - INDEX_SUFFIX.length) : name;
|
|
19
|
+
return clearRouteName(finalName);
|
|
20
|
+
};
|
|
21
|
+
const clearRouteName = (routeName)=>{
|
|
22
|
+
let finalRouteName = routeName.trim();
|
|
23
|
+
if (!finalRouteName.startsWith('/')) finalRouteName = `/${finalRouteName}`;
|
|
24
|
+
if (finalRouteName.length > 1 && finalRouteName.endsWith('/')) finalRouteName = finalRouteName.substring(0, finalRouteName.length - 1);
|
|
25
|
+
return finalRouteName;
|
|
26
|
+
};
|
|
27
|
+
const isHandler = (input)=>input && 'function' == typeof input;
|
|
28
|
+
const isFunction = (input)=>input && '[object Function]' === ({}).toString.call(input);
|
|
29
|
+
const requireHandlerModule = async (modulePath)=>{
|
|
30
|
+
const module = await compatibleRequire(modulePath, false);
|
|
31
|
+
if (isFunction(module)) return {
|
|
32
|
+
default: module
|
|
33
|
+
};
|
|
34
|
+
return module;
|
|
35
|
+
};
|
|
36
|
+
const routeValue = (routePath)=>{
|
|
37
|
+
if (routePath.includes(':')) return 11;
|
|
38
|
+
return 1;
|
|
39
|
+
};
|
|
40
|
+
const sortRoutes = (apiHandlers)=>apiHandlers.sort((handlerA, handlerB)=>routeValue(handlerA.routeName) - routeValue(handlerB.routeName));
|
|
41
|
+
export { getFiles, getPathFromFilename, isHandler, requireHandlerModule, sortRoutes };
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
|
|
2
|
+
const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
|
|
3
|
+
const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
|
|
4
|
+
const DEFAULT_DENY_STATUS = 403;
|
|
5
|
+
const normalizeHeaderName = (headerName, fallback)=>(headerName || fallback).trim().toLowerCase();
|
|
6
|
+
const normalizeStatusCode = (statusCode)=>{
|
|
7
|
+
if ('number' == typeof statusCode && Number.isFinite(statusCode) && statusCode >= 400 && statusCode <= 599) return Math.floor(statusCode);
|
|
8
|
+
return DEFAULT_DENY_STATUS;
|
|
9
|
+
};
|
|
10
|
+
const readHeader = (headers, headerName)=>{
|
|
11
|
+
const lowerHeaderName = headerName.toLowerCase();
|
|
12
|
+
for (const [name, value] of Object.entries(headers || {}))if (name.toLowerCase() === lowerHeaderName) {
|
|
13
|
+
if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : void 0;
|
|
14
|
+
if (null == value) return;
|
|
15
|
+
return String(value);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
const extractNamespace = (requestId)=>requestId.split(/[/:.]/)[0]?.trim().toLowerCase();
|
|
19
|
+
const createViolation = (reason, message, status)=>({
|
|
20
|
+
code: 'BFF_CROSS_PROJECT_POLICY_DENIED',
|
|
21
|
+
reason,
|
|
22
|
+
message,
|
|
23
|
+
status
|
|
24
|
+
});
|
|
25
|
+
const evaluateCrossProjectPolicy = (headers, policy)=>{
|
|
26
|
+
if (!policy?.enabled) return null;
|
|
27
|
+
const status = normalizeStatusCode(policy.denyStatus);
|
|
28
|
+
const requireEnvelope = policy.requireEnvelope ?? true;
|
|
29
|
+
const requireOperationContext = policy.requireOperationContext ?? true;
|
|
30
|
+
const requireOperationContextDetails = policy.requireOperationContextDetails ?? true;
|
|
31
|
+
const requireOperationSchemaHash = policy.requireOperationSchemaHash ?? true;
|
|
32
|
+
const requireOperationVersion = policy.requireOperationVersion ?? true;
|
|
33
|
+
const allowUnknownOperations = policy.allowUnknownOperations ?? false;
|
|
34
|
+
const envelopeHeader = normalizeHeaderName(policy.envelopeHeader, BFF_ENVELOPE_HEADER);
|
|
35
|
+
const operationContextHeader = normalizeHeaderName(policy.operationContextHeader, BFF_OPERATION_CONTEXT_HEADER);
|
|
36
|
+
const operationContextDetailHeader = normalizeHeaderName(policy.operationContextDetailHeader, BFF_OPERATION_CONTEXT_DETAIL_HEADER);
|
|
37
|
+
const envelopeRaw = readHeader(headers, envelopeHeader);
|
|
38
|
+
if (!envelopeRaw) {
|
|
39
|
+
if (!requireEnvelope) return null;
|
|
40
|
+
return createViolation('missing_envelope', `Missing cross-project envelope header "${envelopeHeader}"`, status);
|
|
41
|
+
}
|
|
42
|
+
let envelope;
|
|
43
|
+
try {
|
|
44
|
+
const parsed = JSON.parse(envelopeRaw);
|
|
45
|
+
if (!parsed || 'object' != typeof parsed) throw new Error('invalid envelope object');
|
|
46
|
+
envelope = parsed;
|
|
47
|
+
} catch (_error) {
|
|
48
|
+
return createViolation('invalid_envelope', `Invalid cross-project envelope header "${envelopeHeader}"`, status);
|
|
49
|
+
}
|
|
50
|
+
const requestId = String(envelope.requestId || '').trim();
|
|
51
|
+
if (!requestId) return createViolation('missing_request_id', 'Cross-project envelope does not include a valid requestId', status);
|
|
52
|
+
const namespaces = (policy.allowedNamespaces || []).map((item)=>item.trim().toLowerCase()).filter(Boolean);
|
|
53
|
+
if (namespaces.length > 0) {
|
|
54
|
+
const namespace = extractNamespace(requestId);
|
|
55
|
+
if (!namespace || !namespaces.includes(namespace)) return createViolation('namespace_not_allowed', `Producer namespace "${namespace || 'unknown'}" is not allowed`, status);
|
|
56
|
+
}
|
|
57
|
+
if (requireOperationContext) {
|
|
58
|
+
const operationContext = readHeader(headers, operationContextHeader);
|
|
59
|
+
if (!operationContext) return createViolation('missing_operation_context', `Missing operation context header "${operationContextHeader}"`, status);
|
|
60
|
+
if (!operationContext.startsWith(`${requestId}:`)) return createViolation('operation_context_mismatch', `Operation context header "${operationContextHeader}" does not match requestId "${requestId}"`, status);
|
|
61
|
+
const operationContextDetailsRaw = readHeader(headers, operationContextDetailHeader);
|
|
62
|
+
if (!operationContextDetailsRaw) {
|
|
63
|
+
if (requireOperationContextDetails) return createViolation('missing_operation_context_details', `Missing operation context details header "${operationContextDetailHeader}"`, status);
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
let operationContextDetails;
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(operationContextDetailsRaw);
|
|
69
|
+
if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) throw new Error('invalid operation context details object');
|
|
70
|
+
operationContextDetails = parsed;
|
|
71
|
+
} catch (_error) {
|
|
72
|
+
return createViolation('invalid_operation_context_details', `Invalid operation context details header "${operationContextDetailHeader}"`, status);
|
|
73
|
+
}
|
|
74
|
+
const detailRequestId = String(operationContextDetails.requestId || '').trim();
|
|
75
|
+
if (detailRequestId && detailRequestId !== requestId) return createViolation('operation_context_details_request_id_mismatch', `Operation context details requestId "${detailRequestId}" does not match envelope requestId "${requestId}"`, status);
|
|
76
|
+
const detailSchemaHash = String(operationContextDetails.schemaHash || '').trim();
|
|
77
|
+
if (requireOperationSchemaHash && !detailSchemaHash) return createViolation('missing_operation_schema_hash', `Operation context details header "${operationContextDetailHeader}" must include schemaHash`, status);
|
|
78
|
+
const detailOperationVersion = operationContextDetails.operationVersion;
|
|
79
|
+
if (requireOperationVersion && 'number' != typeof detailOperationVersion) return createViolation('missing_operation_version', `Operation context details header "${operationContextDetailHeader}" must include operationVersion`, status);
|
|
80
|
+
const expectedContracts = policy.expectedOperationContracts;
|
|
81
|
+
if (expectedContracts && 'object' == typeof expectedContracts && Object.keys(expectedContracts).length > 0) {
|
|
82
|
+
const method = String(operationContextDetails.method || '').toUpperCase();
|
|
83
|
+
const routePath = String(operationContextDetails.routePath || '').trim();
|
|
84
|
+
const operationId = String(operationContextDetails.operationId || '').trim();
|
|
85
|
+
const expectedContract = expectedContracts[`${method}:${routePath}`] || expectedContracts[`operation:${operationId}`];
|
|
86
|
+
if (expectedContract) {
|
|
87
|
+
if (expectedContract.schemaHash && detailSchemaHash && expectedContract.schemaHash !== detailSchemaHash) return createViolation('operation_schema_hash_mismatch', `Operation schema hash mismatch for "${operationId || `${method}:${routePath}`}"`, status);
|
|
88
|
+
if ('number' == typeof expectedContract.operationVersion && 'number' == typeof detailOperationVersion && expectedContract.operationVersion !== detailOperationVersion) return createViolation('operation_version_mismatch', `Operation version mismatch for "${operationId || `${method}:${routePath}`}"`, status);
|
|
89
|
+
} else if (!allowUnknownOperations) return createViolation('unknown_operation_contract', `No expected operation contract found for operation "${operationId || `${method}:${routePath}`}"`, status);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
};
|
|
94
|
+
export { BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER, evaluateCrossProjectPolicy };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { createHash } from "crypto";
|
|
2
|
+
const DEFAULT_OPERATION_VERSION = 1;
|
|
3
|
+
const createOperationEntries = (handlers)=>handlers.map((item)=>({
|
|
4
|
+
name: item.name,
|
|
5
|
+
httpMethod: String(item.httpMethod || '').toUpperCase(),
|
|
6
|
+
routePath: item.routePath
|
|
7
|
+
})).sort((a, b)=>{
|
|
8
|
+
const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
|
|
9
|
+
const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
|
|
10
|
+
return keyA.localeCompare(keyB);
|
|
11
|
+
});
|
|
12
|
+
const createOperationSchemaHash = (operationEntries, requestId)=>createHash('sha256').update(JSON.stringify({
|
|
13
|
+
operations: operationEntries.map((item)=>({
|
|
14
|
+
name: item.name,
|
|
15
|
+
httpMethod: item.httpMethod,
|
|
16
|
+
routePath: item.routePath
|
|
17
|
+
})),
|
|
18
|
+
requestId
|
|
19
|
+
})).digest('hex');
|
|
20
|
+
const buildOperationContractMap = ({ handlers, requestId })=>{
|
|
21
|
+
const normalizedRequestId = 'string' == typeof requestId && requestId.trim().length > 0 ? requestId.trim() : 'default';
|
|
22
|
+
const byModule = new Map();
|
|
23
|
+
handlers.forEach((item)=>{
|
|
24
|
+
const moduleId = 'string' == typeof item.filename && item.filename.length > 0 ? item.filename : '__anonymous__';
|
|
25
|
+
const group = byModule.get(moduleId) || [];
|
|
26
|
+
group.push({
|
|
27
|
+
name: item.name,
|
|
28
|
+
httpMethod: item.httpMethod.toUpperCase(),
|
|
29
|
+
routePath: item.routePath,
|
|
30
|
+
filename: item.filename
|
|
31
|
+
});
|
|
32
|
+
byModule.set(moduleId, group);
|
|
33
|
+
});
|
|
34
|
+
const contracts = {};
|
|
35
|
+
byModule.forEach((moduleEntries)=>{
|
|
36
|
+
const entries = createOperationEntries(moduleEntries);
|
|
37
|
+
const schemaHash = createOperationSchemaHash(entries, normalizedRequestId);
|
|
38
|
+
const filename = moduleEntries[0]?.filename;
|
|
39
|
+
entries.forEach((entry)=>{
|
|
40
|
+
const operationId = `${normalizedRequestId}:${entry.name}`;
|
|
41
|
+
const contract = {
|
|
42
|
+
requestId: normalizedRequestId,
|
|
43
|
+
operationVersion: DEFAULT_OPERATION_VERSION,
|
|
44
|
+
schemaHash,
|
|
45
|
+
method: entry.httpMethod,
|
|
46
|
+
routePath: entry.routePath,
|
|
47
|
+
operationId,
|
|
48
|
+
handlerName: entry.name,
|
|
49
|
+
filename
|
|
50
|
+
};
|
|
51
|
+
contracts[`${entry.httpMethod}:${entry.routePath}`] = contract;
|
|
52
|
+
contracts[`operation:${operationId}`] = contract;
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
return contracts;
|
|
56
|
+
};
|
|
57
|
+
export { DEFAULT_OPERATION_VERSION, buildOperationContractMap, createOperationEntries, createOperationSchemaHash };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
var types_OperatorType = /*#__PURE__*/ function(OperatorType) {
|
|
2
|
+
OperatorType[OperatorType["Trigger"] = 0] = "Trigger";
|
|
3
|
+
OperatorType[OperatorType["Middleware"] = 1] = "Middleware";
|
|
4
|
+
return OperatorType;
|
|
5
|
+
}({});
|
|
6
|
+
var types_TriggerType = /*#__PURE__*/ function(TriggerType) {
|
|
7
|
+
TriggerType[TriggerType["Http"] = 0] = "Http";
|
|
8
|
+
return TriggerType;
|
|
9
|
+
}({});
|
|
10
|
+
var types_HttpMetadata = /*#__PURE__*/ function(HttpMetadata) {
|
|
11
|
+
HttpMetadata["Method"] = "METHOD";
|
|
12
|
+
HttpMetadata["Data"] = "DATA";
|
|
13
|
+
HttpMetadata["Query"] = "QUERY";
|
|
14
|
+
HttpMetadata["Params"] = "PARAMS";
|
|
15
|
+
HttpMetadata["Headers"] = "HEADERS";
|
|
16
|
+
HttpMetadata["Response"] = "RESPONSE";
|
|
17
|
+
HttpMetadata["Files"] = "Files";
|
|
18
|
+
return HttpMetadata;
|
|
19
|
+
}({});
|
|
20
|
+
var types_ResponseMetaType = /*#__PURE__*/ function(ResponseMetaType) {
|
|
21
|
+
ResponseMetaType[ResponseMetaType["StatusCode"] = 0] = "StatusCode";
|
|
22
|
+
ResponseMetaType[ResponseMetaType["Redirect"] = 1] = "Redirect";
|
|
23
|
+
ResponseMetaType[ResponseMetaType["Headers"] = 2] = "Headers";
|
|
24
|
+
return ResponseMetaType;
|
|
25
|
+
}({});
|
|
26
|
+
var types_HttpMethod = /*#__PURE__*/ function(HttpMethod) {
|
|
27
|
+
HttpMethod["Get"] = "GET";
|
|
28
|
+
HttpMethod["Post"] = "POST";
|
|
29
|
+
HttpMethod["Put"] = "PUT";
|
|
30
|
+
HttpMethod["Delete"] = "DELETE";
|
|
31
|
+
HttpMethod["Connect"] = "CONNECT";
|
|
32
|
+
HttpMethod["Trace"] = "TRACE";
|
|
33
|
+
HttpMethod["Patch"] = "PATCH";
|
|
34
|
+
HttpMethod["Options"] = "OPTIONS";
|
|
35
|
+
HttpMethod["Head"] = "HEAD";
|
|
36
|
+
return HttpMethod;
|
|
37
|
+
}({});
|
|
38
|
+
const httpMethods = Object.values(types_HttpMethod);
|
|
39
|
+
export { httpMethods, types_HttpMetadata as HttpMetadata, types_HttpMethod as HttpMethod, types_OperatorType as OperatorType, types_ResponseMetaType as ResponseMetaType, types_TriggerType as TriggerType };
|