~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/spaces-bookclub

Book club: a Svelte demo app for atproto spaces (@atproto/lex-space)

0
0
main
284 lines · 8.9 KB Raw History
import {
  Client,
  type DidString,
  type SpaceRefString,
  XrpcResponseError,
  currentDatetimeString,
} from '@atproto/lex'
import {
  MemberspacePolicyManager,
  SpaceClient,
  SpaceManager,
  listSpaces,
  memberspace,
} from '@atproto/lex-space'
import { createDidResolver } from '@atproto-labs/did-resolver'
import {
  BrowserOAuthClient,
  type OAuthSession,
  buildAtprotoLoopbackClientMetadata,
} from '@atproto/oauth-client-browser'
import { com } from '../lexicons/index.ts'

// The local network started by `pnpm network`
const PLC_DIRECTORY_URL = 'http://localhost:2582'
const HANDLE_RESOLVER_URL = 'http://localhost:2580' // see dev/network.ts

// Space types are passed as their `main` schema (unlike record types, their
// generated namespace does not expose the schema's properties)
export const club = com.example.bookclub.club.main
export const review = com.example.bookclub.review
export const info = com.example.bookclub.info

// What the app asks the user to grant. The PDS resolves the space type's
// lexicon at consent time to show it, and to expand the first scope into the
// collections it declares (com.example.bookclub.info and .review).
export const SCOPE = [
  'atproto',
  // Read every book club the user is in, under any authority, and write their
  // own reviews in it (and, as a host, the club's info)
  `space:${club.nsid}?authority=*`,
  // Create book clubs with the user as authority, and manage them (members,
  // writer set, deletion)
  `space:${club.nsid}?manage=create&manage=update&manage=delete`,
].join(' ')

export const oauthClient = new BrowserOAuthClient({
  // A loopback client: no client metadata document to host in development
  clientMetadata: buildAtprotoLoopbackClientMetadata({
    scope: SCOPE,
    redirect_uris: ['http://127.0.0.1:5173/'],
  }),
  handleResolver: HANDLE_RESOLVER_URL,
  plcDirectoryUrl: PLC_DIRECTORY_URL,
  allowHttp: true, // The local PDSes and PLC are not served over https
})

// lex-space resolves DIDs to find each repo's host and verify its MACs
const didResolver = createDidResolver({
  plcDirectoryUrl: PLC_DIRECTORY_URL,
  allowHttp: true,
})

const handles = new Map<string, Promise<string>>()

/** The handle of a DID, for display. */
export function handleOf(did: string): Promise<string> {
  let handle = handles.get(did)
  if (!handle) {
    handle = oauthClient.identityResolver
      .resolve(did)
      .then((identity) => identity.handle)
      .catch(() => did)
    handles.set(did, handle)
  }
  return handle
}

export type Review = com.example.bookclub.review.Main & {
  repo: DidString
  rkey: string
}

export type Member = { did: DidString; read: boolean; write: boolean }

export type ClubInfo = { name: string; description?: string }

// Club info, by club, remembered across loads so lists show names at once
const INFO_CACHE_KEY = 'bookclub:club-info'
const infoCache: Record<string, ClubInfo> = JSON.parse(
  localStorage.getItem(INFO_CACHE_KEY) ?? '{}',
)

function cacheInfo(uri: SpaceRefString, value: ClubInfo | null) {
  if (value) infoCache[uri] = value
  else delete infoCache[uri]
  localStorage.setItem(INFO_CACHE_KEY, JSON.stringify(infoCache))
}

/** The last known info of a club, if any. */
export function cachedClubInfo(uri: SpaceRefString): ClubInfo | undefined {
  return infoCache[uri]
}

/** Forgets every club's info: names are private to members (on sign-out). */
export function clearClubInfoCache() {
  for (const uri of Object.keys(infoCache)) delete infoCache[uri]
  localStorage.removeItem(INFO_CACHE_KEY)
}

/** The book club app, for one signed-in user. */
export class BookClubApp {
  readonly client: Client
  // One SpaceClient per space: each caches its own space credential
  readonly #spaces = new Map<SpaceRefString, SpaceClient<typeof club>>()

  constructor(readonly session: OAuthSession) {
    this.client = new Client(session)
  }

  get did(): DidString {
    return this.session.did
  }

  open(uri: SpaceRefString): SpaceClient<typeof club> {
    let space = this.#spaces.get(uri)
    if (!space) {
      space = SpaceClient.openSpace(club, uri, {
        agent: this.session,
        didResolver,
      })
      this.#spaces.set(uri, space)
    }
    return space
  }

  /**
   * The book clubs the user's PDS knows about: those they created, and those
   * they wrote to. Being added as a member is recorded by the club's authority
   * only, so a new member joins with the club's URI instead (see `join`).
   */
  async listClubs(): Promise<SpaceRefString[]> {
    const { spaces } = await this.client.call(listSpaces, {
      spaceType: club.nsid,
    })
    return spaces.map((s) => s.space)
  }

  async createClub(value: ClubInfo): Promise<SpaceRefString> {
    // The PDS generates the club's key: its name lives in the info record,
    // so it can change
    const space = await SpaceClient.createSpace(
      this.session,
      club,
      { policy: memberspace.policy.$build({}) },
      { didResolver },
    )
    this.#spaces.set(space.uri, space)
    await space.put(info, value)
    cacheInfo(space.uri, value)
    return space.uri
  }

  /** The club's info, from its host's repo, or null if the host set none. */
  async clubInfo(uri: SpaceRefString): Promise<ClubInfo | null> {
    const space = this.open(uri)
    try {
      const { value } = await space.get(info, { repo: space.ref.spaceDid })
      const result = { name: value.name, description: value.description }
      cacheInfo(uri, result)
      return result
    } catch (err) {
      if (err instanceof XrpcResponseError && err.error === 'RecordNotFound') {
        cacheInfo(uri, null)
        return null
      }
      throw err
    }
  }

  /** Renames the club, or changes its description (host only). */
  async updateClubInfo(uri: SpaceRefString, value: ClubInfo) {
    await this.open(uri).put(info, value)
    cacheInfo(uri, value)
  }

  /** Checks the club grants the user access (throws SpaceNotFound if not). */
  async join(uri: SpaceRefString): Promise<SpaceRefString> {
    await this.open(uri).authorize()
    return uri
  }

  isAuthority(uri: SpaceRefString): boolean {
    return this.open(uri).ref.spaceDid === this.did
  }

  /** Every review in the club, from every member's repo, verified. */
  async reviews(uri: SpaceRefString): Promise<Review[]> {
    const reviews: Review[] = []
    for await (const item of this.open(uri).allRecords({
      collections: [review],
    })) {
      if (item.valid && item.collection === review.$type) {
        reviews.push({ ...item.record, repo: item.repo, rkey: item.rkey })
      }
    }
    return reviews.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
  }

  async postReview(
    uri: SpaceRefString,
    book: string,
    stars: number,
    text: string,
  ) {
    await this.open(uri).create(review, {
      book,
      stars,
      text,
      createdAt: currentDatetimeString(),
    })
  }

  async deleteReview(uri: SpaceRefString, rkey: string) {
    await this.open(uri).delete(review, { rkey })
  }

  async members(uri: SpaceRefString): Promise<Member[]> {
    const manager = await SpaceManager.open(this.session, uri, {
      policies: [MemberspacePolicyManager],
    })
    const members: Member[] = []
    for await (const member of manager.members()) members.push(member)
    return members
  }

  async addMember(uri: SpaceRefString, handle: string) {
    const { did } = await oauthClient.identityResolver
      .resolve(handle)
      .catch(() => {
        throw new Error(`We couldn’t find an account for @${handle}.`)
      })
    const manager = await SpaceManager.open(this.session, uri, {
      policies: [MemberspacePolicyManager],
    })
    await manager.putMembers([{ did, read: true, write: true }])
  }

  /**
   * Revokes the member's access, and drops their repo from the writer set so
   * readers stop syncing it.
   */
  async removeMember(uri: SpaceRefString, did: DidString) {
    const manager = await SpaceManager.open(this.session, uri, {
      policies: [MemberspacePolicyManager],
    })
    await manager.removeMembers([did])
    await new SpaceManager(this.session, uri).removeWriter(did)
  }

  async deleteClub(uri: SpaceRefString) {
    await new SpaceManager(this.session, uri).deleteSpace()
    this.#spaces.delete(uri)
    cacheInfo(uri, null)
  }
}

// What users see when an action fails, without protocol details
const FRIENDLY_ERRORS: Record<string, string> = {
  SpaceNotFound:
    'This club doesn’t exist, or you aren’t a member. Ask its host to add you.',
  SpaceDeleted: 'This club was deleted by its host.',
  AppNotAuthorized: 'This club doesn’t allow this app.',
  SpaceAlreadyExists: 'You already have a club with this name.',
}

export function errorMessage(err: unknown): string {
  if (err instanceof XrpcResponseError) {
    return FRIENDLY_ERRORS[err.error] ?? 'Something went wrong. Try again.'
  }
  if (err instanceof TypeError && err.message === 'Failed to fetch') {
    return 'Couldn’t reach the server. Check your connection and try again.'
  }
  return err instanceof Error ? err.message : String(err)
}