@@ -2,7 +2,6 @@ import { Hono } from "@hono/hono";
2
2
import { bearerAuth } from "@hono/hono/bearer-auth" ;
3
3
import { assert , is } from "@core/unknownutil" ;
4
4
import { parseURL } from "ufo" ;
5
-
6
5
import { chooseEndpoint , convertToCustomEndpoint } from "./util.ts" ;
7
6
8
7
export function createApp (
@@ -18,15 +17,25 @@ export function createApp(
18
17
) {
19
18
const app = new Hono ( ) ;
20
19
21
- if ( is . String ( OPENAI_API_KEY ) ) {
22
- app . use ( "*" , bearerAuth ( { token : OPENAI_API_KEY } ) ) ;
23
- }
20
+ // Apply bearer authentication, but skip it for OPTIONS requests
21
+ app . use ( ( c , next ) => {
22
+ if ( c . req . method !== "OPTIONS" ) {
23
+ if ( is . String ( OPENAI_API_KEY ) ) {
24
+ return bearerAuth ( { token : OPENAI_API_KEY } ) ( c , next ) ;
25
+ }
26
+ }
27
+ // If the method is OPTIONS, skip the bearerAuth
28
+ return next ( ) ;
29
+ } ) ;
24
30
31
+ // Handle POST requests
25
32
app . post ( "*" , async ( c ) => {
26
33
const json = await c . req . raw . clone ( ) . json ( ) ;
27
34
const { model } = json ;
28
- /** if model name starts with "gpt" then it is a chat model */
35
+
36
+ // Validate the request payload
29
37
assert ( json , is . ObjectOf ( { model : is . String } ) ) ;
38
+
30
39
const endpoint = chooseEndpoint ( {
31
40
model,
32
41
ollamaEndpoint,
@@ -35,10 +44,27 @@ export function createApp(
35
44
36
45
const url = convertToCustomEndpoint ( c . req . url , parseURL ( endpoint ) ) ;
37
46
const req = new Request ( url , c . req . raw ) ;
47
+ req . headers . set ( "Host" , ollamaEndpoint ) ;
48
+ return fetch ( req ) ;
49
+ } ) ;
38
50
51
+ // Handle GET requests
52
+ app . get ( "*" , async ( c ) => {
53
+ const url = convertToCustomEndpoint ( c . req . url , parseURL ( ollamaEndpoint ) ) ;
54
+ const req = new Request ( url , c . req . raw ) ;
39
55
req . headers . set ( "Host" , ollamaEndpoint ) ;
40
56
return fetch ( req ) ;
41
57
} ) ;
42
58
59
+ // Handle OPTIONS requests
60
+ app . options ( "*" , ( c ) => {
61
+ c . header ( "Allow" , "OPTIONS, GET, POST" ) ;
62
+ c . header ( "Access-Control-Allow-Origin" , "*" ) ;
63
+ c . header ( "Access-Control-Allow-Methods" , "OPTIONS, GET, POST" ) ;
64
+ c . header ( "Access-Control-Allow-Headers" , "Content-Type, Authorization" ) ;
65
+ return c . body ( null , 204 ) ;
66
+ } ) ;
67
+
43
68
return app ;
44
69
}
70
+
0 commit comments