| 1 | import type * as runtime from "@cloudflare/workers-types"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import { Worker, WorkerEnvironment } from "../Workers/Worker.ts"; |
| 5 | import { makeClient, tryAiSearch } from "./QuerySearch.ts"; |
| 6 | import { |
| 7 | QuerySearchNamespace, |
| 8 | type QuerySearchNamespaceClient, |
| 9 | } from "./QuerySearchNamespace.ts"; |
| 10 | import type { SearchNamespace } from "./SearchNamespace.ts"; |
| 11 | |
| 12 | /** |
| 13 | * Runtime layer for {@link QuerySearchNamespace}. |
| 14 | */ |
| 15 | export const QuerySearchNamespaceBinding = Layer.effect( |
| 16 | QuerySearchNamespace, |
| 17 | Effect.gen(function* () { |
| 18 | const env = yield* WorkerEnvironment; |
| 19 | const host = yield* Worker; |
| 20 | |
| 21 | return Effect.fn(function* (namespace: SearchNamespace) { |
| 22 | if (!globalThis.__ALCHEMY_RUNTIME__) { |
| 23 | yield* host.bind`${namespace}`({ |
| 24 | bindings: [ |
| 25 | { |
| 26 | type: "ai_search_namespace", |
| 27 | name: namespace.LogicalId, |
| 28 | namespace: namespace.name, |
| 29 | }, |
| 30 | ], |
| 31 | }); |
| 32 | } |
| 33 | |
| 34 | const nsEff = Effect.sync( |
| 35 | () => |
| 36 | (env as Record<string, runtime.AiSearchNamespace>)[ |
| 37 | namespace.LogicalId |
| 38 | ]!, |
| 39 | ); |
| 40 | return { |
| 41 | raw: nsEff, |
| 42 | get: (instanceName) => |
| 43 | makeClient(nsEff.pipe(Effect.map((ns) => ns.get(instanceName)))), |
| 44 | list: (params) => |
| 45 | Effect.flatMap(nsEff, (ns) => tryAiSearch(() => ns.list(params))), |
| 46 | search: (params) => |
| 47 | Effect.flatMap(nsEff, (ns) => tryAiSearch(() => ns.search(params))), |
| 48 | } satisfies QuerySearchNamespaceClient; |
| 49 | }); |
| 50 | }), |
| 51 | ); |