1import { createAttachmentEnvironmentAtoms } from "@t3tools/client-runtime/state/attachments";
2import type { AtomCommand } from "@t3tools/client-runtime/state/runtime";
3import {
4 AuthOrchestrationOperateScope,
5 EnvironmentAuthorizationError,
6 type EnvironmentId,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import { AsyncResult } from "effect/reactivity";
10
11import { connectionAtomRuntime } from "../connection/runtime";
12import { readEnvironmentScope } from "./session";
13
14function requireAttachmentWriteAccess<W extends { readonly environmentId: EnvironmentId }, A, E>(
15 command: AtomCommand<W, A, E>,
16): AtomCommand<W, A, E | EnvironmentAuthorizationError> {
17 return {
18 ...command,
19 run: async (registry, input) => {
20 if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) {
21 return AsyncResult.failure(
22 Cause.fail(
23 new EnvironmentAuthorizationError({
24 message: "This connection cannot change attachments.",
25 requiredScope: AuthOrchestrationOperateScope,
26 }),
27 ),
28 );
29 }
30 return command.run(registry, input);
31 },
32 };
33}
34
35const commands = createAttachmentEnvironmentAtoms(connectionAtomRuntime);
36export const attachmentEnvironment = {
37 createUploadUrl: requireAttachmentWriteAccess(commands.createUploadUrl),
38 remove: requireAttachmentWriteAccess(commands.remove),
39};