account.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { Effect, Scope, Stream } from "effect"
  2. import { AccountV2 } from "../account"
  3. import { EventV2 } from "../event"
  4. import { PluginV2 } from "../plugin"
  5. export const AccountPlugin = PluginV2.define({
  6. id: PluginV2.ID.make("account"),
  7. effect: Effect.gen(function* () {
  8. const accounts = yield* AccountV2.Service
  9. const events = yield* EventV2.Service
  10. const scope = yield* Scope.Scope
  11. yield* events.subscribe(AccountV2.Event.Switched).pipe(
  12. Stream.runForEach((event) =>
  13. PluginV2.Service.use((plugin) => plugin.trigger("account.switched", event.data, {})).pipe(Effect.asVoid),
  14. ),
  15. Effect.forkIn(scope, { startImmediately: true }),
  16. )
  17. return {
  18. "catalog.transform": Effect.fn(function* (evt) {
  19. for (const item of evt.data) {
  20. const account = yield* accounts.active(AccountV2.ServiceID.make(item.provider.id)).pipe(Effect.orDie)
  21. if (!account) continue
  22. evt.provider.update(item.provider.id, (provider) => {
  23. provider.enabled = {
  24. via: "account",
  25. service: account.serviceID,
  26. }
  27. if (account.credential.type === "api") {
  28. provider.options.aisdk.provider.apiKey = account.credential.key
  29. Object.assign(provider.options.aisdk.provider, account.credential.metadata ?? {})
  30. }
  31. if (account.credential.type === "oauth") provider.options.aisdk.provider.apiKey = account.credential.access
  32. })
  33. }
  34. }),
  35. "account.switched": Effect.fn(function* () {}),
  36. }
  37. }),
  38. })