import type { Did } from "@atcute/lexicons/syntax"; import type { OAuthUserAgent } from "@atcute/oauth-browser-client"; import { getOrCreateDelegatedSession } from "$lib/api/actAs"; import { provisionDelegate, type DelegationService } from "$lib/api/delegation"; import { ensureProfile, PROFILE_COLLECTION } from "$lib/api/profile"; import type { ProfileRecord } from "$lib/api/records"; import { isValidSubdomain, SUBDOMAIN_MAX_LENGTH, SUBDOMAIN_MIN_LENGTH } from "$lib/subdomain"; export const ORG_HANDLE_SUFFIX = ".tranquil.tngl.boltless.dev"; export const ORG_PROFILE_MARKER: ProfileRecord = { $type: PROFILE_COLLECTION, bluesky: false, isOrganization: true }; export interface OrgAccount { did: Did; handle: string; } export interface CreatedOrg extends OrgAccount { warnings: string[]; } const validateOrgHandle = (raw: string): string => { const label = raw.trim().toLowerCase(); if (label.length < SUBDOMAIN_MIN_LENGTH || label.length > SUBDOMAIN_MAX_LENGTH) { throw new Error( `Organization name must be ${SUBDOMAIN_MIN_LENGTH}-${SUBDOMAIN_MAX_LENGTH} characters.` ); } if (!isValidSubdomain(label)) { throw new Error( "Organization name can only contain lowercase letters, digits, and hyphens, and cannot start or end with a hyphen." ); } return `${label}${ORG_HANDLE_SUFFIX}`; }; export const createOrgAccount = async ( agent: OAuthUserAgent, rawHandle: string, service: DelegationService ): Promise => { const handle = validateOrgHandle(rawHandle); const account = await provisionDelegate(agent, handle, service); return { did: account.did, handle: account.handle }; }; export const createOrg = async ( controllerAgent: OAuthUserAgent, rawHandle: string, service: DelegationService, existingOrg?: OrgAccount ): Promise => { const org = existingOrg ?? (await createOrgAccount(controllerAgent, rawHandle, service)); try { const orgAgent = await getOrCreateDelegatedSession(controllerAgent, org.did); await ensureProfile(orgAgent, ORG_PROFILE_MARKER); } catch { return { ...org, warnings: ["Unable to set up the organization's profile. Try again later."] }; } return { ...org, warnings: [] }; };