@faapi/faapi 0.0.0-canary.0 → 0.0.0-canary.02bea8c

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