dynamic.ts 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. import { Effect } from "effect"
  2. import { pathToFileURL } from "url"
  3. import { define } from "../internal"
  4. import { Npm } from "../../npm"
  5. export const DynamicProviderPlugin = define({
  6. id: "dynamic-provider",
  7. effect: Effect.fn(function* (ctx) {
  8. const npm = yield* Npm.Service
  9. yield* ctx.aisdk.sdk(
  10. Effect.fn(function* (evt) {
  11. if (evt.sdk) return
  12. const installedPath = evt.package.startsWith("file://")
  13. ? evt.package
  14. : (yield* npm.add(evt.package).pipe(Effect.orDie)).entrypoint
  15. if (!installedPath) throw new Error(`Package ${evt.package} has no import entrypoint`)
  16. const mod = yield* Effect.promise(async () => {
  17. return (await import(
  18. installedPath.startsWith("file://") ? installedPath : pathToFileURL(installedPath).href
  19. )) as Record<string, (options: any) => any>
  20. }).pipe(Effect.orDie)
  21. const match = Object.keys(mod).find((name) => name.startsWith("create"))
  22. if (!match) throw new Error(`Package ${evt.package} has no provider factory export`)
  23. evt.sdk = mod[match](evt.options)
  24. }),
  25. )
  26. }),
  27. })