-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
enable ai binding in next-dev module
- Loading branch information
1 parent
a4efc7b
commit 4be7860
Showing
3 changed files
with
69 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { Response } from 'miniflare'; | ||
import type { Request } from 'miniflare'; | ||
|
||
import { cloneHeaders } from "./wrangler"; | ||
|
||
type Fetcher = (req: Request) => Promise<Response>; | ||
|
||
export function getAIFetcher({ accountId, apiToken }: {accountId: string, apiToken: string}): Fetcher { | ||
// Tweaked version of the wrangler ai fetcher | ||
// (source: https://github.com/cloudflare/workers-sdk/blob/912bfe/packages/wrangler/src/ai/fetcher.ts) | ||
return async function AIFetcher(request: Request) { | ||
request.headers.delete("Host"); | ||
request.headers.delete("Content-Length"); | ||
|
||
const res = await performApiFetch(`/accounts/${accountId}/ai/run/proxy`, { | ||
method: "POST", | ||
headers: Object.fromEntries(request.headers.entries()), | ||
body: request.body as BodyInit, | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-ignore | ||
duplex: "half", | ||
}, apiToken); | ||
|
||
return new Response(res.body, { status: res.status }); | ||
}; | ||
} | ||
|
||
// (Heavily) Simplified version of performApiFetch from wrangler | ||
// (source: https://github.com/cloudflare/workers-sdk/blob/912bfe/packages/wrangler/src/cfetch/internal.ts#L18) | ||
export async function performApiFetch( | ||
resource: string, | ||
init: RequestInit = {}, | ||
apiToken: string, | ||
) { | ||
const method = init.method ?? "GET"; | ||
const headers = cloneHeaders(init.headers); | ||
headers["Authorization"] = `Bearer ${apiToken}`; | ||
|
||
return fetch(`https://api.cloudflare.com/client/v4${resource}`, { | ||
method, | ||
...init, | ||
headers, | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters