@faapi/faapi 0.0.0-canary.0f443f9 → 0.0.0-canary.22b65a2

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/dist/index.js CHANGED
@@ -1,6 +1,135 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/utils/isPlainObject.ts
12
+ function isPlainObject(value) {
13
+ if (value === null || typeof value !== "object") {
14
+ return false;
15
+ }
16
+ if (Array.isArray(value)) {
17
+ return false;
18
+ }
19
+ const proto = Object.getPrototypeOf(value);
20
+ return proto === null || proto === Object.prototype;
21
+ }
22
+ var init_isPlainObject = __esm({
23
+ "src/utils/isPlainObject.ts"() {
24
+ "use strict";
25
+ }
26
+ });
27
+
28
+ // src/response/toResponse.ts
29
+ var toResponse_exports = {};
30
+ __export(toResponse_exports, {
31
+ toResponse: () => toResponse
32
+ });
33
+ async function toResponse(value, meta) {
34
+ if (value instanceof Promise) {
35
+ return toResponse(await value, meta);
36
+ }
37
+ const applyMeta = (headers2) => {
38
+ if (!meta) return;
39
+ for (const [key, val] of Object.entries(meta.headers)) {
40
+ headers2.set(key, val);
41
+ }
42
+ for (const cookie of meta.setCookies ?? []) {
43
+ headers2.append("set-cookie", cookie);
44
+ }
45
+ };
46
+ if (value instanceof Response) {
47
+ if (meta && (meta.status !== void 0 || Object.keys(meta.headers).length > 0 || meta.setCookies.length > 0)) {
48
+ const headers2 = new Headers(value.headers);
49
+ applyMeta(headers2);
50
+ return new Response(value.body, {
51
+ status: meta.status ?? value.status,
52
+ headers: headers2
53
+ });
54
+ }
55
+ return value;
56
+ }
57
+ if (value === null || value === void 0) {
58
+ const status = meta?.status ?? 204;
59
+ const headers2 = new Headers();
60
+ applyMeta(headers2);
61
+ return new Response(null, { status, headers: headers2 });
62
+ }
63
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
64
+ const headers2 = new Headers({ "Content-Type": "application/octet-stream" });
65
+ applyMeta(headers2);
66
+ return new Response(value, {
67
+ status: meta?.status ?? 200,
68
+ headers: headers2
69
+ });
70
+ }
71
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) {
72
+ const headers2 = new Headers({ "Content-Type": "application/octet-stream" });
73
+ applyMeta(headers2);
74
+ return new Response(value, {
75
+ status: meta?.status ?? 200,
76
+ headers: headers2
77
+ });
78
+ }
79
+ if (value instanceof Uint8Array) {
80
+ const headers2 = new Headers({ "Content-Type": "application/octet-stream" });
81
+ applyMeta(headers2);
82
+ return new Response(value, {
83
+ status: meta?.status ?? 200,
84
+ headers: headers2
85
+ });
86
+ }
87
+ if (isPlainObject(value) || Array.isArray(value)) {
88
+ const body2 = JSON.stringify(value);
89
+ const headers2 = new Headers({ "Content-Type": "application/json" });
90
+ applyMeta(headers2);
91
+ return new Response(body2, {
92
+ status: meta?.status ?? 200,
93
+ headers: headers2
94
+ });
95
+ }
96
+ if (typeof value === "string") {
97
+ const headers2 = new Headers({ "Content-Type": "text/plain" });
98
+ applyMeta(headers2);
99
+ return new Response(value, {
100
+ status: meta?.status ?? 200,
101
+ headers: headers2
102
+ });
103
+ }
104
+ if (typeof value === "number" || typeof value === "boolean") {
105
+ const headers2 = new Headers({ "Content-Type": "text/plain" });
106
+ applyMeta(headers2);
107
+ return new Response(String(value), {
108
+ status: meta?.status ?? 200,
109
+ headers: headers2
110
+ });
111
+ }
112
+ const body = JSON.stringify(value);
113
+ const headers = new Headers({ "Content-Type": "application/json" });
114
+ applyMeta(headers);
115
+ return new Response(body, {
116
+ status: meta?.status ?? 200,
117
+ headers
118
+ });
119
+ }
120
+ var init_toResponse = __esm({
121
+ "src/response/toResponse.ts"() {
122
+ "use strict";
123
+ init_isPlainObject();
124
+ }
125
+ });
126
+
1
127
  // src/ast/createProgram.ts
2
128
  import ts from "typescript";
3
129
  var programCache = /* @__PURE__ */ new Map();
130
+ function invalidateProgramCache() {
131
+ programCache.clear();
132
+ }
4
133
  function createProgram(filePath) {
5
134
  const cached = programCache.get(filePath);
6
135
  if (cached) {
@@ -417,6 +546,45 @@ function extractTypeInfo(program, filePath, typeName) {
417
546
  });
418
547
  return result;
419
548
  }
549
+ function extractAllTypes(program, filePath) {
550
+ const sourceFile = program.getSourceFile(filePath);
551
+ if (!sourceFile) return /* @__PURE__ */ new Map();
552
+ const checker = program.getTypeChecker();
553
+ const result = /* @__PURE__ */ new Map();
554
+ ts3.forEachChild(sourceFile, (node) => {
555
+ if (ts3.isInterfaceDeclaration(node)) {
556
+ const visited = /* @__PURE__ */ new Set();
557
+ visited.add(node.name.text);
558
+ const runtimeType = withFileContext(
559
+ filePath,
560
+ node.name.text,
561
+ () => resolveInterfaceDeclaration(node, checker, visited)
562
+ );
563
+ result.set(node.name.text, {
564
+ name: node.name.text,
565
+ properties: runtimeType.kind === "object" ? runtimeType.properties : [],
566
+ runtimeType
567
+ });
568
+ return;
569
+ }
570
+ if (ts3.isTypeAliasDeclaration(node)) {
571
+ const visited = /* @__PURE__ */ new Set();
572
+ visited.add(node.name.text);
573
+ const runtimeType = withFileContext(
574
+ filePath,
575
+ node.name.text,
576
+ () => resolveTypeNode(node.type, checker, visited)
577
+ );
578
+ result.set(node.name.text, {
579
+ name: node.name.text,
580
+ properties: runtimeType.kind === "object" ? runtimeType.properties : [],
581
+ runtimeType
582
+ });
583
+ return;
584
+ }
585
+ });
586
+ return result;
587
+ }
420
588
  function withFileContext(filePath, typeName, fn) {
421
589
  try {
422
590
  return fn();
@@ -442,122 +610,187 @@ function getInputTypeForMethod(method) {
442
610
  }
443
611
  return "body";
444
612
  }
613
+ function hasBody(method) {
614
+ const upper = method.toUpperCase();
615
+ return upper === "POST" || upper === "PUT" || upper === "PATCH" || upper === "DELETE";
616
+ }
445
617
 
446
- // src/validator/schemaRegistry.ts
447
- var SchemaRegistry = class {
448
- manifest = /* @__PURE__ */ new Map();
449
- /**
450
- * 批量加载 manifest
451
- * 覆盖已有数据
452
- */
453
- loadManifest(manifest) {
454
- this.manifest.clear();
455
- for (const [filePath, fileSchemas] of manifest) {
456
- const copy = /* @__PURE__ */ new Map();
457
- fileSchemas.forEach((value, key) => copy.set(key, value));
458
- this.manifest.set(filePath, copy);
618
+ // src/validator/schemaName.ts
619
+ function getSchemaName(method, inputType) {
620
+ return `${method.toUpperCase()}${inputType.charAt(0).toUpperCase() + inputType.slice(1)}`;
621
+ }
622
+
623
+ // src/injection/analyzeInjection.ts
624
+ import ts5 from "typescript";
625
+
626
+ // src/injection/resolveInjection.ts
627
+ import ts4 from "typescript";
628
+ var PARAM_TYPE_MAP = {
629
+ query: "query",
630
+ body: "body",
631
+ headers: "headers",
632
+ params: "params",
633
+ context: "context",
634
+ ctx: "context",
635
+ // 别名
636
+ cookies: "cookies",
637
+ ip: "ip",
638
+ files: "files",
639
+ fields: "fields"
640
+ };
641
+ function resolveInjection(fn) {
642
+ const fnStr = fn.toString();
643
+ const params = extractParamsWithAst(fnStr);
644
+ return params.map((param) => {
645
+ const type = PARAM_TYPE_MAP[param.name] || "unknown";
646
+ return {
647
+ name: param.name,
648
+ type,
649
+ hasType: false
650
+ // 运行时类型已擦除
651
+ };
652
+ });
653
+ }
654
+ function extractParamsWithAst(fnStr) {
655
+ const sourceFile = ts4.createSourceFile(
656
+ "__faapi_injection__.ts",
657
+ fnStr,
658
+ ts4.ScriptTarget.Latest,
659
+ true
660
+ );
661
+ const paramNames = [];
662
+ function visit(node) {
663
+ if (ts4.isFunctionDeclaration(node) && node.parameters.length > 0) {
664
+ for (const param of node.parameters) {
665
+ extractParamName(param, paramNames);
666
+ }
667
+ return;
459
668
  }
669
+ if ((ts4.isArrowFunction(node) || ts4.isFunctionExpression(node)) && node.parameters.length > 0) {
670
+ for (const param of node.parameters) {
671
+ extractParamName(param, paramNames);
672
+ }
673
+ return;
674
+ }
675
+ ts4.forEachChild(node, visit);
460
676
  }
461
- /**
462
- * 查询单条 schema
463
- * @returns SchemaEntry | null | undefined
464
- * - SchemaEntry:有类型声明
465
- * - null:无类型声明(跳过校验)
466
- * - undefined:manifest 不完整(抛错)
467
- */
468
- get(filePath, schemaName) {
469
- const fileSchemas = this.manifest.get(filePath);
470
- if (!fileSchemas) return void 0;
471
- return fileSchemas.get(schemaName);
472
- }
473
- /**
474
- * 设置单个文件的所有 schema
475
- * 覆盖该文件的已有数据
476
- */
477
- set(filePath, schemas) {
478
- const copy = /* @__PURE__ */ new Map();
479
- schemas.forEach((value, key) => copy.set(key, value));
480
- this.manifest.set(filePath, copy);
677
+ visit(sourceFile);
678
+ return paramNames.map((name) => ({ name }));
679
+ }
680
+ function extractParamName(param, names) {
681
+ const name = param.name;
682
+ if (ts4.isIdentifier(name)) {
683
+ names.push(name.text);
684
+ return;
481
685
  }
482
- /**
483
- * 删除单个文件(文件被删除时)
484
- */
485
- delete(filePath) {
486
- this.manifest.delete(filePath);
686
+ if (ts4.isObjectBindingPattern(name)) {
687
+ for (const element of name.elements) {
688
+ if (ts4.isBindingElement(element)) {
689
+ const elemName = element.name;
690
+ if (ts4.isIdentifier(elemName)) {
691
+ names.push(elemName.text);
692
+ }
693
+ }
694
+ }
695
+ return;
487
696
  }
488
- /**
489
- * 判断文件是否已注册
490
- */
491
- hasFile(filePath) {
492
- return this.manifest.has(filePath);
697
+ if (ts4.isArrayBindingPattern(name)) {
698
+ for (const element of name.elements) {
699
+ if (element && ts4.isBindingElement(element)) {
700
+ const elemName = element.name;
701
+ if (ts4.isIdentifier(elemName)) {
702
+ names.push(elemName.text);
703
+ }
704
+ }
705
+ }
706
+ return;
493
707
  }
494
- /**
495
- * 清空(测试用 / watch 全量重建前)
496
- */
497
- clear() {
498
- this.manifest.clear();
708
+ }
709
+
710
+ // src/injection/analyzeInjection.ts
711
+ function analyzeInjection(code, functionName) {
712
+ const sourceFile = ts5.createSourceFile("temp.ts", code, ts5.ScriptTarget.Latest, true);
713
+ const params = [];
714
+ ts5.forEachChild(sourceFile, (node) => {
715
+ if (ts5.isFunctionDeclaration(node) && node.name?.text === functionName) {
716
+ for (const param of node.parameters) {
717
+ const paramMeta = analyzeParam(param, sourceFile);
718
+ params.push(paramMeta);
719
+ }
720
+ }
721
+ });
722
+ return { params };
723
+ }
724
+ function analyzeParam(param, sourceFile) {
725
+ const name = param.name.getText(sourceFile);
726
+ const type = PARAM_TYPE_MAP[name] || "unknown";
727
+ const result = { name, type };
728
+ if (param.type) {
729
+ if (ts5.isTypeReferenceNode(param.type)) {
730
+ result.typeName = param.type.typeName.getText(sourceFile);
731
+ } else if (ts5.isTypeLiteralNode(param.type)) {
732
+ result.schema = extractSchema(param.type, sourceFile);
733
+ }
499
734
  }
500
- /**
501
- * 已注册的文件数量
502
- */
503
- get size() {
504
- return this.manifest.size;
735
+ return result;
736
+ }
737
+ function extractSchema(typeNode, sourceFile) {
738
+ const schema = [];
739
+ for (const member of typeNode.members) {
740
+ if (ts5.isPropertySignature(member) && member.name && ts5.isIdentifier(member.name)) {
741
+ const propName = member.name.text;
742
+ const optional = !!member.questionToken;
743
+ const propType = member.type?.getText(sourceFile) || "unknown";
744
+ schema.push({
745
+ name: propName,
746
+ type: propType,
747
+ optional
748
+ });
749
+ }
505
750
  }
506
- };
507
- var schemaRegistry = new SchemaRegistry();
508
-
509
- // src/validator/schemaName.ts
510
- function getSchemaName(method, inputType) {
511
- return `${method.toUpperCase()}${inputType.charAt(0).toUpperCase() + inputType.slice(1)}`;
751
+ return schema;
512
752
  }
513
753
 
514
- // src/validator/getSchemaProperties.ts
515
- function getSchemaProperties(filePath, method, inputType) {
516
- const schemaName = getSchemaName(method, inputType);
517
- const entry = schemaRegistry.get(filePath, schemaName);
518
- if (entry === void 0) return void 0;
519
- if (entry === null) {
520
- return { schemaName: null, properties: [] };
754
+ // src/cli/collectRouteSchemaSources.ts
755
+ import path from "path";
756
+ function collectRouteSchemaSources(routes, rootDir) {
757
+ const methodsByFile = /* @__PURE__ */ new Map();
758
+ for (const route of routes) {
759
+ const filePath = rootDir ? path.resolve(rootDir, route.filePath) : route.filePath;
760
+ let entry = methodsByFile.get(filePath);
761
+ if (!entry) {
762
+ entry = { urlPath: route.urlPath, methods: /* @__PURE__ */ new Set() };
763
+ methodsByFile.set(filePath, entry);
764
+ }
765
+ entry.methods.add(route.method);
521
766
  }
522
- return {
523
- schemaName,
524
- properties: entry.properties.map((prop) => ({
525
- name: prop.name,
526
- type: runtimeTypeToString(prop.type),
527
- required: !prop.optional
528
- }))
529
- };
530
- }
531
- function runtimeTypeToString(type) {
532
- switch (type.kind) {
533
- case "string":
534
- case "number":
535
- case "boolean":
536
- case "bigint":
537
- case "null":
538
- case "undefined":
539
- case "date":
540
- return type.kind;
541
- case "literal":
542
- return JSON.stringify(type.value);
543
- case "array":
544
- return `${runtimeTypeToString(type.element)}[]`;
545
- case "tuple":
546
- return `[${type.elements.map((e) => (e.rest ? "..." : "") + runtimeTypeToString(e.type) + (e.optional ? "?" : "")).join(", ")}]`;
547
- case "object":
548
- return "object";
549
- case "union":
550
- return type.members.map(runtimeTypeToString).join(" | ");
551
- case "record":
552
- return `Record<${runtimeTypeToString(type.key)}, ${runtimeTypeToString(type.value)}>`;
553
- case "ref":
554
- return type.name;
555
- case "any":
556
- case "unknown":
557
- return "unknown";
558
- default:
559
- return "unknown";
767
+ const programByFile = /* @__PURE__ */ new Map();
768
+ const allTypesByFile = /* @__PURE__ */ new Map();
769
+ const mergedAllTypes = /* @__PURE__ */ new Map();
770
+ for (const filePath of methodsByFile.keys()) {
771
+ const program = createProgram(filePath);
772
+ programByFile.set(filePath, program);
773
+ const allTypes = extractAllTypes(program, filePath);
774
+ allTypesByFile.set(filePath, allTypes);
775
+ for (const [name, info] of allTypes) {
776
+ mergedAllTypes.set(name, info);
777
+ }
778
+ }
779
+ const sources = [];
780
+ for (const [filePath, entry] of methodsByFile) {
781
+ const program = programByFile.get(filePath);
782
+ const sourceFile = program.getSourceFile(filePath);
783
+ const code = sourceFile?.text ?? "";
784
+ for (const method of entry.methods) {
785
+ const inputType = getInputTypeForMethod(method);
786
+ const schemaName = getSchemaName(method, inputType);
787
+ const meta = analyzeInjection(code, method);
788
+ const param = meta.params.find((p) => p.type === inputType);
789
+ const typeInfo = param?.typeName ? extractTypeInfo(program, filePath, param.typeName) : null;
790
+ sources.push({ urlPath: entry.urlPath, filePath, schemaName, typeInfo });
791
+ }
560
792
  }
793
+ return { sources, allTypesByFile, mergedAllTypes };
561
794
  }
562
795
 
563
796
  // src/middleware/cors.ts
@@ -633,96 +866,2307 @@ function logger(options = {}) {
633
866
  try {
634
867
  const response = await next();
635
868
  const duration = Date.now() - start;
636
- log(`${ctx.method} ${ctx.path} ${response.status} ${duration}ms`);
869
+ const entry = {
870
+ method: ctx.method,
871
+ path: ctx.path,
872
+ status: response.status,
873
+ durationMs: duration
874
+ };
875
+ log(entry, `${ctx.method} ${ctx.path} ${response.status} ${duration}ms`);
637
876
  return response;
638
877
  } catch (err) {
639
878
  const duration = Date.now() - start;
640
879
  const message = err instanceof Error ? err.message : String(err);
641
880
  const status = err?.statusCode ?? 500;
642
- log(`${ctx.method} ${ctx.path} ${status} ${duration}ms - ${message}`);
881
+ const entry = {
882
+ method: ctx.method,
883
+ path: ctx.path,
884
+ status,
885
+ durationMs: duration,
886
+ error: message
887
+ };
888
+ log(entry, `${ctx.method} ${ctx.path} ${status} ${duration}ms - ${message}`);
643
889
  throw err;
644
890
  }
645
891
  };
646
892
  }
647
893
 
894
+ // src/middleware/helmet.ts
895
+ var DEFAULTS = {
896
+ contentSecurityPolicy: "default-src 'self'",
897
+ xFrameOptions: "SAMEORIGIN",
898
+ xContentTypeOptions: true,
899
+ referrerPolicy: "no-referrer",
900
+ strictTransportSecurity: "max-age=31536000; includeSubDomains",
901
+ xDnsPrefetchControl: true,
902
+ xDownloadOptions: true,
903
+ xPermittedCrossDomainPolicies: "none",
904
+ crossOriginOpenerPolicy: "same-origin",
905
+ crossOriginResourcePolicy: "same-origin",
906
+ crossOriginEmbedderPolicy: false,
907
+ originAgentCluster: true,
908
+ xPoweredBy: true
909
+ };
910
+ function helmet(options = {}) {
911
+ const opts = { ...DEFAULTS, ...options };
912
+ return async (ctx, next) => {
913
+ if (opts.contentSecurityPolicy !== false) {
914
+ ctx.setHeader("Content-Security-Policy", opts.contentSecurityPolicy);
915
+ }
916
+ if (opts.xFrameOptions !== false) {
917
+ ctx.setHeader("X-Frame-Options", opts.xFrameOptions);
918
+ }
919
+ if (opts.xContentTypeOptions) {
920
+ ctx.setHeader("X-Content-Type-Options", "nosniff");
921
+ }
922
+ if (opts.referrerPolicy !== false) {
923
+ ctx.setHeader("Referrer-Policy", opts.referrerPolicy);
924
+ }
925
+ if (opts.strictTransportSecurity !== false) {
926
+ ctx.setHeader("Strict-Transport-Security", opts.strictTransportSecurity);
927
+ }
928
+ if (opts.xDnsPrefetchControl) {
929
+ ctx.setHeader("X-DNS-Prefetch-Control", "off");
930
+ }
931
+ if (opts.xDownloadOptions) {
932
+ ctx.setHeader("X-Download-Options", "noopen");
933
+ }
934
+ if (opts.xPermittedCrossDomainPolicies !== false) {
935
+ ctx.setHeader("X-Permitted-Cross-Domain-Policies", opts.xPermittedCrossDomainPolicies);
936
+ }
937
+ if (opts.crossOriginOpenerPolicy !== false) {
938
+ ctx.setHeader("Cross-Origin-Opener-Policy", opts.crossOriginOpenerPolicy);
939
+ }
940
+ if (opts.crossOriginResourcePolicy !== false) {
941
+ ctx.setHeader("Cross-Origin-Resource-Policy", opts.crossOriginResourcePolicy);
942
+ }
943
+ if (opts.crossOriginEmbedderPolicy !== false) {
944
+ ctx.setHeader("Cross-Origin-Embedder-Policy", opts.crossOriginEmbedderPolicy);
945
+ }
946
+ if (opts.originAgentCluster) {
947
+ ctx.setHeader("Origin-Agent-Cluster", "?1");
948
+ }
949
+ if (opts.xPoweredBy) {
950
+ ctx.setHeader("X-Powered-By", "faapi");
951
+ }
952
+ return await next();
953
+ };
954
+ }
955
+
648
956
  // src/config/loadConfig.ts
649
- import path from "path";
957
+ import path2 from "path";
650
958
  import fs from "fs";
959
+
960
+ // src/utils/importWithCacheBust.ts
651
961
  import { pathToFileURL } from "url";
652
- var BASE_CONFIG_FILES = ["faapi.config.ts", "faapi.config.js"];
653
- function getEnv() {
654
- return process.env.NODE_ENV || process.env.FAAPI_ENV || "development";
655
- }
656
- function deepMerge(base, override) {
657
- const result = { ...base };
658
- for (const key of Object.keys(override)) {
659
- const baseVal = base[key];
660
- const overVal = override[key];
661
- if (baseVal instanceof Date || overVal instanceof Date || baseVal instanceof RegExp || overVal instanceof RegExp || baseVal instanceof Map || overVal instanceof Map || baseVal instanceof Set || overVal instanceof Set) {
662
- result[key] = overVal;
663
- continue;
962
+ var loadTs;
963
+ function setLoadTimestamp(ts6) {
964
+ loadTs = ts6;
965
+ }
966
+ async function importWithCacheBust(filePath) {
967
+ let url = pathToFileURL(filePath).href;
968
+ if (loadTs !== void 0) {
969
+ url += `?t=${loadTs}`;
970
+ }
971
+ return await import(url);
972
+ }
973
+
974
+ // src/config/loadConfig.ts
975
+ var CONFIG_PRODUCT_FILE = "faapi-config.js";
976
+ async function loadConfig(rootDir, outDir) {
977
+ const configProductPath = path2.resolve(rootDir, outDir, CONFIG_PRODUCT_FILE);
978
+ if (fs.existsSync(configProductPath)) {
979
+ const module = await importWithCacheBust(configProductPath);
980
+ return module.default ?? {};
981
+ }
982
+ const hasSourceConfig = fs.existsSync(path2.join(rootDir, "faapi.config.ts")) || fs.existsSync(path2.join(rootDir, "faapi.config.js"));
983
+ if (hasSourceConfig) {
984
+ throw new Error(
985
+ `[faapi] ${outDir}/${CONFIG_PRODUCT_FILE} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6267\u884C \`faapi build\`\uFF08\u6216 \`faapi dev\`\uFF09\u751F\u6210\u4EA7\u7269\u3002`
986
+ );
987
+ }
988
+ return null;
989
+ }
990
+
991
+ // src/cli/createAppCore.ts
992
+ import fs4 from "fs";
993
+ import path7 from "path";
994
+ import { PassThrough } from "stream";
995
+
996
+ // src/router/sortRoutes.ts
997
+ function sortRoutes(routes) {
998
+ return [...routes].sort((a, b) => {
999
+ if (a.isDynamic !== b.isDynamic) {
1000
+ return a.isDynamic ? 1 : -1;
664
1001
  }
665
- if (baseVal !== null && overVal !== null && typeof baseVal === "object" && typeof overVal === "object" && !Array.isArray(baseVal) && !Array.isArray(overVal) && !(baseVal instanceof Function) && !(overVal instanceof Function)) {
666
- result[key] = deepMerge(
667
- baseVal,
668
- overVal
669
- );
1002
+ if (a.isCatchAll !== b.isCatchAll) {
1003
+ return a.isCatchAll ? 1 : -1;
1004
+ }
1005
+ const aSegments = a.urlPath.split("/").filter(Boolean).length;
1006
+ const bSegments = b.urlPath.split("/").filter(Boolean).length;
1007
+ if (aSegments !== bSegments) {
1008
+ return aSegments - bSegments;
1009
+ }
1010
+ return a.urlPath.localeCompare(b.urlPath);
1011
+ });
1012
+ }
1013
+
1014
+ // src/router/detectRouteConflicts.ts
1015
+ function detectRouteConflicts(routes) {
1016
+ const map = /* @__PURE__ */ new Map();
1017
+ for (const route of routes) {
1018
+ const key = `${route.method} ${route.urlPath}`;
1019
+ const existing = map.get(key);
1020
+ if (existing) {
1021
+ existing.files.push(route.filePath);
670
1022
  } else {
671
- result[key] = overVal;
1023
+ map.set(key, {
1024
+ method: route.method,
1025
+ urlPath: route.urlPath,
1026
+ files: [route.filePath]
1027
+ });
672
1028
  }
673
1029
  }
674
- return result;
1030
+ const conflicts = [];
1031
+ for (const conflict of map.values()) {
1032
+ if (conflict.files.length > 1) {
1033
+ conflicts.push(conflict);
1034
+ }
1035
+ }
1036
+ return conflicts;
1037
+ }
1038
+
1039
+ // src/server/createServer.ts
1040
+ import {
1041
+ createServer as createHttpServer
1042
+ } from "http";
1043
+ import { createSecureServer as createHttp2SecureServer } from "http2";
1044
+ import { readFileSync } from "fs";
1045
+ import { Readable as Readable2 } from "stream";
1046
+ import path5 from "path";
1047
+
1048
+ // src/router/matchRoute.ts
1049
+ function matchRoute(routes, method, path9) {
1050
+ for (const route of routes) {
1051
+ if (route.method !== method) {
1052
+ continue;
1053
+ }
1054
+ if (!route.isDynamic) {
1055
+ if (route.urlPath === path9) {
1056
+ return { route, params: {} };
1057
+ }
1058
+ continue;
1059
+ }
1060
+ const params = matchDynamicPath(route.urlPath, path9, route.paramNames, route.isCatchAll);
1061
+ if (params !== null) {
1062
+ return { route, params };
1063
+ }
1064
+ }
1065
+ return null;
1066
+ }
1067
+ function matchWsRoute(wsRoutes, path9) {
1068
+ for (const route of wsRoutes) {
1069
+ if (!route.isDynamic) {
1070
+ if (route.urlPath === path9) {
1071
+ return { route, params: {} };
1072
+ }
1073
+ continue;
1074
+ }
1075
+ const params = matchDynamicPath(route.urlPath, path9, route.paramNames, route.isCatchAll);
1076
+ if (params !== null) {
1077
+ return { route, params };
1078
+ }
1079
+ }
1080
+ return null;
675
1081
  }
676
- async function loadConfigFile(filePath) {
677
- if (!fs.existsSync(filePath)) {
1082
+ function matchDynamicPath(pattern, path9, paramNames, isCatchAll) {
1083
+ const patternSegments = pattern.split("/").filter(Boolean);
1084
+ const pathSegments = path9.split("/").filter(Boolean);
1085
+ if (isCatchAll) {
1086
+ const nonCatchAllCount = patternSegments.length - 1;
1087
+ if (pathSegments.length <= nonCatchAllCount) {
1088
+ return null;
1089
+ }
1090
+ const params2 = {};
1091
+ for (let i = 0; i < nonCatchAllCount; i++) {
1092
+ const patternSeg = patternSegments[i];
1093
+ const pathSeg = pathSegments[i];
1094
+ if (patternSeg.startsWith(":")) {
1095
+ const paramName = patternSeg.slice(1);
1096
+ params2[paramName] = pathSeg;
1097
+ } else if (patternSeg !== pathSeg) {
1098
+ return null;
1099
+ }
1100
+ }
1101
+ const catchAllValue = pathSegments.slice(nonCatchAllCount).join("/");
1102
+ const catchAllParamName = patternSegments[nonCatchAllCount].slice(4);
1103
+ params2[catchAllParamName] = catchAllValue;
1104
+ if (Object.keys(params2).length !== paramNames.length) {
1105
+ return null;
1106
+ }
1107
+ return params2;
1108
+ }
1109
+ if (patternSegments.length !== pathSegments.length) {
678
1110
  return null;
679
1111
  }
680
- try {
681
- const url = pathToFileURL(filePath).href;
682
- const module = await import(url);
683
- return module.default ?? {};
684
- } catch (err) {
1112
+ const params = {};
1113
+ for (let i = 0; i < patternSegments.length; i++) {
1114
+ const patternSeg = patternSegments[i];
1115
+ const pathSeg = pathSegments[i];
1116
+ if (patternSeg.startsWith(":")) {
1117
+ const paramName = patternSeg.slice(1);
1118
+ params[paramName] = pathSeg;
1119
+ } else if (patternSeg !== pathSeg) {
1120
+ return null;
1121
+ }
1122
+ }
1123
+ if (Object.keys(params).length !== paramNames.length) {
1124
+ return null;
1125
+ }
1126
+ return params;
1127
+ }
1128
+
1129
+ // src/loader/resolveExports.ts
1130
+ function resolveExport(module, exportName) {
1131
+ if (exportName in module && typeof module[exportName] !== "undefined") {
1132
+ return module[exportName];
1133
+ }
1134
+ const defaultExport = module.default;
1135
+ if (defaultExport !== null && typeof defaultExport === "object") {
1136
+ const value = defaultExport[exportName];
1137
+ if (value !== void 0) {
1138
+ return value;
1139
+ }
1140
+ }
1141
+ return void 0;
1142
+ }
1143
+
1144
+ // src/loader/validateRouteModule.ts
1145
+ function validateRouteModule(value, method, filePath) {
1146
+ if (typeof value !== "function") {
685
1147
  throw new Error(
686
- `Failed to load config file ${filePath}: ${err instanceof Error ? err.message : String(err)}`,
687
- { cause: err }
1148
+ `Route module "${filePath}" does not export a valid handler for method "${method}". Expected a function, got ${typeof value}.`
688
1149
  );
689
1150
  }
690
1151
  }
691
- async function loadConfig(rootDir, configPath) {
692
- if (configPath) {
693
- const resolvedPath = path.resolve(rootDir, configPath);
694
- if (!fs.existsSync(resolvedPath)) {
695
- throw new Error(`Config file not found: ${configPath}`);
1152
+
1153
+ // src/loader/loadRouteModule.ts
1154
+ async function loadRouteModule(filePath, method) {
1155
+ let module;
1156
+ try {
1157
+ module = await importWithCacheBust(filePath);
1158
+ } catch (err) {
1159
+ const reason = err instanceof Error ? err.message : String(err);
1160
+ throw new Error(`Failed to load route module "${filePath}": ${reason}`, { cause: err });
1161
+ }
1162
+ const handler = resolveExport(module, method);
1163
+ validateRouteModule(handler, method, filePath);
1164
+ return { handler, method };
1165
+ }
1166
+
1167
+ // src/runtime/sse.ts
1168
+ function encodeSseEvent(event) {
1169
+ let out = "";
1170
+ if (event.comment !== void 0) {
1171
+ out += `: ${event.comment}
1172
+ `;
1173
+ }
1174
+ if (event.event !== void 0) {
1175
+ out += `event: ${event.event}
1176
+ `;
1177
+ }
1178
+ if (event.id !== void 0) {
1179
+ out += `id: ${event.id}
1180
+ `;
1181
+ }
1182
+ if (event.retry !== void 0) {
1183
+ out += `retry: ${event.retry}
1184
+ `;
1185
+ }
1186
+ if (event.data !== void 0) {
1187
+ let dataStr;
1188
+ if (typeof event.data === "string") {
1189
+ dataStr = event.data;
1190
+ } else if (event.data === null) {
1191
+ dataStr = "null";
1192
+ } else {
1193
+ dataStr = JSON.stringify(event.data);
1194
+ }
1195
+ const lines = dataStr.split("\n");
1196
+ for (const line of lines) {
1197
+ out += `data: ${line}
1198
+ `;
696
1199
  }
697
- return loadConfigFile(resolvedPath);
698
1200
  }
699
- let baseConfig = null;
700
- for (const fileName of BASE_CONFIG_FILES) {
701
- const filePath = path.join(rootDir, fileName);
702
- baseConfig = await loadConfigFile(filePath);
703
- if (baseConfig) break;
1201
+ out += "\n";
1202
+ return out;
1203
+ }
1204
+ function createSseWriter() {
1205
+ const encoder = new TextEncoder();
1206
+ let controller = null;
1207
+ let closed = false;
1208
+ let aborted = false;
1209
+ const stream = new ReadableStream({
1210
+ start(c) {
1211
+ controller = c;
1212
+ },
1213
+ cancel() {
1214
+ aborted = true;
1215
+ closed = true;
1216
+ controller = null;
1217
+ }
1218
+ });
1219
+ const response = new Response(stream, {
1220
+ status: 200,
1221
+ headers: {
1222
+ "Content-Type": "text/event-stream",
1223
+ "Cache-Control": "no-cache",
1224
+ Connection: "keep-alive"
1225
+ }
1226
+ });
1227
+ const writer = {
1228
+ send(event) {
1229
+ if (closed || !controller) return;
1230
+ const text = encodeSseEvent(event);
1231
+ controller.enqueue(encoder.encode(text));
1232
+ },
1233
+ sendError(error) {
1234
+ if (closed || !controller) return;
1235
+ const message = error instanceof Error ? error.message : String(error);
1236
+ const text = encodeSseEvent({ event: "error", data: message });
1237
+ try {
1238
+ controller.enqueue(encoder.encode(text));
1239
+ } finally {
1240
+ writer.close();
1241
+ }
1242
+ },
1243
+ close() {
1244
+ if (closed) return;
1245
+ closed = true;
1246
+ if (controller) {
1247
+ try {
1248
+ controller.close();
1249
+ } catch {
1250
+ }
1251
+ controller = null;
1252
+ }
1253
+ },
1254
+ get closed() {
1255
+ return closed;
1256
+ },
1257
+ get aborted() {
1258
+ return aborted;
1259
+ },
1260
+ get response() {
1261
+ return response;
1262
+ }
1263
+ };
1264
+ return writer;
1265
+ }
1266
+
1267
+ // src/runtime/createContext.ts
1268
+ function parseCookies(cookieHeader) {
1269
+ const cookies = /* @__PURE__ */ new Map();
1270
+ if (!cookieHeader) return cookies;
1271
+ for (const pair of cookieHeader.split(";")) {
1272
+ const [name, ...rest] = pair.split("=");
1273
+ const trimmed = name?.trim();
1274
+ if (trimmed) {
1275
+ cookies.set(trimmed, rest.join("=").trim());
1276
+ }
704
1277
  }
705
- if (!baseConfig) {
706
- return null;
1278
+ return cookies;
1279
+ }
1280
+ function formatSetCookie(name, value, options) {
1281
+ let cookie = `${name}=${value}`;
1282
+ if (options?.domain) cookie += `; Domain=${options.domain}`;
1283
+ if (options?.path) cookie += `; Path=${options.path}`;
1284
+ if (options?.maxAge !== void 0) cookie += `; Max-Age=${options.maxAge}`;
1285
+ if (options?.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
1286
+ if (options?.httpOnly) cookie += `; HttpOnly`;
1287
+ if (options?.secure) cookie += `; Secure`;
1288
+ if (options?.sameSite) cookie += `; SameSite=${options.sameSite}`;
1289
+ return cookie;
1290
+ }
1291
+ function createContext(request, params, config = {}, ip = "") {
1292
+ const url = new URL(request.url);
1293
+ const meta = { headers: {}, setCookies: [] };
1294
+ const parsedCookies = parseCookies(request.headers.get("cookie") ?? "");
1295
+ const cookiesObj = {};
1296
+ for (const [key, val] of parsedCookies) {
1297
+ cookiesObj[key] = val;
707
1298
  }
708
- const env = getEnv();
709
- const envFiles = [`faapi.config.${env}.ts`, `faapi.config.${env}.js`];
710
- for (const envFile of envFiles) {
711
- const envConfig = await loadConfigFile(path.join(rootDir, envFile));
712
- if (envConfig) {
713
- baseConfig = deepMerge(baseConfig, envConfig);
714
- break;
1299
+ const ctx = {
1300
+ request,
1301
+ params,
1302
+ query: url.searchParams,
1303
+ headers: request.headers,
1304
+ method: request.method,
1305
+ path: url.pathname,
1306
+ ip,
1307
+ cookies: cookiesObj,
1308
+ config,
1309
+ meta,
1310
+ setStatus(status) {
1311
+ meta.status = status;
1312
+ },
1313
+ setHeader(key, value) {
1314
+ meta.headers[key] = value;
1315
+ },
1316
+ setETag(value) {
1317
+ meta.headers["etag"] = value;
1318
+ },
1319
+ redirect(url2, status = 302) {
1320
+ return new Response(null, {
1321
+ status,
1322
+ headers: { Location: url2 }
1323
+ });
1324
+ },
1325
+ json(data, status) {
1326
+ const headers = { "Content-Type": "application/json" };
1327
+ return new Response(JSON.stringify(data), {
1328
+ status: status ?? 200,
1329
+ headers
1330
+ });
1331
+ },
1332
+ html(html, status) {
1333
+ const headers = { "Content-Type": "text/html; charset=utf-8" };
1334
+ return new Response(html, {
1335
+ status: status ?? 200,
1336
+ headers
1337
+ });
1338
+ },
1339
+ getCookie(name) {
1340
+ return parsedCookies.get(name);
1341
+ },
1342
+ setCookie(name, value, options) {
1343
+ meta.setCookies.push(formatSetCookie(name, value, options));
1344
+ },
1345
+ deleteCookie(name) {
1346
+ meta.setCookies.push(formatSetCookie(name, "", { maxAge: 0 }));
1347
+ },
1348
+ /**
1349
+ * 创建 SSE writer,用于流式推送事件
1350
+ *
1351
+ * handler 调用此方法后,通过返回的 writer 推送事件,框架自动把 writer.response
1352
+ * 作为 HTTP 响应(Content-Type: text/event-stream)。
1353
+ *
1354
+ * 与 ctx.json / ctx.html 互斥:一个 handler 只能用一种响应方式。
1355
+ */
1356
+ sse() {
1357
+ const writer = createSseWriter();
1358
+ const ctxWithSse = ctx;
1359
+ ctxWithSse.__sseResponse = writer.response;
1360
+ ctxWithSse.__sseWriter = writer;
1361
+ return writer;
715
1362
  }
1363
+ };
1364
+ const extend = config?.extendContext;
1365
+ if (typeof extend === "function") {
1366
+ extend(ctx);
716
1367
  }
717
- return baseConfig;
1368
+ return ctx;
1369
+ }
1370
+
1371
+ // src/utils/queryToObject.ts
1372
+ function queryToObject(params) {
1373
+ const result = {};
1374
+ for (const [key, value] of params) {
1375
+ result[key] = value;
1376
+ }
1377
+ return result;
1378
+ }
1379
+
1380
+ // src/utils/parseJsonBody.ts
1381
+ function parseJsonBody(text) {
1382
+ try {
1383
+ const data = JSON.parse(text);
1384
+ return { success: true, data };
1385
+ } catch {
1386
+ return { success: false, error: "Invalid JSON body" };
1387
+ }
1388
+ }
1389
+
1390
+ // src/utils/parseMultipart.ts
1391
+ async function parseMultipart(request) {
1392
+ const formData = await request.formData();
1393
+ const fields = {};
1394
+ const files = [];
1395
+ for (const [key, value] of formData.entries()) {
1396
+ if (value instanceof File) {
1397
+ files.push({
1398
+ name: key,
1399
+ filename: value.name,
1400
+ type: value.type,
1401
+ size: value.size,
1402
+ arrayBuffer: () => value.arrayBuffer()
1403
+ });
1404
+ } else {
1405
+ if (key in fields) {
1406
+ const existing = fields[key];
1407
+ if (Array.isArray(existing)) {
1408
+ existing.push(value);
1409
+ } else {
1410
+ fields[key] = [existing, value];
1411
+ }
1412
+ } else {
1413
+ fields[key] = value;
1414
+ }
1415
+ }
1416
+ }
1417
+ return { fields, files };
1418
+ }
1419
+
1420
+ // src/errors/FaapiError.ts
1421
+ var FaapiError = class extends Error {
1422
+ constructor(code, message, statusCode) {
1423
+ super(message);
1424
+ this.code = code;
1425
+ this.statusCode = statusCode;
1426
+ this.name = "FaapiError";
1427
+ }
1428
+ code;
1429
+ statusCode;
1430
+ };
1431
+
1432
+ // src/errors/httpErrors.ts
1433
+ function deriveStatusCode(issues) {
1434
+ const has400 = issues.some((i) => i.code === "INVALID_FORMAT" || i.code === "MISSING_FIELD");
1435
+ return has400 ? 400 : 422;
1436
+ }
1437
+ var ValidationError = class extends FaapiError {
1438
+ constructor(message, issues) {
1439
+ super("VALIDATION_ERROR", message, deriveStatusCode(issues));
1440
+ this.issues = issues;
1441
+ this.name = "ValidationError";
1442
+ }
1443
+ issues;
1444
+ };
1445
+ var RouteNotFoundError = class extends FaapiError {
1446
+ constructor(path9) {
1447
+ super("ROUTE_NOT_FOUND", `Route not found: ${path9}`, 404);
1448
+ this.name = "RouteNotFoundError";
1449
+ }
1450
+ };
1451
+ var MethodNotAllowedError = class extends FaapiError {
1452
+ constructor(method, path9, allowedMethods) {
1453
+ super("METHOD_NOT_ALLOWED", `Method ${method} not allowed for ${path9}`, 405);
1454
+ this.allowedMethods = allowedMethods;
1455
+ this.name = "MethodNotAllowedError";
1456
+ }
1457
+ allowedMethods;
1458
+ };
1459
+ var InternalError = class extends FaapiError {
1460
+ constructor(message) {
1461
+ super("INTERNAL_ERROR", message, 500);
1462
+ this.name = "InternalError";
1463
+ }
1464
+ };
1465
+
1466
+ // src/runtime/resolveInput.ts
1467
+ async function resolveInput(method, request) {
1468
+ const inputType = getInputTypeForMethod(method);
1469
+ if (inputType === "body") {
1470
+ const contentType = request.headers.get("content-type") ?? "";
1471
+ if (contentType.includes("multipart/form-data")) {
1472
+ return parseMultipart(request);
1473
+ }
1474
+ if (contentType.includes("application/x-www-form-urlencoded")) {
1475
+ const text2 = await request.text();
1476
+ if (text2.trim() === "") return null;
1477
+ const params = new URLSearchParams(text2);
1478
+ const obj = {};
1479
+ for (const [key, value] of params) {
1480
+ obj[key] = value;
1481
+ }
1482
+ return obj;
1483
+ }
1484
+ const text = await request.text();
1485
+ if (text.trim() === "") {
1486
+ return null;
1487
+ }
1488
+ const result = parseJsonBody(text);
1489
+ if (!result.success) {
1490
+ throw new ValidationError("\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5\u7684 JSON", [
1491
+ {
1492
+ path: "body",
1493
+ code: "INVALID_FORMAT",
1494
+ expected: "JSON",
1495
+ received: "text",
1496
+ message: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5\u7684 JSON"
1497
+ }
1498
+ ]);
1499
+ }
1500
+ return result.data;
1501
+ }
1502
+ const url = new URL(request.url);
1503
+ return queryToObject(url.searchParams);
1504
+ }
1505
+
1506
+ // src/runtime/invokeHandler.ts
1507
+ init_toResponse();
1508
+
1509
+ // src/injection/injectParams.ts
1510
+ function getBuiltinInjectionValue(type, ctx, body) {
1511
+ switch (type) {
1512
+ case "query":
1513
+ return queryToObject(ctx.query);
1514
+ case "params":
1515
+ return ctx.params;
1516
+ case "headers":
1517
+ return ctx.headers;
1518
+ case "context":
1519
+ return ctx;
1520
+ case "cookies":
1521
+ return ctx.cookies;
1522
+ case "ip":
1523
+ return ctx.ip;
1524
+ case "body":
1525
+ return body;
1526
+ case "files":
1527
+ if (body && typeof body === "object" && "files" in body) {
1528
+ return body.files;
1529
+ }
1530
+ return [];
1531
+ case "fields":
1532
+ if (body && typeof body === "object" && "fields" in body) {
1533
+ return body.fields;
1534
+ }
1535
+ return {};
1536
+ default:
1537
+ return void 0;
1538
+ }
1539
+ }
1540
+ async function injectParamsAsync(handler, ctx, body, injectors) {
1541
+ const injections = resolveInjection(handler);
1542
+ if (injections.length === 0) {
1543
+ return await handler();
1544
+ }
1545
+ const args = await Promise.all(
1546
+ injections.map(async (injection) => {
1547
+ if (injection.type !== "unknown") {
1548
+ return getBuiltinInjectionValue(injection.type, ctx, body);
1549
+ }
1550
+ if (injectors && injection.name in injectors) {
1551
+ return await injectors[injection.name](ctx);
1552
+ }
1553
+ return void 0;
1554
+ })
1555
+ );
1556
+ return await handler(...args);
1557
+ }
1558
+
1559
+ // src/runtime/invokeHandler.ts
1560
+ function mergeMeta(response, meta) {
1561
+ const hasMeta = meta.status !== void 0 || Object.keys(meta.headers).length > 0 || meta.setCookies.length > 0;
1562
+ if (!hasMeta) return response;
1563
+ const headers = new Headers(response.headers);
1564
+ for (const [key, value] of Object.entries(meta.headers)) {
1565
+ headers.set(key, value);
1566
+ }
1567
+ for (const cookie of meta.setCookies) {
1568
+ headers.append("set-cookie", cookie);
1569
+ }
1570
+ return new Response(response.body, {
1571
+ status: meta.status ?? response.status,
1572
+ headers
1573
+ });
1574
+ }
1575
+ async function compose(middlewares, ctx, finalHandler) {
1576
+ const meta = ctx.meta;
1577
+ let index = -1;
1578
+ async function dispatch(i) {
1579
+ if (i <= index) {
1580
+ throw new Error("next() called multiple times");
1581
+ }
1582
+ index = i;
1583
+ if (i >= middlewares.length) {
1584
+ return await finalHandler();
1585
+ }
1586
+ const mw = middlewares[i];
1587
+ let innerResponse;
1588
+ const next = async () => {
1589
+ innerResponse = await dispatch(i + 1);
1590
+ return innerResponse;
1591
+ };
1592
+ const result = await mw(ctx, next);
1593
+ if (result instanceof Response) {
1594
+ return mergeMeta(result, meta);
1595
+ }
1596
+ if (innerResponse !== void 0) {
1597
+ return innerResponse;
1598
+ }
1599
+ throw new Error("\u4E2D\u95F4\u4EF6\u5FC5\u987B await next() \u6216\u8FD4\u56DE Response");
1600
+ }
1601
+ return await dispatch(0);
1602
+ }
1603
+ async function invokeHandler(handler, ctx, body, middlewares, injectors) {
1604
+ const meta = ctx.meta;
1605
+ const pickSseAndAutoClose = () => {
1606
+ const sseWriter = ctx.__sseWriter;
1607
+ if (!sseWriter) return null;
1608
+ if (!sseWriter.closed && !sseWriter.aborted) {
1609
+ sseWriter.close();
1610
+ }
1611
+ return mergeMeta(sseWriter.response, meta);
1612
+ };
1613
+ const autoCloseSseOnError = () => {
1614
+ const sseWriter = ctx.__sseWriter;
1615
+ if (sseWriter && !sseWriter.closed && !sseWriter.aborted) {
1616
+ sseWriter.close();
1617
+ }
1618
+ };
1619
+ if (!middlewares || middlewares.length === 0) {
1620
+ try {
1621
+ const result = await injectParamsAsync(handler, ctx, body, injectors);
1622
+ const sseResponse = pickSseAndAutoClose();
1623
+ if (sseResponse) return sseResponse;
1624
+ return toResponse(result, meta);
1625
+ } catch (err) {
1626
+ autoCloseSseOnError();
1627
+ throw err;
1628
+ }
1629
+ }
1630
+ const finalHandler = async () => {
1631
+ try {
1632
+ const result = await injectParamsAsync(handler, ctx, body, injectors);
1633
+ const sseResponse = pickSseAndAutoClose();
1634
+ if (sseResponse) return sseResponse;
1635
+ return toResponse(result, meta);
1636
+ } catch (err) {
1637
+ autoCloseSseOnError();
1638
+ throw err;
1639
+ }
1640
+ };
1641
+ return await compose(middlewares, ctx, finalHandler);
1642
+ }
1643
+
1644
+ // src/response/sendNodeResponse.ts
1645
+ import { Readable } from "stream";
1646
+ async function sendNodeResponse(response, res) {
1647
+ res.statusCode = response.status;
1648
+ for (const [key, value] of response.headers) {
1649
+ if (key.toLowerCase() === "set-cookie") {
1650
+ res.appendHeader(key, value);
1651
+ } else {
1652
+ res.setHeader(key, value);
1653
+ }
1654
+ }
1655
+ if (response.body) {
1656
+ const nodeStream = Readable.fromWeb(response.body);
1657
+ await new Promise((resolve, reject) => {
1658
+ nodeStream.on("error", reject);
1659
+ res.on("error", reject);
1660
+ res.on("finish", resolve);
1661
+ nodeStream.pipe(res);
1662
+ });
1663
+ return;
1664
+ }
1665
+ res.end();
1666
+ }
1667
+
1668
+ // src/validator/validateInput.ts
1669
+ var moduleCache = /* @__PURE__ */ new Map();
1670
+ function invalidateSchemaCache() {
1671
+ moduleCache.clear();
1672
+ }
1673
+ async function loadSchemaModule(schemaPath) {
1674
+ let mod = moduleCache.get(schemaPath);
1675
+ if (!mod) {
1676
+ mod = await importWithCacheBust(schemaPath);
1677
+ moduleCache.set(schemaPath, mod);
1678
+ }
1679
+ return mod;
1680
+ }
1681
+ async function validateInput(schemaPath, method, inputType, input) {
1682
+ const schemaName = getSchemaName(method, inputType);
1683
+ const schemaKey = `${schemaName}Schema`;
1684
+ let mod;
1685
+ try {
1686
+ mod = await loadSchemaModule(schemaPath);
1687
+ } catch (err) {
1688
+ const reason = err instanceof Error ? err.message : String(err);
1689
+ throw new InternalError(`Schema \u6A21\u5757\u52A0\u8F7D\u5931\u8D25: ${schemaPath}: ${reason}`);
1690
+ }
1691
+ const schema = mod[schemaKey];
1692
+ if (schema === void 0 || schema === null) {
1693
+ const data = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
1694
+ return { valid: true, issues: [], data };
1695
+ }
1696
+ if (typeof schema !== "object" || typeof schema.safeParse !== "function") {
1697
+ throw new InternalError(`Schema \u4E0D\u662F\u6709\u6548\u7684 zod schema: ${schemaPath}#${schemaName}`);
1698
+ }
1699
+ const inputObj = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
1700
+ const zodSchema = schema;
1701
+ const result = zodSchema.safeParse(inputObj);
1702
+ if (result.success) {
1703
+ const data = typeof result.data === "object" && result.data !== null && !Array.isArray(result.data) ? result.data : {};
1704
+ return { valid: true, issues: [], data };
1705
+ }
1706
+ const issues = mapZodIssues(result.error);
1707
+ return { valid: false, issues, data: inputObj };
1708
+ }
1709
+ function mapZodIssues(error) {
1710
+ return error.issues.map((issue) => {
1711
+ const code = mapZodCode(issue.code, issue.message);
1712
+ const path9 = issue.path.map(String).join(".") || "";
1713
+ return {
1714
+ path: path9,
1715
+ code,
1716
+ expected: issue.expected ?? mapExpectedFromMessage(issue.message),
1717
+ received: issue.received ?? mapReceivedFromMessage(issue.message),
1718
+ message: issue.message
1719
+ };
1720
+ });
1721
+ }
1722
+ function mapZodCode(zodCode, message) {
1723
+ switch (zodCode) {
1724
+ case "invalid_type":
1725
+ case "invalid_union":
1726
+ case "invalid_union_discriminator":
1727
+ return "TYPE_MISMATCH";
1728
+ case "unrecognized_keys":
1729
+ return "INVALID_FORMAT";
1730
+ case "invalid_enum_value":
1731
+ case "invalid_string":
1732
+ case "invalid_date":
1733
+ case "too_small":
1734
+ case "too_big":
1735
+ case "invalid_intersection_types":
1736
+ case "not_multiple_of":
1737
+ return "INVALID_VALUE";
1738
+ case "not_finite":
1739
+ return "COERCE_FAILED";
1740
+ case "custom":
1741
+ return "INVALID_VALUE";
1742
+ default:
1743
+ if (message.includes("Required") || message.includes("required")) {
1744
+ return "MISSING_FIELD";
1745
+ }
1746
+ return "INVALID_VALUE";
1747
+ }
1748
+ }
1749
+ function mapExpectedFromMessage(message) {
1750
+ const match = message.match(/Expected\s+(\w+)/i);
1751
+ return match ? match[1].toLowerCase() : "unknown";
1752
+ }
1753
+ function mapReceivedFromMessage(message) {
1754
+ const match = message.match(/received\s+(\w+)/i);
1755
+ return match ? match[1].toLowerCase() : "unknown";
1756
+ }
1757
+
1758
+ // src/utils/getClientIp.ts
1759
+ function getClientIp(req) {
1760
+ const xff = req.headers["x-forwarded-for"];
1761
+ if (typeof xff === "string" && xff.length > 0) {
1762
+ const first = xff.split(",")[0]?.trim();
1763
+ if (first) return first;
1764
+ }
1765
+ const remote = req.socket.remoteAddress;
1766
+ if (remote) {
1767
+ if (remote.startsWith("::ffff:")) {
1768
+ return remote.slice(7);
1769
+ }
1770
+ return remote;
1771
+ }
1772
+ return "";
1773
+ }
1774
+
1775
+ // src/server/handleWsUpgrade.ts
1776
+ import { WebSocketServer, WebSocket } from "ws";
1777
+ import path3 from "path";
1778
+
1779
+ // src/errors/formatErrorResponse.ts
1780
+ function formatErrorResponse(error) {
1781
+ if (error instanceof ValidationError) {
1782
+ const body2 = {
1783
+ code: error.code,
1784
+ message: error.message,
1785
+ issues: error.issues
1786
+ };
1787
+ return new Response(JSON.stringify({ error: body2 }), {
1788
+ status: error.statusCode,
1789
+ headers: { "Content-Type": "application/json" }
1790
+ });
1791
+ }
1792
+ if (error instanceof MethodNotAllowedError) {
1793
+ const body2 = {
1794
+ code: error.code,
1795
+ message: error.message
1796
+ };
1797
+ return new Response(JSON.stringify({ error: body2 }), {
1798
+ status: error.statusCode,
1799
+ headers: {
1800
+ "Content-Type": "application/json",
1801
+ Allow: error.allowedMethods.join(", ")
1802
+ }
1803
+ });
1804
+ }
1805
+ if (error instanceof FaapiError) {
1806
+ const body2 = {
1807
+ code: error.code,
1808
+ message: error.message
1809
+ };
1810
+ return new Response(JSON.stringify({ error: body2 }), {
1811
+ status: error.statusCode,
1812
+ headers: { "Content-Type": "application/json" }
1813
+ });
1814
+ }
1815
+ const body = {
1816
+ code: "INTERNAL_ERROR",
1817
+ message: error instanceof Error ? error.message : "An unknown error occurred"
1818
+ };
1819
+ return new Response(JSON.stringify({ error: body }), {
1820
+ status: 500,
1821
+ headers: { "Content-Type": "application/json" }
1822
+ });
1823
+ }
1824
+
1825
+ // src/server/serverUtils.ts
1826
+ function nodeHttpToWebHeaders(req) {
1827
+ const headers = new Headers();
1828
+ for (const [key, value] of Object.entries(req.headers)) {
1829
+ if (value === void 0) continue;
1830
+ if (Array.isArray(value)) {
1831
+ for (const v of value) headers.append(key, v);
1832
+ } else {
1833
+ headers.set(key, value);
1834
+ }
1835
+ }
1836
+ return headers;
1837
+ }
1838
+ function buildErrorResponse(err, ctx, errorFormat) {
1839
+ if (errorFormat) {
1840
+ try {
1841
+ const res = errorFormat(err, ctx);
1842
+ if (res) return res;
1843
+ } catch {
1844
+ }
1845
+ }
1846
+ try {
1847
+ return formatErrorResponse(err);
1848
+ } catch {
1849
+ return new Response(
1850
+ JSON.stringify({ error: { code: "INTERNAL_ERROR", message: "Internal Server Error" } }),
1851
+ {
1852
+ status: 500,
1853
+ headers: { "Content-Type": "application/json" }
1854
+ }
1855
+ );
1856
+ }
1857
+ }
1858
+
1859
+ // src/runtime/wsHandler.ts
1860
+ function wrapWsSocket(rawSocket) {
1861
+ return {
1862
+ send(data) {
1863
+ const payload = typeof data === "string" || Buffer.isBuffer(data) ? data : JSON.stringify(data);
1864
+ rawSocket.send(payload);
1865
+ },
1866
+ close(code, reason) {
1867
+ rawSocket.close(code, reason);
1868
+ },
1869
+ get readyState() {
1870
+ return rawSocket.readyState;
1871
+ }
1872
+ };
1873
+ }
1874
+
1875
+ // src/server/handleWsUpgrade.ts
1876
+ function getPathname(req) {
1877
+ const url = req.url ?? "/";
1878
+ const idx = url.indexOf("?");
1879
+ return idx >= 0 ? url.slice(0, idx) : url;
1880
+ }
1881
+ async function loadWsHandler(filePath, ctx) {
1882
+ const module = await importWithCacheBust(filePath);
1883
+ const handler = module["WS"];
1884
+ if (typeof handler !== "function") {
1885
+ throw new Error(`WS export not found in ${filePath}`);
1886
+ }
1887
+ return handler(ctx);
1888
+ }
1889
+ function bindEvents(rawSocket, handlers) {
1890
+ if (!handlers) return;
1891
+ const ws = wrapWsSocket(rawSocket);
1892
+ if (handlers.onOpen) {
1893
+ if (rawSocket.readyState === WebSocket.OPEN) {
1894
+ handlers.onOpen(ws);
1895
+ } else {
1896
+ rawSocket.once("open", () => handlers.onOpen(ws));
1897
+ }
1898
+ }
1899
+ if (handlers.onMessage) {
1900
+ rawSocket.on("message", (data) => {
1901
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
1902
+ handlers.onMessage(ws, buf.toString("utf8"));
1903
+ });
1904
+ }
1905
+ if (handlers.onClose) {
1906
+ rawSocket.on("close", (code, reason) => {
1907
+ handlers.onClose(ws, code, reason.toString("utf8"));
1908
+ });
1909
+ }
1910
+ if (handlers.onError) {
1911
+ rawSocket.on("error", (err) => {
1912
+ handlers.onError(ws, err);
1913
+ });
1914
+ }
1915
+ }
1916
+ async function sendResponseToSocket(socket, response) {
1917
+ const body = await response.text().catch(() => "");
1918
+ const statusLine = `HTTP/1.1 ${response.status} ${response.statusText || ""}\r
1919
+ `;
1920
+ const headerLines = [];
1921
+ let hasContentLength = false;
1922
+ for (const [key, value] of response.headers) {
1923
+ if (key.toLowerCase() === "content-length") {
1924
+ hasContentLength = true;
1925
+ }
1926
+ headerLines.push(`${key}: ${value}`);
1927
+ }
1928
+ if (!hasContentLength) {
1929
+ headerLines.push(`Content-Length: ${Buffer.byteLength(body)}`);
1930
+ }
1931
+ socket.write(statusLine + headerLines.join("\r\n") + "\r\n\r\n" + body);
1932
+ socket.destroy();
1933
+ }
1934
+ function attachWebSocket(options) {
1935
+ const { server, routesRef, rootDir, config, errorFormat, globalMiddlewares } = options;
1936
+ const wss = new WebSocketServer({ noServer: true });
1937
+ server.on("upgrade", async (req, socket, head) => {
1938
+ const currentWsRoutes = routesRef.wsCurrent;
1939
+ const pathname = getPathname(req);
1940
+ const match = matchWsRoute(currentWsRoutes, pathname);
1941
+ if (!match) {
1942
+ socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
1943
+ socket.destroy();
1944
+ return;
1945
+ }
1946
+ const { route, params } = match;
1947
+ const headers = nodeHttpToWebHeaders(req);
1948
+ const host = req.headers.host ?? "localhost";
1949
+ const url = `http://${host}${req.url ?? "/"}`;
1950
+ const request = new Request(url, { method: "GET", headers });
1951
+ const ctx = createContext(request, params, config, getClientIp(req));
1952
+ const meta = ctx.meta;
1953
+ let upgraded = false;
1954
+ const finalHandler = async () => {
1955
+ let handlers;
1956
+ try {
1957
+ const absoluteFilePath = path3.resolve(rootDir, route.filePath);
1958
+ handlers = await loadWsHandler(absoluteFilePath, ctx);
1959
+ } catch (err) {
1960
+ const reason = err instanceof Error ? err.message : String(err);
1961
+ console.error(`[faapi] WS handler \u52A0\u8F7D\u5931\u8D25 ${route.filePath}: ${reason}`);
1962
+ return new Response("Internal Server Error", { status: 500 });
1963
+ }
1964
+ await new Promise((resolve, reject) => {
1965
+ wss.handleUpgrade(req, socket, head, (rawSocket) => {
1966
+ try {
1967
+ bindEvents(rawSocket, handlers);
1968
+ wss.emit("connection", rawSocket, req);
1969
+ upgraded = true;
1970
+ resolve();
1971
+ } catch (err) {
1972
+ reject(err);
1973
+ }
1974
+ });
1975
+ });
1976
+ return new Response(null, { status: 200 });
1977
+ };
1978
+ let response;
1979
+ try {
1980
+ const dirMiddlewares = route.middlewares ?? [];
1981
+ const allMiddlewares = globalMiddlewares && globalMiddlewares.length > 0 ? [...globalMiddlewares, ...dirMiddlewares] : dirMiddlewares;
1982
+ if (allMiddlewares.length > 0) {
1983
+ response = await compose(allMiddlewares, ctx, finalHandler);
1984
+ } else {
1985
+ response = await finalHandler();
1986
+ }
1987
+ } catch (err) {
1988
+ if (upgraded) {
1989
+ console.error("[faapi] WS \u63E1\u624B\u540E\u4E2D\u95F4\u4EF6\u629B\u9519:", err);
1990
+ return;
1991
+ }
1992
+ response = buildErrorResponse(err, ctx, errorFormat);
1993
+ }
1994
+ if (upgraded) {
1995
+ return;
1996
+ }
1997
+ await sendResponseToSocket(socket, mergeMeta(response, meta));
1998
+ });
1999
+ return wss;
2000
+ }
2001
+
2002
+ // src/cli/generateSchemaFiles.ts
2003
+ import path4 from "path";
2004
+ import fs2 from "fs/promises";
2005
+
2006
+ // src/ast/generateZodSchema.ts
2007
+ var CodeGenContext = class {
2008
+ /** 命名类型集合:name → RuntimeType */
2009
+ namedTypes = /* @__PURE__ */ new Map();
2010
+ /** 类型解析器(用于解析 ref 的实际类型) */
2011
+ resolveType;
2012
+ /** 入口类型原始名(typeInfo.name,用于识别入口类型的自引用) */
2013
+ entryTypeName = "";
2014
+ /** 入口类型导出名(exportName,自引用时用此名生成变量名) */
2015
+ entryExportName = "";
2016
+ /**
2017
+ * 是否生成 coerce 逻辑(query/params 场景,URL 来源均为 string)
2018
+ *
2019
+ * true 时为 number/boolean 字段包 z.preprocess,把合法的字符串转成对应类型。
2020
+ * 嵌套类型(array/object/tuple/union 等)的元素递归处理。
2021
+ */
2022
+ coerce = false;
2023
+ constructor(resolveType) {
2024
+ this.resolveType = resolveType;
2025
+ }
2026
+ };
2027
+ function collectNamedTypes(type, ctx) {
2028
+ switch (type.kind) {
2029
+ case "string":
2030
+ case "number":
2031
+ case "boolean":
2032
+ case "bigint":
2033
+ case "null":
2034
+ case "undefined":
2035
+ case "any":
2036
+ case "unknown":
2037
+ case "literal":
2038
+ case "date":
2039
+ return;
2040
+ case "array":
2041
+ collectNamedTypes(type.element, ctx);
2042
+ return;
2043
+ case "tuple":
2044
+ for (const el of type.elements) {
2045
+ collectNamedTypes(el.type, ctx);
2046
+ }
2047
+ return;
2048
+ case "object":
2049
+ for (const prop of type.properties) {
2050
+ collectNamedTypes(prop.type, ctx);
2051
+ }
2052
+ return;
2053
+ case "union":
2054
+ for (const member of type.members) {
2055
+ collectNamedTypes(member, ctx);
2056
+ }
2057
+ return;
2058
+ case "record":
2059
+ collectNamedTypes(type.key, ctx);
2060
+ collectNamedTypes(type.value, ctx);
2061
+ return;
2062
+ case "ref": {
2063
+ if (ctx.namedTypes.has(type.name)) return;
2064
+ ctx.namedTypes.set(type.name, { kind: "any" });
2065
+ const resolved = ctx.resolveType(type.name);
2066
+ if (resolved) {
2067
+ ctx.namedTypes.set(type.name, resolved);
2068
+ collectNamedTypes(resolved, ctx);
2069
+ }
2070
+ return;
2071
+ }
2072
+ }
2073
+ }
2074
+ function runtimeTypeToZodExpression(type, ctx) {
2075
+ const expr = baseExpression(type, ctx);
2076
+ if (ctx.coerce && (type.kind === "number" || type.kind === "boolean")) {
2077
+ return wrapCoercePreprocess(type.kind, expr);
2078
+ }
2079
+ return expr;
2080
+ }
2081
+ function baseExpression(type, ctx) {
2082
+ switch (type.kind) {
2083
+ case "string":
2084
+ return "z.string()";
2085
+ case "number":
2086
+ return "z.number()";
2087
+ case "boolean":
2088
+ return "z.boolean()";
2089
+ case "bigint":
2090
+ return "z.never()";
2091
+ case "null":
2092
+ return "z.null()";
2093
+ case "undefined":
2094
+ return "z.undefined()";
2095
+ case "any":
2096
+ case "unknown":
2097
+ return "z.unknown()";
2098
+ case "literal":
2099
+ return `z.literal(${JSON.stringify(type.value)})`;
2100
+ case "array":
2101
+ return `z.array(${runtimeTypeToZodExpression(type.element, ctx)})`;
2102
+ case "tuple":
2103
+ return generateTupleExpression(type.elements, ctx);
2104
+ case "object":
2105
+ return generateObjectExpression(type.properties, ctx);
2106
+ case "union":
2107
+ return generateUnionExpression(type.members, ctx);
2108
+ case "date":
2109
+ return 'z.preprocess((v) => (typeof v === "string" ? new Date(v) : v), z.date())';
2110
+ case "record":
2111
+ return `z.record(${runtimeTypeToZodExpression(type.key, ctx)}, ${runtimeTypeToZodExpression(type.value, ctx)})`;
2112
+ case "ref":
2113
+ if (type.name === ctx.entryTypeName) {
2114
+ return `${ctx.entryExportName}Schema`;
2115
+ }
2116
+ return `${type.name}Schema`;
2117
+ }
2118
+ }
2119
+ var COERCE_NUMBER_HELPER = 'export const coerceNumber = (v) => typeof v === "string" && v.trim() !== "" && !isNaN(Number(v)) ? Number(v) : v;';
2120
+ var COERCE_BOOLEAN_HELPER = 'export const coerceBoolean = (v) => v === "true" || v === "1" ? true : v === "false" || v === "0" ? false : v;';
2121
+ var HELPERS_FILENAME = "faapi-helpers.js";
2122
+ function generateHelpersFileSource() {
2123
+ return [
2124
+ "// faapi-helpers.js \u2014 faapi \u81EA\u52A8\u751F\u6210\u7684\u516C\u7528\u51FD\u6570\uFF08\u8BF7\u52FF\u624B\u52A8\u7F16\u8F91\uFF09",
2125
+ COERCE_NUMBER_HELPER,
2126
+ COERCE_BOOLEAN_HELPER,
2127
+ ""
2128
+ ].join("\n");
2129
+ }
2130
+ function usesCoerceHelpers(code) {
2131
+ return code.includes("coerceNumber") || code.includes("coerceBoolean");
2132
+ }
2133
+ function wrapCoercePreprocess(kind, inner) {
2134
+ if (kind === "number") {
2135
+ return `z.preprocess(coerceNumber, ${inner})`;
2136
+ }
2137
+ return `z.preprocess(coerceBoolean, ${inner})`;
2138
+ }
2139
+ function generateTupleExpression(elements, ctx) {
2140
+ const fixedExprs = [];
2141
+ const fixedOptional = [];
2142
+ let restExpression = "";
2143
+ let restStarted = false;
2144
+ for (const el of elements) {
2145
+ if (el.rest) {
2146
+ restExpression = runtimeTypeToZodExpression(el.type, ctx);
2147
+ restStarted = true;
2148
+ } else if (!restStarted) {
2149
+ fixedExprs.push(runtimeTypeToZodExpression(el.type, ctx));
2150
+ fixedOptional.push(el.optional);
2151
+ }
2152
+ }
2153
+ if (restExpression) {
2154
+ return `z.tuple([${fixedExprs.join(", ")}]).rest(${restExpression})`;
2155
+ }
2156
+ const hasOptional = fixedOptional.some((o) => o);
2157
+ if (!hasOptional) {
2158
+ return `z.tuple([${fixedExprs.join(", ")}])`;
2159
+ }
2160
+ const variants = [];
2161
+ for (let len = fixedExprs.length; len >= 0; len--) {
2162
+ const removed = fixedOptional.slice(len);
2163
+ if (removed.length > 0 && removed.some((o) => !o)) {
2164
+ break;
2165
+ }
2166
+ const subset = fixedExprs.slice(0, len);
2167
+ variants.push(`z.tuple([${subset.join(", ")}])`);
2168
+ }
2169
+ variants.reverse();
2170
+ if (variants.length === 1) {
2171
+ return variants[0];
2172
+ }
2173
+ return `z.union([${variants.join(", ")}])`;
2174
+ }
2175
+ function generateObjectExpression(properties, ctx) {
2176
+ const fields = properties.map((prop) => {
2177
+ const expr = runtimeTypeToZodExpression(prop.type, ctx);
2178
+ return `${JSON.stringify(prop.name)}: ${prop.optional ? `${expr}.optional()` : expr}`;
2179
+ });
2180
+ return `z.object({ ${fields.join(", ")} })`;
2181
+ }
2182
+ function generateUnionExpression(members, ctx) {
2183
+ const hasNull = members.some((m) => m.kind === "null");
2184
+ const nonNull = members.filter((m) => m.kind !== "null");
2185
+ if (hasNull && nonNull.length === 1) {
2186
+ return `${runtimeTypeToZodExpression(nonNull[0], ctx)}.nullable()`;
2187
+ }
2188
+ if (hasNull) {
2189
+ const unionInner2 = nonNull.map((m) => runtimeTypeToZodExpression(m, ctx)).join(", ");
2190
+ return `z.union([${unionInner2}]).nullable()`;
2191
+ }
2192
+ const unionInner = members.map((m) => runtimeTypeToZodExpression(m, ctx)).join(", ");
2193
+ return `z.union([${unionInner}])`;
2194
+ }
2195
+ function generateNamedTypeDeclaration(name, type, ctx) {
2196
+ const expr = runtimeTypeToZodExpression(type, ctx);
2197
+ const hasRef = containsRef(type, /* @__PURE__ */ new Set([name]));
2198
+ if (hasRef) {
2199
+ return `const ${name}Schema = z.lazy(() => ${expr});`;
2200
+ }
2201
+ return `const ${name}Schema = ${expr};`;
2202
+ }
2203
+ function containsRef(type, visited) {
2204
+ switch (type.kind) {
2205
+ case "ref":
2206
+ return visited.has(type.name);
2207
+ case "array":
2208
+ return containsRef(type.element, visited);
2209
+ case "tuple":
2210
+ return type.elements.some((el) => containsRef(el.type, visited));
2211
+ case "object":
2212
+ return type.properties.some((prop) => containsRef(prop.type, visited));
2213
+ case "union":
2214
+ return type.members.some((m) => containsRef(m, visited));
2215
+ case "record":
2216
+ return containsRef(type.key, visited) || containsRef(type.value, visited);
2217
+ default:
2218
+ return false;
2219
+ }
2220
+ }
2221
+ function generateZodSchemaSource(typeInfo, resolveType, exportName, coerce = false) {
2222
+ const ctx = new CodeGenContext(resolveType);
2223
+ const name = exportName ?? typeInfo.name;
2224
+ ctx.entryTypeName = typeInfo.name;
2225
+ ctx.entryExportName = name;
2226
+ ctx.coerce = coerce;
2227
+ collectNamedTypes(typeInfo.runtimeType, ctx);
2228
+ ctx.namedTypes.delete(typeInfo.name);
2229
+ const lines = [];
2230
+ lines.push("import { z } from 'zod';");
2231
+ lines.push("");
2232
+ for (const [n, type] of ctx.namedTypes) {
2233
+ lines.push(generateNamedTypeDeclaration(n, type, ctx));
2234
+ }
2235
+ if (ctx.namedTypes.size > 0) lines.push("");
2236
+ const entryExpr = runtimeTypeToZodExpression(typeInfo.runtimeType, ctx);
2237
+ const hasSelfRef = containsRef(typeInfo.runtimeType, /* @__PURE__ */ new Set([typeInfo.name]));
2238
+ if (hasSelfRef) {
2239
+ lines.push(`export const ${name}Schema = z.lazy(() => ${entryExpr});`);
2240
+ } else {
2241
+ lines.push(`export const ${name}Schema = ${entryExpr};`);
2242
+ }
2243
+ return lines.join("\n");
2244
+ }
2245
+
2246
+ // src/cli/generateSchemaFiles.ts
2247
+ function getSchemaOutputPath(sourceFile, appDir, outDir, rootDir) {
2248
+ let rel = sourceFile.replace(/\\/g, "/");
2249
+ if (appDir !== "." && rel.startsWith(`${appDir}/`)) {
2250
+ rel = rel.slice(appDir.length + 1);
2251
+ }
2252
+ const idx = rel.lastIndexOf("/");
2253
+ const relDir = idx >= 0 ? rel.slice(0, idx) : "";
2254
+ return path4.resolve(rootDir, outDir, relDir, "zod.js");
2255
+ }
2256
+ function getRuntimeSchemaPath(filePath, appDir, outDir, rootDir) {
2257
+ let rel = filePath.replace(/\\/g, "/");
2258
+ if (appDir !== "." && rel.startsWith(`${appDir}/`)) {
2259
+ rel = rel.slice(appDir.length + 1);
2260
+ } else if (rel.startsWith(`${outDir}/`)) {
2261
+ rel = rel.slice(outDir.length + 1);
2262
+ }
2263
+ const idx = rel.lastIndexOf("/");
2264
+ const relDir = idx >= 0 ? rel.slice(0, idx) : "";
2265
+ return path4.resolve(rootDir, outDir, relDir, "zod.js");
2266
+ }
2267
+ function getHelpersImportPath(relDir) {
2268
+ if (!relDir) return `./${HELPERS_FILENAME}`;
2269
+ const depth = relDir.split("/").filter(Boolean).length;
2270
+ return `${"../".repeat(depth)}${HELPERS_FILENAME}`;
2271
+ }
2272
+ function generateSchemaFileSource(sources, allTypes, helpersImportPath) {
2273
+ const resolveType = (name) => allTypes.get(name)?.runtimeType;
2274
+ const lines = ["import { z } from 'zod';"];
2275
+ const schemaBlocks = [];
2276
+ for (const source of sources) {
2277
+ const { schemaName, typeInfo } = source;
2278
+ if (!typeInfo) {
2279
+ continue;
2280
+ }
2281
+ const coerce = /(?:Query|Params)$/.test(schemaName);
2282
+ const block = [`// ${schemaName}`];
2283
+ const schemaCode = generateZodSchemaSource(typeInfo, resolveType, schemaName, coerce).replace(
2284
+ /^import \{ z \} from 'zod';\s*\n\s*\n/,
2285
+ ""
2286
+ );
2287
+ block.push(schemaCode);
2288
+ block.push("");
2289
+ schemaBlocks.push(block.join("\n"));
2290
+ }
2291
+ const allSchemaCode = schemaBlocks.join("\n");
2292
+ if (helpersImportPath && usesCoerceHelpers(allSchemaCode)) {
2293
+ lines.push(`import { coerceNumber, coerceBoolean } from '${helpersImportPath}';`);
2294
+ }
2295
+ lines.push("");
2296
+ lines.push(...schemaBlocks);
2297
+ return lines.join("\n").replace(/\n+$/, "\n");
2298
+ }
2299
+ async function generateSchemaFiles(routes, rootDir, appDir, outDir) {
2300
+ if (routes.length === 0) return;
2301
+ const { sources, allTypesByFile } = collectRouteSchemaSources(routes, rootDir);
2302
+ const sourcesByFile = /* @__PURE__ */ new Map();
2303
+ for (const source of sources) {
2304
+ let list = sourcesByFile.get(source.filePath);
2305
+ if (!list) {
2306
+ list = [];
2307
+ sourcesByFile.set(source.filePath, list);
2308
+ }
2309
+ list.push(source);
2310
+ }
2311
+ const fileEntries = [];
2312
+ for (const [filePath, fileSources] of sourcesByFile) {
2313
+ const relFile = path4.relative(rootDir, filePath).replace(/\\/g, "/");
2314
+ const outputPath = getSchemaOutputPath(relFile, appDir, outDir, rootDir);
2315
+ const allTypes = allTypesByFile.get(filePath) ?? /* @__PURE__ */ new Map();
2316
+ let relForDir = relFile;
2317
+ if (appDir !== "." && relForDir.startsWith(`${appDir}/`)) {
2318
+ relForDir = relForDir.slice(appDir.length + 1);
2319
+ }
2320
+ const dirIdx = relForDir.lastIndexOf("/");
2321
+ const zodRelDir = dirIdx >= 0 ? relForDir.slice(0, dirIdx) : "";
2322
+ const helpersImportPath = getHelpersImportPath(zodRelDir);
2323
+ const source = generateSchemaFileSource(fileSources, allTypes, helpersImportPath);
2324
+ fileEntries.push({ outputPath, source });
2325
+ }
2326
+ const allSourceCode = fileEntries.map((e) => e.source).join("\n");
2327
+ if (usesCoerceHelpers(allSourceCode)) {
2328
+ const helpersPath = path4.resolve(rootDir, outDir, HELPERS_FILENAME);
2329
+ await writeSchemaFile(helpersPath, generateHelpersFileSource());
2330
+ }
2331
+ await Promise.all(
2332
+ fileEntries.map(({ outputPath, source }) => writeSchemaFile(outputPath, source))
2333
+ );
2334
+ }
2335
+ async function writeSchemaFile(outputPath, source) {
2336
+ await fs2.mkdir(path4.dirname(outputPath), { recursive: true });
2337
+ await fs2.writeFile(outputPath, source, "utf-8");
2338
+ }
2339
+
2340
+ // src/server/createServer.ts
2341
+ var DEFAULT_BODY_LIMIT = 10 * 1024 * 1024;
2342
+ function toWebRequest(req, bodyLimit = DEFAULT_BODY_LIMIT) {
2343
+ const forwardedProto = req.headers["x-forwarded-proto"];
2344
+ const protocol = Array.isArray(forwardedProto) ? forwardedProto[0]?.split(",")[0]?.trim() ?? "http" : forwardedProto?.split(",")[0]?.trim() ?? "http";
2345
+ const host = req.headers.host ?? "localhost";
2346
+ const url = new URL(req.url ?? "/", `${protocol}://${host}`);
2347
+ const headers = nodeHttpToWebHeaders(req);
2348
+ const method = req.method ?? "GET";
2349
+ if (method === "GET" || method === "HEAD") {
2350
+ return new Request(url.toString(), { method, headers });
2351
+ }
2352
+ const stream = Readable2.toWeb(req);
2353
+ const limitedStream = limitStreamSize(stream, bodyLimit);
2354
+ return new Request(url.toString(), {
2355
+ method,
2356
+ headers,
2357
+ body: limitedStream,
2358
+ duplex: "half"
2359
+ });
2360
+ }
2361
+ function limitStreamSize(stream, maxSize) {
2362
+ let totalSize = 0;
2363
+ const reader = stream.getReader();
2364
+ return new ReadableStream({
2365
+ async pull(controller) {
2366
+ const { done, value } = await reader.read();
2367
+ if (done) {
2368
+ controller.close();
2369
+ reader.releaseLock();
2370
+ return;
2371
+ }
2372
+ totalSize += value.byteLength;
2373
+ if (totalSize > maxSize) {
2374
+ controller.error(new Error(`\u8BF7\u6C42\u4F53\u8D85\u8FC7\u5927\u5C0F\u9650\u5236 ${maxSize} \u5B57\u8282`));
2375
+ reader.releaseLock();
2376
+ return;
2377
+ }
2378
+ controller.enqueue(value);
2379
+ },
2380
+ cancel(reason) {
2381
+ reader.cancel(reason);
2382
+ }
2383
+ });
2384
+ }
2385
+ function findAllowedMethods(routes, path9) {
2386
+ const methods = /* @__PURE__ */ new Set();
2387
+ for (const route of routes) {
2388
+ if (route.urlPath === path9) {
2389
+ methods.add(route.method);
2390
+ continue;
2391
+ }
2392
+ if (route.isDynamic) {
2393
+ const params = matchDynamicPath(route.urlPath, path9, route.paramNames, route.isCatchAll);
2394
+ if (params !== null) {
2395
+ methods.add(route.method);
2396
+ }
2397
+ }
2398
+ }
2399
+ return Array.from(methods);
2400
+ }
2401
+ function createServer(options) {
2402
+ const {
2403
+ routes,
2404
+ rootDir,
2405
+ appDir,
2406
+ outDir,
2407
+ cors: corsOption,
2408
+ responseFormat,
2409
+ errorFormat,
2410
+ onError,
2411
+ config,
2412
+ wsRoutes,
2413
+ middlewares: globalMiddlewares,
2414
+ injectors: globalInjectors,
2415
+ helmet: helmetOption,
2416
+ bodyLimit = DEFAULT_BODY_LIMIT,
2417
+ http2: http2Option
2418
+ } = options;
2419
+ const routesRef = { current: routes, wsCurrent: wsRoutes ?? [] };
2420
+ const configMiddlewares = [];
2421
+ const corsMiddleware = corsOption === false ? null : corsOption === true || corsOption === void 0 ? cors() : cors(corsOption);
2422
+ if (corsMiddleware) configMiddlewares.push(corsMiddleware);
2423
+ if (helmetOption) {
2424
+ const helmOpts = typeof helmetOption === "object" ? helmetOption : {};
2425
+ configMiddlewares.push(helmet(helmOpts));
2426
+ }
2427
+ const server = (() => {
2428
+ if (http2Option) {
2429
+ const h2Opts = typeof http2Option === "object" ? http2Option : {};
2430
+ return createHttp2SecureServer({
2431
+ key: h2Opts.key ? readFileSync(h2Opts.key) : void 0,
2432
+ cert: h2Opts.cert ? readFileSync(h2Opts.cert) : void 0,
2433
+ allowHTTP1: true
2434
+ });
2435
+ }
2436
+ return createHttpServer();
2437
+ })();
2438
+ server.on("request", (req, res) => {
2439
+ const currentRoutes = routesRef.current;
2440
+ handleRequest(
2441
+ currentRoutes,
2442
+ rootDir,
2443
+ appDir,
2444
+ outDir,
2445
+ req,
2446
+ res,
2447
+ configMiddlewares,
2448
+ responseFormat,
2449
+ errorFormat,
2450
+ onError,
2451
+ config,
2452
+ globalMiddlewares,
2453
+ globalInjectors,
2454
+ bodyLimit
2455
+ ).catch(() => {
2456
+ res.statusCode = 500;
2457
+ res.end();
2458
+ });
2459
+ });
2460
+ if (routesRef.wsCurrent.length > 0) {
2461
+ attachWebSocket({ server, routesRef, rootDir, config, errorFormat, globalMiddlewares });
2462
+ }
2463
+ return { server, routesRef };
2464
+ }
2465
+ async function handleRequest(routes, rootDir, appDir, outDir, req, res, configMiddlewares, responseFormat, errorFormat, onError, config, globalMiddlewares, globalInjectors, bodyLimit) {
2466
+ const request = toWebRequest(req, bodyLimit);
2467
+ const method = request.method.toUpperCase();
2468
+ const urlPath = new URL(request.url).pathname;
2469
+ const ctx = createContext(request, {}, config, getClientIp(req));
2470
+ const meta = ctx.meta;
2471
+ const routePipeline = async () => {
2472
+ const match = matchRoute(routes, method, urlPath);
2473
+ if (!match) {
2474
+ const allowedMethods = findAllowedMethods(routes, urlPath);
2475
+ if (allowedMethods.length > 0) {
2476
+ throw new MethodNotAllowedError(method, urlPath, allowedMethods);
2477
+ }
2478
+ throw new RouteNotFoundError(urlPath);
2479
+ }
2480
+ ctx.params = match.params;
2481
+ const { route } = match;
2482
+ const absoluteFilePath = path5.resolve(rootDir, route.filePath);
2483
+ const routeModule = await loadRouteModule(absoluteFilePath, route.method);
2484
+ const input = await resolveInput(route.method, request);
2485
+ const inputType = getInputTypeForMethod(route.method);
2486
+ const schemaPath = getRuntimeSchemaPath(route.filePath, appDir, outDir, rootDir);
2487
+ const result = await validateInput(schemaPath, route.method, inputType, input);
2488
+ if (!result.valid) {
2489
+ throw new ValidationError("\u53C2\u6570\u6821\u9A8C\u5931\u8D25", result.issues);
2490
+ }
2491
+ const body = hasBody(route.method) ? result.data : void 0;
2492
+ const mergedInjectors = globalInjectors ? { ...globalInjectors, ...route.injectors } : route.injectors;
2493
+ let response = await invokeHandler(
2494
+ routeModule.handler,
2495
+ ctx,
2496
+ body,
2497
+ route.middlewares,
2498
+ mergedInjectors
2499
+ );
2500
+ if (responseFormat && response.status >= 200 && response.status < 300) {
2501
+ const contentType = response.headers.get("Content-Type") ?? "";
2502
+ if (contentType.includes("application/json")) {
2503
+ const data = await response.json();
2504
+ const formatted = responseFormat(data, ctx);
2505
+ const { toResponse: toResponse2 } = await Promise.resolve().then(() => (init_toResponse(), toResponse_exports));
2506
+ response = await toResponse2(formatted, meta);
2507
+ }
2508
+ }
2509
+ return response;
2510
+ };
2511
+ try {
2512
+ let response;
2513
+ const outerMiddlewares = [];
2514
+ if (configMiddlewares.length > 0) outerMiddlewares.push(...configMiddlewares);
2515
+ if (globalMiddlewares && globalMiddlewares.length > 0) {
2516
+ outerMiddlewares.push(...globalMiddlewares);
2517
+ }
2518
+ if (outerMiddlewares.length > 0) {
2519
+ response = await compose(outerMiddlewares, ctx, routePipeline);
2520
+ } else {
2521
+ response = await routePipeline();
2522
+ }
2523
+ await sendNodeResponse(response, res);
2524
+ } catch (err) {
2525
+ const errorResponse = buildErrorResponse(err, ctx, errorFormat);
2526
+ await sendNodeResponse(mergeMeta(errorResponse, meta), res);
2527
+ if (onError) {
2528
+ try {
2529
+ await onError(err, ctx);
2530
+ } catch {
2531
+ }
2532
+ }
2533
+ }
2534
+ }
2535
+
2536
+ // src/server/startServer.ts
2537
+ function applyPluginWrappers(server, handlerWrappers, upgradeWrappers) {
2538
+ if (handlerWrappers.length > 0) {
2539
+ const listeners = server.listeners("request");
2540
+ const original = listeners[0];
2541
+ if (original) {
2542
+ server.removeAllListeners("request");
2543
+ let handler = original;
2544
+ for (const wrap of handlerWrappers) {
2545
+ handler = wrap(handler);
2546
+ }
2547
+ server.on("request", handler);
2548
+ }
2549
+ }
2550
+ if (upgradeWrappers.length > 0) {
2551
+ const listeners = server.listeners("upgrade");
2552
+ const original = listeners[0];
2553
+ server.removeAllListeners("upgrade");
2554
+ let upgrade = original;
2555
+ for (const wrap of upgradeWrappers) {
2556
+ upgrade = wrap(upgrade);
2557
+ }
2558
+ if (upgrade) {
2559
+ server.on("upgrade", upgrade);
2560
+ }
2561
+ }
2562
+ }
2563
+
2564
+ // src/cli/generateRoutes.ts
2565
+ import fs3 from "fs";
2566
+ import path6 from "path";
2567
+
2568
+ // src/middleware/loadMiddlewares.ts
2569
+ var middlewareCache = /* @__PURE__ */ new Map();
2570
+ function invalidateMiddlewareCache() {
2571
+ middlewareCache.clear();
2572
+ }
2573
+ function getCachedMiddlewares(absPath) {
2574
+ return middlewareCache.get(absPath);
2575
+ }
2576
+ function setCachedMiddlewares(absPath, bundle) {
2577
+ middlewareCache.set(absPath, bundle);
2578
+ }
2579
+ async function loadMiddlewaresFile(filePath) {
2580
+ try {
2581
+ const module = await importWithCacheBust(filePath);
2582
+ const middlewares = module.default ?? module.middlewares ?? [];
2583
+ if (!Array.isArray(middlewares)) {
2584
+ console.warn(`[faapi] middlewares.ts \u5E94\u5BFC\u51FA\u6570\u7EC4\uFF0C\u5DF2\u5FFD\u7565: ${filePath}`);
2585
+ return { middlewares: [], injectors: {} };
2586
+ }
2587
+ const validMiddlewares = middlewares.filter((m) => {
2588
+ if (typeof m !== "function") {
2589
+ console.warn(`[faapi] \u65E0\u6548\u7684\u4E2D\u95F4\u4EF6\u9879\uFF08\u5E94\u4E3A\u51FD\u6570\uFF09\uFF0C\u5DF2\u5FFD\u7565: ${typeof m}`);
2590
+ return false;
2591
+ }
2592
+ return true;
2593
+ });
2594
+ const injectors = module.injectors ?? {};
2595
+ if (typeof injectors !== "object" || injectors === null) {
2596
+ console.warn(`[faapi] injectors \u5E94\u5BFC\u51FA\u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565: ${filePath}`);
2597
+ return { middlewares: validMiddlewares, injectors: {} };
2598
+ }
2599
+ const validInjectors = {};
2600
+ for (const [name, injector] of Object.entries(injectors)) {
2601
+ if (typeof injector !== "function") {
2602
+ console.warn(`[faapi] \u6CE8\u5165\u5668 ${name} \u5E94\u4E3A\u51FD\u6570\uFF0C\u5DF2\u5FFD\u7565`);
2603
+ continue;
2604
+ }
2605
+ validInjectors[name] = injector;
2606
+ }
2607
+ return { middlewares: validMiddlewares, injectors: validInjectors };
2608
+ } catch {
2609
+ return { middlewares: [], injectors: {} };
2610
+ }
2611
+ }
2612
+
2613
+ // src/cli/generateRoutes.ts
2614
+ async function hydrateRoutes(manifest) {
2615
+ const hydrateRoute = async (serialized) => {
2616
+ const bundle = await loadMiddlewarePaths(serialized.middlewarePaths);
2617
+ return {
2618
+ method: serialized.method,
2619
+ urlPath: serialized.urlPath,
2620
+ filePath: serialized.filePath,
2621
+ paramNames: serialized.paramNames,
2622
+ isDynamic: serialized.isDynamic,
2623
+ isCatchAll: serialized.isCatchAll,
2624
+ middlewares: bundle?.middlewares,
2625
+ injectors: bundle?.injectors
2626
+ };
2627
+ };
2628
+ const hydrateWsRoute = async (serialized) => {
2629
+ const bundle = await loadMiddlewarePaths(serialized.middlewarePaths);
2630
+ return {
2631
+ urlPath: serialized.urlPath,
2632
+ filePath: serialized.filePath,
2633
+ paramNames: serialized.paramNames,
2634
+ isDynamic: serialized.isDynamic,
2635
+ isCatchAll: serialized.isCatchAll,
2636
+ middlewares: bundle?.middlewares,
2637
+ injectors: bundle?.injectors
2638
+ };
2639
+ };
2640
+ const routes = await Promise.all(manifest.routes.map(hydrateRoute));
2641
+ const wsRoutes = await Promise.all(manifest.wsRoutes.map(hydrateWsRoute));
2642
+ return { routes, wsRoutes };
2643
+ }
2644
+ async function loadMiddlewarePaths(middlewarePaths) {
2645
+ if (middlewarePaths.length === 0) return void 0;
2646
+ const mergedMiddlewares = [];
2647
+ const mergedInjectors = {};
2648
+ for (const absMwPath of middlewarePaths) {
2649
+ let bundle = getCachedMiddlewares(absMwPath);
2650
+ if (bundle === void 0) {
2651
+ bundle = await loadMiddlewaresFile(absMwPath);
2652
+ setCachedMiddlewares(absMwPath, bundle);
2653
+ }
2654
+ mergedMiddlewares.push(...bundle.middlewares);
2655
+ for (const [name, injector] of Object.entries(bundle.injectors)) {
2656
+ mergedInjectors[name] = injector;
2657
+ }
2658
+ }
2659
+ return { middlewares: mergedMiddlewares, injectors: mergedInjectors };
2660
+ }
2661
+
2662
+ // src/cli/loadPlugins.ts
2663
+ async function loadPlugins(declarations, ctx) {
2664
+ const handlerWrappers = [];
2665
+ const upgradeWrappers = [];
2666
+ if (!declarations || declarations.length === 0) {
2667
+ return { handlerWrappers, upgradeWrappers };
2668
+ }
2669
+ const fullCtx = {
2670
+ ...ctx,
2671
+ wrapHandler: (fn) => {
2672
+ handlerWrappers.push(fn);
2673
+ },
2674
+ wrapUpgradeHandler: (fn) => {
2675
+ upgradeWrappers.push(fn);
2676
+ }
2677
+ };
2678
+ const loaded = /* @__PURE__ */ new Set();
2679
+ for (const decl of declarations) {
2680
+ const { specifier, options, enable } = resolveDeclaration(decl);
2681
+ if (enable === false) continue;
2682
+ if (loaded.has(specifier)) {
2683
+ console.warn(`! Plugin already loaded: ${specifier}, skipping`);
2684
+ continue;
2685
+ }
2686
+ loaded.add(specifier);
2687
+ try {
2688
+ const mod = await import(specifier);
2689
+ const plugin = mod.default ?? mod;
2690
+ if (typeof plugin.setup !== "function") {
2691
+ console.warn(`! Plugin ${specifier} has no setup function, skipping`);
2692
+ continue;
2693
+ }
2694
+ await plugin.setup({ ...fullCtx, options });
2695
+ console.log(`- Plugin loaded: ${plugin.name ?? specifier}`);
2696
+ } catch (err) {
2697
+ console.warn(
2698
+ `! Failed to load plugin ${specifier}: ${err instanceof Error ? err.message : String(err)}`
2699
+ );
2700
+ }
2701
+ }
2702
+ return { handlerWrappers, upgradeWrappers };
2703
+ }
2704
+ function resolveDeclaration(decl) {
2705
+ if (typeof decl === "string") {
2706
+ return { specifier: decl };
2707
+ }
2708
+ if (Array.isArray(decl)) {
2709
+ const [specifier, options] = decl;
2710
+ return { specifier, options };
2711
+ }
2712
+ if ("package" in decl) {
2713
+ return { specifier: decl.package, options: decl.options, enable: decl.enable };
2714
+ }
2715
+ if ("path" in decl) {
2716
+ return { specifier: decl.path, options: decl.options, enable: decl.enable };
2717
+ }
2718
+ throw new Error(`Invalid plugin declaration: ${JSON.stringify(decl)}`);
2719
+ }
2720
+
2721
+ // src/cli/createAppCore.ts
2722
+ var DEFAULT_OUT_DIR = "dist";
2723
+ var DEFAULT_APP_DIR = "src";
2724
+ var DEFAULT_PORT = 3e3;
2725
+ var ROUTES_FILE = "faapi-routes.js";
2726
+ var FAAPI_CONFIG_KEYS = /* @__PURE__ */ new Set([
2727
+ "cors",
2728
+ "responseFormat",
2729
+ "errorFormat",
2730
+ "lifecycle",
2731
+ "middlewares",
2732
+ "injectors",
2733
+ "extendContext",
2734
+ "plugins",
2735
+ "helmet",
2736
+ "bodyLimit",
2737
+ "logger",
2738
+ "http2"
2739
+ ]);
2740
+ function isFaapiConfigKey(key) {
2741
+ return FAAPI_CONFIG_KEYS.has(key);
2742
+ }
2743
+ async function createAppBase(options) {
2744
+ const rootDir = options?.rootDir ?? process.cwd();
2745
+ const outDir = process.env.FAAPI_OUT_DIR ?? DEFAULT_OUT_DIR;
2746
+ const routesPath = path7.resolve(rootDir, outDir, ROUTES_FILE);
2747
+ if (!fs4.existsSync(routesPath)) {
2748
+ throw new Error(
2749
+ `[faapi] ${outDir}/${ROUTES_FILE} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6267\u884C \`faapi build\`\uFF08\u6216 \`faapi dev\`\uFF09\u751F\u6210\u4EA7\u7269\u3002`
2750
+ );
2751
+ }
2752
+ const config = await loadConfig(rootDir, outDir);
2753
+ const appDir = options?.appDir ?? process.env.FAAPI_APP_DIR ?? DEFAULT_APP_DIR;
2754
+ const patterns = appDir === "." ? ["api/**/*.ts"] : [`${appDir}/api/**/*.ts`];
2755
+ const serialized = await importWithCacheBust(routesPath);
2756
+ const hydrated = await hydrateRoutes(serialized);
2757
+ let sorted = sortRoutes(hydrated.routes);
2758
+ let wsRoutes = hydrated.wsRoutes;
2759
+ const conflicts = detectRouteConflicts(sorted);
2760
+ if (conflicts.length > 0) {
2761
+ for (const conflict of conflicts) {
2762
+ console.warn(`! \u8DEF\u7531\u51B2\u7A81: ${conflict.method} ${conflict.urlPath}`);
2763
+ for (const file of conflict.files) {
2764
+ console.warn(` - ${file}`);
2765
+ }
2766
+ }
2767
+ }
2768
+ const pluginConfig = config ? Object.fromEntries(Object.entries(config).filter(([k]) => !isFaapiConfigKey(k))) : {};
2769
+ const { server, routesRef } = createServer({
2770
+ routes: sorted,
2771
+ rootDir,
2772
+ appDir,
2773
+ outDir,
2774
+ cors: config?.cors ?? true,
2775
+ responseFormat: config?.responseFormat,
2776
+ errorFormat: config?.errorFormat,
2777
+ onError: config?.lifecycle?.onError,
2778
+ config: config ?? void 0,
2779
+ wsRoutes,
2780
+ middlewares: config?.middlewares,
2781
+ injectors: config?.injectors,
2782
+ helmet: config?.helmet,
2783
+ bodyLimit: config?.bodyLimit,
2784
+ http2: config?.http2
2785
+ });
2786
+ const { handlerWrappers, upgradeWrappers } = await loadPlugins(config?.plugins, {
2787
+ rootDir,
2788
+ routes: sorted,
2789
+ server,
2790
+ config: pluginConfig
2791
+ });
2792
+ applyPluginWrappers(server, handlerWrappers, upgradeWrappers);
2793
+ let closed = false;
2794
+ const app = {
2795
+ server: null,
2796
+ routes: sorted,
2797
+ wsRoutes,
2798
+ rootDir,
2799
+ async listen(listenPort) {
2800
+ const envPort = process.env.PORT ? Number(process.env.PORT) : void 0;
2801
+ const actualPort = listenPort ?? options?.port ?? envPort ?? DEFAULT_PORT;
2802
+ return new Promise((resolve) => {
2803
+ server.listen(actualPort, async () => {
2804
+ const address = server.address();
2805
+ const p = typeof address === "object" && address !== null ? address.port : actualPort;
2806
+ console.log("faapi server started");
2807
+ console.log(`- Local: http://localhost:${p}`);
2808
+ console.log("- Loaded routes:");
2809
+ for (const route of sorted) {
2810
+ console.log(` ${route.method.padEnd(6)}${route.urlPath} ${route.filePath}`);
2811
+ }
2812
+ if (wsRoutes.length > 0) {
2813
+ console.log("- WebSocket routes:");
2814
+ for (const route of wsRoutes) {
2815
+ console.log(` WS ${route.urlPath} ${route.filePath}`);
2816
+ }
2817
+ }
2818
+ if (config?.lifecycle?.onClose) {
2819
+ const graceful = async (signal) => {
2820
+ console.log(`
2821
+ - Received ${signal}, shutting down...`);
2822
+ await app.close();
2823
+ process.exit(0);
2824
+ };
2825
+ process.on("SIGTERM", () => void graceful("SIGTERM"));
2826
+ process.on("SIGINT", () => void graceful("SIGINT"));
2827
+ }
2828
+ if (config?.lifecycle?.onReady) {
2829
+ await config.lifecycle.onReady({ rootDir, routes: sorted, server });
2830
+ console.log("- onReady hook executed");
2831
+ }
2832
+ app.server = server;
2833
+ resolve(server);
2834
+ });
2835
+ });
2836
+ },
2837
+ async inject(injectOpts) {
2838
+ const {
2839
+ method = "GET",
2840
+ path: reqPath = "/",
2841
+ headers: reqHeaders = {},
2842
+ query,
2843
+ body
2844
+ } = injectOpts ?? {};
2845
+ const queryStr = query ? "?" + new URLSearchParams(Object.entries(query).map(([k, v]) => [k, String(v)])).toString() : "";
2846
+ return new Promise((resolve, reject) => {
2847
+ const mockRes = {
2848
+ statusCode: 200,
2849
+ _headers: {},
2850
+ _body: Buffer.alloc(0),
2851
+ setHeader(name, value) {
2852
+ this._headers[name.toLowerCase()] = value;
2853
+ },
2854
+ writeHead(status, headers) {
2855
+ this.statusCode = status;
2856
+ if (headers) {
2857
+ Object.assign(this._headers, headers);
2858
+ }
2859
+ },
2860
+ end(data) {
2861
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data ?? "");
2862
+ this._body = buf;
2863
+ resolve({
2864
+ status: this.statusCode,
2865
+ headers: new Headers(this._headers),
2866
+ body: this.parseBody()
2867
+ });
2868
+ },
2869
+ parseBody() {
2870
+ try {
2871
+ return JSON.parse(this._body.toString());
2872
+ } catch {
2873
+ return this._body.toString();
2874
+ }
2875
+ }
2876
+ };
2877
+ const listeners = server.listeners("request");
2878
+ const handler = listeners[listeners.length - 1];
2879
+ if (typeof handler !== "function") {
2880
+ reject(new Error("No request handler found"));
2881
+ return;
2882
+ }
2883
+ const mockReq = new PassThrough({
2884
+ read() {
2885
+ this.push(null);
2886
+ }
2887
+ });
2888
+ mockReq.method = method;
2889
+ mockReq.url = `${reqPath}${queryStr}`;
2890
+ mockReq.headers = {
2891
+ ...reqHeaders,
2892
+ host: "localhost",
2893
+ "content-type": body !== void 0 ? "application/json" : void 0
2894
+ };
2895
+ if (body !== void 0) {
2896
+ mockReq.push(JSON.stringify(body));
2897
+ }
2898
+ handler(
2899
+ mockReq,
2900
+ mockRes
2901
+ );
2902
+ });
2903
+ },
2904
+ async close() {
2905
+ if (closed) return;
2906
+ closed = true;
2907
+ server.closeIdleConnections?.();
2908
+ server.closeAllConnections?.();
2909
+ if (config?.lifecycle?.onClose) {
2910
+ await config.lifecycle.onClose({ rootDir, routes: sorted, server });
2911
+ }
2912
+ return new Promise((resolve) => {
2913
+ server.close((err) => {
2914
+ if (err) console.error("Error closing server:", err);
2915
+ app.server = null;
2916
+ resolve();
2917
+ });
2918
+ });
2919
+ }
2920
+ };
2921
+ const ctx = {
2922
+ rootDir,
2923
+ appDir,
2924
+ outDir,
2925
+ patterns,
2926
+ server,
2927
+ routesRef,
2928
+ config,
2929
+ updateRoutes(newRoutes, newWsRoutes) {
2930
+ sorted = newRoutes;
2931
+ wsRoutes = newWsRoutes;
2932
+ app.routes = newRoutes;
2933
+ app.wsRoutes = newWsRoutes;
2934
+ routesRef.current = newRoutes;
2935
+ routesRef.wsCurrent = newWsRoutes;
2936
+ }
2937
+ };
2938
+ return { app, ctx };
2939
+ }
2940
+
2941
+ // src/router/scanRoutes.ts
2942
+ import fg from "fast-glob";
2943
+ import path8 from "path";
2944
+ import fs5 from "fs";
2945
+
2946
+ // src/router/constants.ts
2947
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
2948
+ var HTTP_METHOD_SET = new Set(HTTP_METHODS);
2949
+ function isHttpMethod(value) {
2950
+ return HTTP_METHOD_SET.has(value);
2951
+ }
2952
+
2953
+ // src/utils/normalizePath.ts
2954
+ function normalizePath(path9) {
2955
+ if (!path9) return "";
2956
+ let result = path9.replace(/\\/g, "/");
2957
+ result = result.replace(/\/+/g, "/");
2958
+ result = result.replace(/\/+$/, "");
2959
+ if (result && !result.startsWith("/")) {
2960
+ result = "/" + result;
2961
+ }
2962
+ return result;
2963
+ }
2964
+
2965
+ // src/router/parseRouteFile.ts
2966
+ function dynamicSegmentToParam(segment) {
2967
+ const match = segment.match(/^\[(.+)\]$/);
2968
+ if (match) {
2969
+ return ":" + match[1];
2970
+ }
2971
+ return segment;
2972
+ }
2973
+ function extractParamNames(urlPath) {
2974
+ const params = [];
2975
+ const segments = urlPath.split("/");
2976
+ for (const segment of segments) {
2977
+ if (segment.startsWith(":...")) {
2978
+ params.push(segment.slice(4));
2979
+ } else if (segment.startsWith(":")) {
2980
+ params.push(segment.slice(1));
2981
+ }
2982
+ }
2983
+ return params;
2984
+ }
2985
+ function isCatchAllSegment(segment) {
2986
+ return /^\[\.\.\..+\]$/.test(segment);
2987
+ }
2988
+ function isRouteGroup(segment) {
2989
+ return /^\(.+\)$/.test(segment);
2990
+ }
2991
+ function filePathToUrlPath(filePath, appDir = ".") {
2992
+ const withoutPrefix = filePath.startsWith(appDir + "/") ? filePath.slice(appDir.length + 1) : filePath;
2993
+ const lastSlashIndex = withoutPrefix.lastIndexOf("/");
2994
+ const dirPath = lastSlashIndex === -1 ? "" : withoutPrefix.slice(0, lastSlashIndex);
2995
+ if (!dirPath) {
2996
+ return "";
2997
+ }
2998
+ const segments = dirPath.split("/").filter((s) => !isRouteGroup(s)).map(dynamicSegmentToParam);
2999
+ return normalizePath(segments.join("/"));
3000
+ }
3001
+
3002
+ // src/router/scanRoutes.ts
3003
+ function toProdAbsPath(sourceAbsPath, rootDir, appDir, prodDir) {
3004
+ let rel = path8.relative(rootDir, sourceAbsPath).replace(/\\/g, "/");
3005
+ if (appDir !== "." && rel.startsWith(`${appDir}/`)) {
3006
+ rel = rel.slice(appDir.length + 1);
3007
+ }
3008
+ const prodRel = `${prodDir}/${rel.replace(/\.ts$/, ".js")}`;
3009
+ return path8.resolve(rootDir, prodRel);
3010
+ }
3011
+ async function findMergedMiddlewares(routeFilePath, rootDir, appDir, prodDir) {
3012
+ const routeDir = path8.dirname(routeFilePath);
3013
+ const resolvedRoot = path8.resolve(rootDir);
3014
+ const mwPaths = [];
3015
+ let currentDir = path8.resolve(rootDir, routeDir);
3016
+ while (true) {
3017
+ if (prodDir) {
3018
+ const mwPath = path8.join(currentDir, "middlewares.js");
3019
+ const absMwPath = path8.resolve(rootDir, mwPath);
3020
+ const prodAbsMwPath = toProdAbsPath(absMwPath, rootDir, appDir, prodDir);
3021
+ if (fs5.existsSync(prodAbsMwPath)) {
3022
+ mwPaths.push(prodAbsMwPath);
3023
+ }
3024
+ } else {
3025
+ for (const ext of [".ts", ".js"]) {
3026
+ const mwPath = path8.join(currentDir, `middlewares${ext}`);
3027
+ const absMwPath = path8.resolve(rootDir, mwPath);
3028
+ if (fs5.existsSync(absMwPath)) {
3029
+ mwPaths.push(absMwPath);
3030
+ break;
3031
+ }
3032
+ }
3033
+ }
3034
+ if (currentDir === resolvedRoot) break;
3035
+ const parentDir = path8.dirname(currentDir);
3036
+ if (parentDir === currentDir) break;
3037
+ currentDir = parentDir;
3038
+ }
3039
+ if (mwPaths.length === 0) return void 0;
3040
+ mwPaths.reverse();
3041
+ const mergedMiddlewares = [];
3042
+ const mergedInjectors = {};
3043
+ for (const absMwPath of mwPaths) {
3044
+ let bundle = getCachedMiddlewares(absMwPath);
3045
+ if (bundle === void 0) {
3046
+ bundle = await loadMiddlewaresFile(absMwPath);
3047
+ setCachedMiddlewares(absMwPath, bundle);
3048
+ }
3049
+ mergedMiddlewares.push(...bundle.middlewares);
3050
+ for (const [name, injector] of Object.entries(bundle.injectors)) {
3051
+ mergedInjectors[name] = injector;
3052
+ }
3053
+ }
3054
+ if (mergedMiddlewares.length === 0 && Object.keys(mergedInjectors).length === 0) {
3055
+ return void 0;
3056
+ }
3057
+ return { middlewares: mergedMiddlewares, injectors: mergedInjectors };
3058
+ }
3059
+ async function extractMethodsFromHandler(absPath) {
3060
+ try {
3061
+ const module = await importWithCacheBust(absPath);
3062
+ const methods = [];
3063
+ for (const key of Object.keys(module)) {
3064
+ if (isHttpMethod(key) && typeof module[key] === "function") {
3065
+ methods.push(key);
3066
+ }
3067
+ }
3068
+ return methods;
3069
+ } catch (err) {
3070
+ const reason = err instanceof Error ? err.message : String(err);
3071
+ console.warn(`[faapi] \u52A0\u8F7D\u8DEF\u7531\u6587\u4EF6\u5931\u8D25 ${absPath}: ${reason}`);
3072
+ return [];
3073
+ }
3074
+ }
3075
+ async function hasWsExport(absPath) {
3076
+ try {
3077
+ const module = await importWithCacheBust(absPath);
3078
+ return typeof module["WS"] === "function";
3079
+ } catch (err) {
3080
+ const reason = err instanceof Error ? err.message : String(err);
3081
+ console.warn(`[faapi] \u52A0\u8F7D\u8DEF\u7531\u6587\u4EF6\u5931\u8D25\uFF08WS \u68C0\u6D4B\uFF09${absPath}: ${reason}`);
3082
+ return false;
3083
+ }
3084
+ }
3085
+ async function scanRoutes(rootDir, patterns, appDir, prodDir) {
3086
+ const dir = appDir ?? ".";
3087
+ const files = await fg(patterns, {
3088
+ cwd: rootDir,
3089
+ onlyFiles: true,
3090
+ absolute: false
3091
+ });
3092
+ const routes = [];
3093
+ const wsRoutes = [];
3094
+ for (const file of files) {
3095
+ const normalizedFile = file.replace(/\\/g, "/");
3096
+ const fileName = normalizedFile.split("/").pop();
3097
+ if (fileName === "handler.ts" || fileName === "handler.js") {
3098
+ const absPath = path8.resolve(rootDir, normalizedFile);
3099
+ const importPath = prodDir ? toProdAbsPath(absPath, rootDir, dir, prodDir) : absPath;
3100
+ const urlPath = filePathToUrlPath(normalizedFile, dir);
3101
+ const paramNames = extractParamNames(urlPath);
3102
+ const isDynamic = paramNames.length > 0;
3103
+ const isCatchAll = normalizedFile.split("/").some(isCatchAllSegment);
3104
+ const middlewareBundle = await findMergedMiddlewares(normalizedFile, rootDir, dir, prodDir);
3105
+ const methods = await extractMethodsFromHandler(importPath);
3106
+ for (const method of methods) {
3107
+ routes.push({
3108
+ method,
3109
+ urlPath,
3110
+ filePath: normalizedFile,
3111
+ paramNames,
3112
+ isDynamic,
3113
+ isCatchAll: isCatchAll || void 0,
3114
+ middlewares: middlewareBundle?.middlewares,
3115
+ injectors: middlewareBundle?.injectors
3116
+ });
3117
+ }
3118
+ const hasWs = await hasWsExport(importPath);
3119
+ if (hasWs) {
3120
+ wsRoutes.push({
3121
+ urlPath,
3122
+ filePath: normalizedFile,
3123
+ paramNames,
3124
+ isDynamic,
3125
+ isCatchAll: isCatchAll || void 0,
3126
+ middlewares: middlewareBundle?.middlewares,
3127
+ injectors: middlewareBundle?.injectors
3128
+ });
3129
+ }
3130
+ continue;
3131
+ }
3132
+ }
3133
+ return { routes, wsRoutes };
3134
+ }
3135
+
3136
+ // src/cli/createDevApp.ts
3137
+ async function createDevApp(options) {
3138
+ const { app, ctx } = await createAppBase(options);
3139
+ const devApp = app;
3140
+ devApp.reloadRoutes = async () => {
3141
+ setLoadTimestamp(Date.now());
3142
+ invalidateMiddlewareCache();
3143
+ invalidateProgramCache();
3144
+ invalidateSchemaCache();
3145
+ const reScanned = await scanRoutes(ctx.rootDir, ctx.patterns, ctx.appDir, ctx.outDir);
3146
+ const sorted = sortRoutes(reScanned.routes);
3147
+ await generateSchemaFiles(sorted, ctx.rootDir, ctx.appDir, ctx.outDir);
3148
+ ctx.updateRoutes(sorted, reScanned.wsRoutes);
3149
+ };
3150
+ return devApp;
3151
+ }
3152
+
3153
+ // src/cli/createProdApp.ts
3154
+ async function createProdApp(options) {
3155
+ const { app } = await createAppBase(options);
3156
+ return app;
718
3157
  }
719
3158
  export {
720
3159
  SchemaExtractionError,
3160
+ collectRouteSchemaSources,
721
3161
  cors,
3162
+ createProdApp as createApp,
3163
+ createDevApp,
3164
+ createProdApp,
722
3165
  createProgram,
723
3166
  extractTypeInfo,
724
3167
  getInputTypeForMethod,
725
- getSchemaProperties,
3168
+ helmet,
3169
+ invalidateProgramCache,
726
3170
  loadConfig,
727
3171
  logger
728
3172
  };