From 3295bc7bef2ea00f73929b50bc2fcad271eda657 Mon Sep 17 00:00:00 2001 From: Ron Bronson Date: Mon, 29 Jun 2026 12:42:05 -0700 Subject: [PATCH] Add TypeScript dev dependency for deploy builds --- .gitignore | 3 + README.md | 25 +++ beachwave.svg | 19 +++ docs/aar.md | 91 +++++++++++ docs/deployment.md | 59 +++++++ docs/pdr.md | 178 +++++++++++++++++++++ docs/protocol.md | 29 ++++ index.html | 14 ++ lexicons/community/beachwave/room.json | 24 +++ netlify.toml | 3 + package.json | 17 ++ src/client/browser-repository.ts | 71 +++++++++ src/client/main.ts | 213 +++++++++++++++++++++++++ src/client/styles.css | 60 +++++++ src/sdk/index.ts | 52 ++++++ src/sdk/memory-client.ts | 35 ++++ src/sdk/types.ts | 40 +++++ src/sdk/validation.ts | 19 +++ test/sdk.test.js | 21 +++ tsconfig.json | 16 ++ vercel.json | 4 + 21 files changed, 993 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 beachwave.svg create mode 100644 docs/aar.md create mode 100644 docs/deployment.md create mode 100644 docs/pdr.md create mode 100644 docs/protocol.md create mode 100644 index.html create mode 100644 lexicons/community/beachwave/room.json create mode 100644 netlify.toml create mode 100644 package.json create mode 100644 src/client/browser-repository.ts create mode 100644 src/client/main.ts create mode 100644 src/client/styles.css create mode 100644 src/sdk/index.ts create mode 100644 src/sdk/memory-client.ts create mode 100644 src/sdk/types.ts create mode 100644 src/sdk/validation.ts create mode 100644 test/sdk.test.js create mode 100644 tsconfig.json create mode 100644 vercel.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a8b1485 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +dist/ +node_modules/ +.env diff --git a/README.md b/README.md new file mode 100644 index 0000000..d23f973 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Beachwave + +Beachwave is an open reference implementation for live audio on ATProto. It defines protocol primitives for decentralized live audio rooms and demonstrates them in a small browser client with a beach-inspired demo brand. + +## Components + +* `lexicons/` contains the ATProto record definitions. The initial protocol ships `community.beachwave.room`. +* `src/sdk/` contains a TypeScript SDK that hides raw repository operations behind a stable API. +* `src/client/` contains a browser reference client that consumes the SDK and uses the Beachwave palette. +* `docs/protocol.md` documents protocol objects independently from the UI. + +## Development + +```sh +npm install +npm run build +npm test +npm run dev +``` + +The current browser demo uses the Beachwave palette (`#007dc3`, `#b7d5d4`, `#37393a`, `#f7c1bb`, `#dc136c`) and the local `beachwave.svg` icon. Run `npm run dev` and open `http://localhost:4173` after building. + +## Deployment + +Beachwave can be deployed as a static site on Vercel or Netlify. The build command is `npm run build`, and the publish/output directory is the repository root (`.`) because `index.html` loads the compiled browser bundle from `dist/client/main.js`. See `docs/deployment.md` for step-by-step instructions. diff --git a/beachwave.svg b/beachwave.svg new file mode 100644 index 0000000..180fa6b --- /dev/null +++ b/beachwave.svg @@ -0,0 +1,19 @@ + + Beachwave logo + A blue wave curling around a rose sun with a berry accent. + + + + + + + + + + + + + + + + diff --git a/docs/aar.md b/docs/aar.md new file mode 100644 index 0000000..73f7349 --- /dev/null +++ b/docs/aar.md @@ -0,0 +1,91 @@ +# Beachwave After Action Report + +## Summary + +The initial Beachwave scaffold was added to the repository. It creates the first protocol artifact, a small SDK, a local demonstration client, protocol documentation, and lifecycle tests. + +This work establishes a baseline for the project, but it is not yet a production-ready live audio application. The largest remaining gaps are real ATProto authentication, a concrete ATProto repository adapter, and LiveKit media integration. + +## What was done + +### Repository structure + +Added the initial project layout: + +* `lexicons/community/beachwave/room.json` for the Room lexicon. +* `src/sdk/` for protocol-facing TypeScript helpers. +* `src/client/` for a small browser reference client. +* `docs/protocol.md` for implementation-independent protocol notes. +* `test/sdk.test.js` for lifecycle coverage. +* `package.json` and `tsconfig.json` for build and test commands. + +### Protocol and lexicon + +Defined the initial `community.beachwave.room` record with fields for title, optional description, LiveKit room name, lifecycle status, timestamps, and host DIDs. + +Documented Room semantics in `docs/protocol.md`, including purpose, lifecycle, ownership, storage location, and interoperability expectations. + +### SDK + +Implemented the initial SDK API: + +* `createRoom()` +* `endRoom()` +* `getRoom()` +* `listRooms()` +* `joinRoom()` +* `leaveRoom()` + +The SDK currently targets a generic `RepositoryClient` interface rather than binding directly to a specific ATProto library. This keeps the public API stable while allowing a real ATProto adapter to be added later. + +### Reference client + +Added a small browser client that consumes the SDK and an in-memory repository adapter. The client can create, discover, and end local demo rooms. + +The client intentionally does not perform raw repository operations. This preserves the separation between reference UI and protocol behavior. + +### Tests + +Added a Node test that exercises the room lifecycle: + +1. create a room; +2. list live rooms; +3. join a live room; +4. end the room; +5. verify ended rooms are no longer listed or joinable. + +## Validation performed + +The previous implementation was validated with: + +* `npm run build` +* `npm test` + +Both commands completed successfully at the time of the initial scaffold. + +## Known limitations + +* The reference client uses `MemoryRepositoryClient`; it is not yet connected to a real ATProto PDS. +* There is no ATProto login flow yet. +* LiveKit is represented by the `livekitRoom` field, but actual LiveKit token retrieval and audio connection are not implemented yet. +* Speaker requests, host controls beyond ending a room, participant records, invitations, recordings, transcripts, and moderation events are not implemented yet. +* The SDK update path should eventually preserve unknown fields from fetched records more deliberately and may need compare-and-swap or revision handling depending on the chosen ATProto adapter. +* Discovery currently depends on explicitly provided repositories. A production client will need a broader discovery strategy. + +## Notes for a future agent + +1. Preserve the separation between protocol, SDK, and reference UI. The client should continue to consume the SDK like any third-party app. +2. Add a real ATProto adapter behind `RepositoryClient` before expanding UI complexity. +3. Do not make the Room lexicon reference-client-specific. Any new fields should be justified by interoperability needs. +4. Before adding future lexicons, document their purpose, lifecycle, ownership, storage location, and interoperability expectations. +5. Add LiveKit through a narrow boundary that returns credentials or connection metadata from a resolved Room record. Avoid storing secrets in ATProto records. +6. Keep tests focused on protocol behavior. UI tests can be added later, but SDK lifecycle tests should remain fast and deterministic. +7. If package dependencies are introduced, update the development docs and commit the lockfile generated by the chosen package manager. + +## Recommended next steps + +1. Implement an ATProto-backed `RepositoryClient` adapter. +2. Add ATProto login to the reference client. +3. Add LiveKit token service documentation and client connection flow. +4. Expand discovery beyond explicitly listed repositories. +5. Draft Participant and Speaker lexicons once room lifecycle behavior is stable. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..239b7ef --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,59 @@ +# Deploying Beachwave + +Beachwave is currently a static proof-of-concept web app. It can be deployed to Vercel, Netlify, GitHub Pages, or any static host that can run `npm run build` and serve this repository root. + +## What the host needs to serve + +The demo entry point is `index.html`. The TypeScript build emits the browser JavaScript into `dist/client/main.js`, and the page loads styles from `src/client/styles.css` plus the local `beachwave.svg` favicon/logo. + +Because of that layout, the current static publish directory is the repository root (`.`), not only `dist/`. + +## Vercel + +1. Import the GitHub repository into Vercel. +2. Use the default framework preset or select **Other**. +3. Set the build command to: + + ```sh + npm run build + ``` + +4. Set the output directory to: + + ```text + . + ``` + +The included `vercel.json` stores those settings for the project. + +## Netlify + +1. Import the GitHub repository into Netlify. +2. Set the build command to: + + ```sh + npm run build + ``` + +3. Set the publish directory to: + + ```text + . + ``` + +The included `netlify.toml` stores those settings for the project. + +## Local preview + +Run the same build locally, then serve the repository root: + +```sh +npm run build +python3 -m http.server 4173 +``` + +Then open `http://localhost:4173`. + +## Current limitations + +This deployment is enough to view and demo the browser proof of concept. The app still uses local browser storage instead of a real ATProto PDS and simulates the LiveKit handoff rather than joining live audio. diff --git a/docs/pdr.md b/docs/pdr.md new file mode 100644 index 0000000..722895a --- /dev/null +++ b/docs/pdr.md @@ -0,0 +1,178 @@ +# Beachwave Product Design Requirements + +## 1. Overview + +Beachwave is an open reference implementation for live audio on ATProto. It defines the protocol primitives needed for decentralized live audio applications and validates them with a small working web client. + +The reference client is not the protocol. It exists to prove that the lexicons, SDK, discovery model, and room lifecycle are sufficient for another developer to build a different interoperable live audio client. + +## 2. Goals + +1. Define an interoperable protocol for creating, discovering, joining, and ending live audio rooms using ATProto records. +2. Provide a complete reference application that exercises every part of that protocol in a real implementation. +3. Keep the protocol implementation-agnostic so multiple clients can interoperate using the same room records. +4. Keep the reference implementation intentionally small, understandable, and easy to extend. + +## 3. Non-goals + +* Beachwave does not define a new identity system; ATProto remains the source of identity. +* Beachwave does not store live audio media in ATProto repositories. +* Beachwave does not require third-party clients to copy the reference UI. +* The initial implementation does not need every future lexicon; only the Room record is required for the first milestone. +* The reference SDK should hide raw repository operations, but it should not prevent advanced clients from using repository APIs directly. + +## 4. Design principles + +* ATProto is the source of identity. +* Room metadata is stored as ATProto records. +* Media transport is handled by LiveKit. +* The protocol is implementation-agnostic. +* Multiple clients should be able to interoperate using the same room records. +* All protocol components are open source. +* The reference client should remain intentionally small, understandable, and easy to extend. + +## 5. Primary users + +### Protocol implementer + +A developer building a separate live audio application that needs to create, discover, join, and end Beachwave-compatible rooms without depending on the reference UI. + +### Reference client user + +A user who signs in with ATProto, creates or discovers a room, participates in live audio through LiveKit, and leaves or ends the room according to their role. + +### Protocol maintainer + +A contributor who evolves lexicons, SDK behavior, and documentation while preserving interoperability expectations. + +## 6. Product requirements + +### 6.1 Lexicons + +The initial milestone must define `community.beachwave.room`. + +The Room record must include: + +* `title`: human-readable room title. +* `description`: optional room summary or agenda. +* `livekitRoom`: media transport room identifier. +* `status`: lifecycle state, initially `live` and eventually `ended`. +* `createdAt`: creation timestamp. +* `endedAt`: optional end timestamp. +* `hosts`: optional list of host DIDs allowed to administer the room. + +Future lexicons may include Speaker, Invitation, Participant, Recording, Transcript, and Moderation Event records. These should be added only when their ownership, lifecycle, and interoperability expectations are documented. + +### 6.2 SDK + +The TypeScript SDK must expose a small stable API: + +* `createRoom()` creates a live Room record. +* `endRoom()` marks a Room record as ended. +* `getRoom()` resolves a Room record by AT URI. +* `listRooms()` lists live Room records from one or more repositories. +* `joinRoom()` validates that a room is live and returns media connection metadata. +* `leaveRoom()` handles local session departure without mutating Room records until a Participant lexicon exists. + +Applications should not need to understand raw repository operations to perform these operations. + +### 6.3 Reference client + +The browser client must demonstrate the protocol by consuming the SDK as a third-party application would. + +The target feature set is: + +* ATProto login. +* Room creation. +* Room discovery. +* LiveKit audio. +* Speaker requests. +* Host controls. +* Room lifecycle. + +The current first milestone may use local adapters and mocked transport boundaries while the lexicon and SDK stabilize, but those seams must remain explicit. + +### 6.4 Documentation + +Documentation must describe protocol behavior independently of the reference implementation. + +Every protocol object should explain: + +* purpose; +* lifecycle; +* ownership; +* storage location; +* interoperability expectations. + +A developer should be able to build a compatible client from the documentation without copying the reference application. + +## 7. Functional flows + +### 7.1 Create room + +1. Authenticated host requests room creation. +2. Client validates user input. +3. SDK creates a `community.beachwave.room` record in the host repository. +4. Record stores metadata and LiveKit room identifier. +5. Discovering clients can list or resolve the record. + +### 7.2 Discover room + +1. Client selects repositories or feeds to inspect. +2. SDK lists `community.beachwave.room` records. +3. Client filters for `status: "live"`. +4. UI displays room metadata and host identity. + +### 7.3 Join room + +1. User selects a live Room record. +2. SDK resolves the record and rejects ended rooms. +3. Client uses the `livekitRoom` value and its LiveKit credentials to join media. +4. Participant state remains local until the Participant lexicon is introduced. + +### 7.4 End room + +1. Host requests room end. +2. SDK resolves the current Room record. +3. SDK updates the record to `status: "ended"` and sets `endedAt`. +4. Discovering clients stop presenting the room as joinable. + +## 8. Interoperability requirements + +* Clients must treat ATProto records as authoritative for room metadata and lifecycle state. +* Clients must not require reference-client-only fields to join or display rooms. +* Clients must preserve unknown compatible fields when updating records whenever possible. +* Ended rooms must not be presented as joinable. +* Media transport details must remain decoupled from ATProto storage. + +## 9. Milestones + +### Milestone 1: Protocol skeleton + +* Define Room lexicon. +* Document protocol object semantics. +* Implement SDK room lifecycle helpers. +* Add a small reference client using the SDK. +* Add automated tests for create, list, join, and end flows. + +### Milestone 2: Real ATProto integration + +* Add a concrete ATProto repository adapter. +* Add ATProto login flow to the reference client. +* Confirm record creation, update, and discovery against a real PDS. + +### Milestone 3: LiveKit media integration + +* Add LiveKit token retrieval boundary. +* Join LiveKit audio rooms from resolved Room records. +* Document deployment expectations for the media service. + +### Milestone 4: Moderated live audio + +* Add speaker request flow. +* Add host controls. +* Evaluate Participant, Speaker, Invitation, and Moderation Event lexicons. + +## 10. Success criteria + +Beachwave succeeds when another developer can build a completely different live audio application that interoperates with the same ATProto room records without depending on the reference UI. diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..111b5b5 --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,29 @@ +# Beachwave Protocol + +Beachwave uses ATProto repositories as the source of identity and room metadata. Media bytes are not stored in ATProto; live audio is transported by LiveKit or any compatible media layer that clients agree to join from the room metadata. + +## Room record + +* **Lexicon:** `community.beachwave.room` +* **Storage:** host user's ATProto repository collection `community.beachwave.room` +* **Owner:** the DID that creates the record; additional host DIDs may be listed in `hosts` +* **Purpose:** advertise a live audio room and provide the LiveKit room name needed to join media +* **Lifecycle:** created with `status: "live"`, updated to `status: "ended"` with `endedAt` when closed +* **Interoperability:** clients should treat ATProto as authoritative for title, lifecycle state, host identity, and discovery; clients should not require reference-client-specific fields + +Required fields are `title`, `livekitRoom`, `createdAt`, and `status`. Optional fields include `description`, `endedAt`, and `hosts`. + +## SDK contract + +Compatible clients can use raw repository operations or the SDK functions: + +* `createRoom()` creates a Room record in the signed-in user's repository. +* `endRoom()` marks a Room record as ended. +* `getRoom()` resolves a Room record by AT URI. +* `listRooms()` lists discoverable live Room records for configured repositories. +* `joinRoom()` returns media connection information for a room. +* `leaveRoom()` is a local media-session operation and does not mutate the Room record. + +## Reference client boundaries + +The browser client demonstrates one possible UI. It intentionally consumes the SDK instead of embedding repository operations so protocol behavior remains independent from the reference application. diff --git a/index.html b/index.html new file mode 100644 index 0000000..53fe70c --- /dev/null +++ b/index.html @@ -0,0 +1,14 @@ + + + + + + Beachwave Demo + + + + +
+ + + diff --git a/lexicons/community/beachwave/room.json b/lexicons/community/beachwave/room.json new file mode 100644 index 0000000..ed9c21c --- /dev/null +++ b/lexicons/community/beachwave/room.json @@ -0,0 +1,24 @@ +{ + "lexicon": 1, + "id": "community.beachwave.room", + "defs": { + "main": { + "type": "record", + "description": "A live audio room announced by an ATProto repository and transported by LiveKit.", + "key": "tid", + "record": { + "type": "object", + "required": ["title", "livekitRoom", "createdAt", "status"], + "properties": { + "title": { "type": "string", "maxLength": 120, "description": "Human-readable room title." }, + "description": { "type": "string", "maxLength": 1000, "description": "Optional room summary or agenda." }, + "livekitRoom": { "type": "string", "maxLength": 256, "description": "LiveKit room identifier used for media transport." }, + "status": { "type": "string", "knownValues": ["live", "ended"], "description": "Current lifecycle state." }, + "createdAt": { "type": "string", "format": "datetime" }, + "endedAt": { "type": "string", "format": "datetime" }, + "hosts": { "type": "array", "items": { "type": "string", "format": "did" }, "description": "DIDs allowed to administer the room." } + } + } + } + } +} diff --git a/netlify.toml b/netlify.toml new file mode 100644 index 0000000..c0d3b4e --- /dev/null +++ b/netlify.toml @@ -0,0 +1,3 @@ +[build] + command = "npm run build" + publish = "." diff --git a/package.json b/package.json new file mode 100644 index 0000000..6e78ae4 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "beachwave", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Reference implementation for live audio on ATProto.", + "scripts": { + "build": "tsc -p tsconfig.json", + "test": "node --test test/*.test.js", + "dev": "npm run build && python3 -m http.server 4173", + "preview": "npm run dev" + }, + "dependencies": {}, + "devDependencies": { + "typescript": "^5.5.4" + } +} diff --git a/src/client/browser-repository.ts b/src/client/browser-repository.ts new file mode 100644 index 0000000..fe4d59a --- /dev/null +++ b/src/client/browser-repository.ts @@ -0,0 +1,71 @@ +import type { RepositoryClient } from '../sdk/types.js'; + +interface StoredRecord { + cid?: string; + value: unknown; +} + +interface StoredRepository { + counter: number; + records: Record; +} + +const STORAGE_KEY = 'beachwave.demo.repository'; + +export class BrowserRepositoryClient implements RepositoryClient { + constructor(public did: string = 'did:web:ronbronson.dev') {} + + async createRecord(collection: string, record: unknown): Promise<{ uri: string; cid?: string }> { + const repository = this.read(); + const nextCounter = repository.counter + 1; + const uri = `at://${this.did}/${collection}/${nextCounter}`; + const cid = `local-${nextCounter}`; + repository.counter = nextCounter; + repository.records[uri] = { cid, value: structuredClone(record) }; + this.write(repository); + return { uri, cid }; + } + + async updateRecord(uri: string, record: unknown): Promise<{ uri: string; cid?: string }> { + const repository = this.read(); + if (!repository.records[uri]) throw new Error(`Record not found: ${uri}`); + const nextCounter = repository.counter + 1; + const cid = `local-${nextCounter}`; + repository.counter = nextCounter; + repository.records[uri] = { cid, value: structuredClone(record) }; + this.write(repository); + return { uri, cid }; + } + + async getRecord(uri: string): Promise<{ uri: string; cid?: string; value: unknown }> { + const record = this.read().records[uri]; + if (!record) throw new Error(`Record not found: ${uri}`); + return { uri, cid: record.cid, value: structuredClone(record.value) }; + } + + async listRecords(collection: string, repo = this.did): Promise> { + const prefix = `at://${repo}/${collection}/`; + return Object.entries(this.read().records) + .filter(([uri]) => uri.startsWith(prefix)) + .map(([uri, record]) => ({ uri, cid: record.cid, value: structuredClone(record.value) })); + } + + clear(): void { + localStorage.removeItem(STORAGE_KEY); + } + + private read(): StoredRepository { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return { counter: 0, records: {} }; + try { + const parsed = JSON.parse(raw) as Partial; + return { counter: parsed.counter ?? 0, records: parsed.records ?? {} }; + } catch { + return { counter: 0, records: {} }; + } + } + + private write(repository: StoredRepository): void { + localStorage.setItem(STORAGE_KEY, JSON.stringify(repository)); + } +} diff --git a/src/client/main.ts b/src/client/main.ts new file mode 100644 index 0000000..6ac8868 --- /dev/null +++ b/src/client/main.ts @@ -0,0 +1,213 @@ +import { createRoom, endRoom, joinRoom, leaveRoom, listRooms, type BeachwaveRoom } from '../sdk/index.js'; +import { BrowserRepositoryClient } from './browser-repository.js'; + +const app = document.querySelector('#root'); +if (!app) throw new Error('Missing #root element'); + +const client = new BrowserRepositoryClient('did:web:ronbronson.dev'); +let rooms: BeachwaveRoom[] = []; +let activeRoom: BeachwaveRoom | undefined; + +app.innerHTML = ` +
+
+
+
+ + Beachwave +
+

ATProto live audio proof of concept

+

Beachwave

+

+ A sunny, ATProto-native proof of concept for creating beachside live audio rooms, + discovering them locally, and walking through the host/listener lifecycle before + the real ATProto and LiveKit adapters are connected. +

+
+ + + +
+
+ +
+ +
+

Create a room

+
+ + +
+ + +
+
+
+ +
+

Discovered live rooms

+
+
+
+`; + +const roomForm = app.querySelector('#room-form')!; +const titleInput = app.querySelector('#title')!; +const descriptionInput = app.querySelector('#description')!; +const roomsElement = app.querySelector('#rooms')!; +const statusElement = app.querySelector('#status')!; +const stageElement = app.querySelector('#stage')!; + +function setStatus(message: string): void { + statusElement.textContent = message; +} + +function roomUrl(room: BeachwaveRoom): string { + const url = new URL(window.location.href); + url.searchParams.set('room', room.uri); + return url.toString(); +} + +async function refreshRooms(): Promise { + rooms = await listRooms(client); + renderRooms(); +} + +function renderRooms(): void { + if (rooms.length === 0) { + roomsElement.innerHTML = '

No live rooms yet. Create one to start the demo.

'; + return; + } + + roomsElement.replaceChildren(...rooms.map((room) => { + const article = document.createElement('article'); + article.className = 'card room'; + + const title = document.createElement('h3'); + title.textContent = room.record.title; + + const description = document.createElement('p'); + description.textContent = room.record.description ?? 'No description provided.'; + + const badge = document.createElement('span'); + badge.className = 'badge'; + badge.textContent = '● Live'; + + const meta = document.createElement('div'); + meta.className = 'meta'; + meta.innerHTML = ` + AT URI + LiveKit room + Host + `; + const codes = meta.querySelectorAll('code'); + codes[0].textContent = room.uri; + codes[1].textContent = room.record.livekitRoom; + codes[2].textContent = room.authorDid; + + const actions = document.createElement('div'); + actions.className = 'actions'; + + const joinButton = document.createElement('button'); + joinButton.type = 'button'; + joinButton.textContent = 'Join audio'; + joinButton.addEventListener('click', () => handleJoin(room)); + + const copyButton = document.createElement('button'); + copyButton.type = 'button'; + copyButton.className = 'secondary'; + copyButton.textContent = 'Copy room link'; + copyButton.addEventListener('click', () => handleCopy(room)); + + const endButton = document.createElement('button'); + endButton.type = 'button'; + endButton.className = 'danger'; + endButton.textContent = 'End room'; + endButton.addEventListener('click', () => handleEnd(room)); + + actions.append(joinButton, copyButton, endButton); + article.append(badge, title, description, meta, actions); + return article; + })); +} + +async function handleJoin(room: BeachwaveRoom): Promise { + const joined = await joinRoom(client, room.uri); + activeRoom = joined.room; + stageElement.innerHTML = ` +
+

Joined room

+

+

LiveKit handoff target:

+ +
+ `; + stageElement.querySelector('h2')!.textContent = activeRoom.record.title; + stageElement.querySelector('strong')!.textContent = joined.livekitRoom; + stageElement.querySelector('#leave')!.addEventListener('click', handleLeave); +} + +async function handleLeave(): Promise { + await leaveRoom(); + activeRoom = undefined; + stageElement.innerHTML = ` +
+

Current session

+

No room joined

+

Join a room to simulate the LiveKit handoff.

+
+ `; +} + +async function handleCopy(room: BeachwaveRoom): Promise { + await navigator.clipboard.writeText(roomUrl(room)); + setStatus('Copied room link.'); +} + +async function handleEnd(room: BeachwaveRoom): Promise { + await endRoom(client, room.uri); + if (activeRoom?.uri === room.uri) await handleLeave(); + setStatus('Room ended.'); + await refreshRooms(); +} + +roomForm.addEventListener('submit', async (event) => { + event.preventDefault(); + await createRoom(client, { + title: titleInput.value, + description: descriptionInput.value + }); + setStatus('Room record published locally.'); + await refreshRooms(); +}); + +app.querySelector('#seed-room')!.addEventListener('click', async () => { + await createRoom(client, { + title: 'Codex Demo Room', + description: 'A seeded room that demonstrates discovery, sharing, joining, and ending.' + }); + setStatus('Demo room created.'); + await refreshRooms(); +}); + +app.querySelector('#refresh')!.addEventListener('click', refreshRooms); +app.querySelector('#reset')!.addEventListener('click', async () => { + client.clear(); + await handleLeave(); + setStatus('Local demo data reset.'); + await refreshRooms(); +}); + +await refreshRooms(); diff --git a/src/client/styles.css b/src/client/styles.css new file mode 100644 index 0000000..a58858d --- /dev/null +++ b/src/client/styles.css @@ -0,0 +1,60 @@ +:root { + color-scheme: light; + --bright-teal-blue: #007dc3; + --light-blue: #b7d5d4; + --gunmetal: #37393a; + --cotton-rose: #f7c1bb; + --berry-lipstick: #dc136c; + --bg: #f8fbff; + --panel: rgba(255, 255, 255, 0.76); + --panel-strong: rgba(183, 213, 212, 0.42); + --text: var(--gunmetal); + --muted: rgba(55, 57, 58, 0.72); + --accent: var(--bright-teal-blue); + --accent-strong: #006ba7; + --danger: var(--berry-lipstick); + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; +} + +* { box-sizing: border-box; } +body { + margin: 0; + min-height: 100vh; + background: + radial-gradient(circle at 8% 8%, rgba(247, 193, 187, 0.9), transparent 20rem), + radial-gradient(circle at 78% 6%, rgba(183, 213, 212, 0.85), transparent 24rem), + linear-gradient(135deg, #fffaf8 0%, #edf8fb 50%, #fdf2f7 100%); + color: var(--text); +} +button, input, textarea { font: inherit; } +button { border: 0; border-radius: 999px; padding: 0.75rem 1rem; color: white; background: var(--accent); font-weight: 800; cursor: pointer; box-shadow: 0 10px 28px rgba(0, 125, 195, .22); } +button:hover { background: var(--accent-strong); transform: translateY(-1px); } +button.secondary { color: var(--gunmetal); background: var(--panel-strong); box-shadow: none; } +button.danger { color: white; background: var(--danger); border: 1px solid rgba(220, 19, 108, 0.2); box-shadow: 0 10px 28px rgba(220, 19, 108, .18); } +input, textarea { width: 100%; border: 1px solid rgba(0,125,195,.18); border-radius: 1rem; padding: .9rem 1rem; color: var(--text); background: rgba(255,255,255,.72); } +input:focus, textarea:focus { outline: 3px solid rgba(0, 125, 195, .18); border-color: var(--bright-teal-blue); } +label { display: grid; gap: .45rem; color: var(--muted); font-size: .9rem; font-weight: 700; } + +.shell { width: min(1120px, calc(100% - 2rem)); margin: 0 auto; padding: 2rem 0 4rem; } +.hero { display: grid; grid-template-columns: 1.2fr .8fr; gap: 1.5rem; align-items: stretch; margin-bottom: 1.5rem; } +.card { border: 1px solid rgba(55,57,58,.08); border-radius: 1.5rem; padding: 1.25rem; background: var(--panel); box-shadow: 0 24px 80px rgba(0, 125, 195, .12); backdrop-filter: blur(14px); } +.hero-card { position: relative; overflow: hidden; } +.hero-card::after { content: ""; position: absolute; inset: auto -6rem -10rem auto; width: 22rem; height: 22rem; border-radius: 999px; background: rgba(247, 193, 187, .55); z-index: -1; } +.brand-lockup { display: inline-flex; align-items: center; gap: .65rem; color: var(--gunmetal); font-weight: 900; letter-spacing: -.03em; } +.brand-lockup img { width: 3rem; height: 3rem; border-radius: 1rem; box-shadow: 0 12px 28px rgba(0, 125, 195, .18); } +.eyebrow { color: var(--berry-lipstick); text-transform: uppercase; letter-spacing: .14em; font-size: .78rem; font-weight: 900; } +h1 { color: var(--bright-teal-blue); font-size: clamp(2.5rem, 6vw, 5rem); line-height: .92; margin: .4rem 0 1rem; letter-spacing: -.07em; } +h2 { margin: 0 0 1rem; } +p { color: var(--muted); line-height: 1.6; } +.form-grid { display: grid; gap: 1rem; } +.actions { display: flex; flex-wrap: wrap; gap: .75rem; align-items: center; } +.status { color: var(--berry-lipstick); min-height: 1.5rem; font-weight: 800; } +.room-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 1rem; } +.room { display: grid; gap: .9rem; } +.room h3 { margin: 0; } +.meta { display: grid; gap: .35rem; color: var(--muted); font-size: .9rem; word-break: break-all; } +.badge { display: inline-flex; width: fit-content; align-items: center; gap: .35rem; border-radius: 999px; padding: .35rem .6rem; color: var(--bright-teal-blue); background: rgba(183,213,212,.5); font-weight: 900; font-size: .78rem; } +.stage { display: grid; gap: .75rem; min-height: 180px; place-items: center; text-align: center; border: 1px dashed rgba(0,125,195,.35); border-radius: 1.25rem; padding: 1rem; background: linear-gradient(160deg, rgba(255,255,255,.72), rgba(183,213,212,.34)); } +.stage strong { color: var(--accent); } +.empty { color: var(--muted); padding: 1rem; border: 1px dashed rgba(0,125,195,.25); border-radius: 1rem; background: rgba(255,255,255,.46); } +@media (max-width: 800px) { .hero { grid-template-columns: 1fr; } } diff --git a/src/sdk/index.ts b/src/sdk/index.ts new file mode 100644 index 0000000..0190d03 --- /dev/null +++ b/src/sdk/index.ts @@ -0,0 +1,52 @@ +import { assertRoomRecord, makeLiveKitRoomName } from './validation.js'; +import { ROOM_COLLECTION, type BeachwaveRoom, type BeachwaveRoomRecord, type CreateRoomInput, type JoinRoomResult, type RepositoryClient } from './types.js'; + +function toRoom(uri: string, cid: string | undefined, value: unknown): BeachwaveRoom { + assertRoomRecord(value); + const authorDid = uri.startsWith('at://') ? uri.slice(5).split('/')[0] : ''; + return { uri, cid, authorDid, record: value }; +} + +export async function createRoom(client: RepositoryClient, input: CreateRoomInput): Promise { + const record: BeachwaveRoomRecord = { + title: input.title.trim(), + description: input.description?.trim() || undefined, + livekitRoom: input.livekitRoom ?? makeLiveKitRoomName(client.did, input.title), + status: 'live', + createdAt: new Date().toISOString(), + hosts: Array.from(new Set([client.did, ...(input.hosts ?? [])])) + }; + assertRoomRecord(record); + const created = await client.createRecord(ROOM_COLLECTION, record); + return toRoom(created.uri, created.cid, record); +} + +export async function endRoom(client: RepositoryClient, uri: string): Promise { + const existing = await client.getRecord(uri); + const record = { ...(existing.value as object), status: 'ended', endedAt: new Date().toISOString() }; + assertRoomRecord(record); + const updated = await client.updateRecord(uri, record); + return toRoom(updated.uri, updated.cid, record); +} + +export async function getRoom(client: RepositoryClient, uri: string): Promise { + const found = await client.getRecord(uri); + return toRoom(found.uri, found.cid, found.value); +} + +export async function listRooms(client: RepositoryClient, repos: string[] = [client.did]): Promise { + const records = await Promise.all(repos.map((repo) => client.listRecords(ROOM_COLLECTION, repo))); + return records.flat().map((item) => toRoom(item.uri, item.cid, item.value)).filter((room) => room.record.status === 'live'); +} + +export async function joinRoom(client: RepositoryClient, uri: string): Promise { + const room = await getRoom(client, uri); + if (room.record.status !== 'live') throw new Error('Cannot join an ended room'); + return { room, livekitRoom: room.record.livekitRoom }; +} + +export async function leaveRoom(): Promise { + // Room membership is local to the media session until the participant lexicon is introduced. +} + +export * from './types.js'; diff --git a/src/sdk/memory-client.ts b/src/sdk/memory-client.ts new file mode 100644 index 0000000..8004c2b --- /dev/null +++ b/src/sdk/memory-client.ts @@ -0,0 +1,35 @@ +import type { RepositoryClient } from './types.js'; + +export class MemoryRepositoryClient implements RepositoryClient { + #records = new Map(); + #counter = 0; + + constructor(public did: string = 'did:example:alice') {} + + async createRecord(collection: string, record: unknown): Promise<{ uri: string; cid?: string }> { + const uri = `at://${this.did}/${collection}/${++this.#counter}`; + const cid = `bafy${this.#counter}`; + this.#records.set(uri, { cid, value: structuredClone(record) }); + return { uri, cid }; + } + + async updateRecord(uri: string, record: unknown): Promise<{ uri: string; cid?: string }> { + if (!this.#records.has(uri)) throw new Error(`Record not found: ${uri}`); + const cid = `bafy${++this.#counter}`; + this.#records.set(uri, { cid, value: structuredClone(record) }); + return { uri, cid }; + } + + async getRecord(uri: string): Promise<{ uri: string; cid?: string; value: unknown }> { + const found = this.#records.get(uri); + if (!found) throw new Error(`Record not found: ${uri}`); + return { uri, cid: found.cid, value: structuredClone(found.value) }; + } + + async listRecords(collection: string, repo = this.did): Promise> { + const prefix = `at://${repo}/${collection}/`; + return Array.from(this.#records.entries()) + .filter(([uri]) => uri.startsWith(prefix)) + .map(([uri, item]) => ({ uri, cid: item.cid, value: structuredClone(item.value) })); + } +} diff --git a/src/sdk/types.ts b/src/sdk/types.ts new file mode 100644 index 0000000..080aad0 --- /dev/null +++ b/src/sdk/types.ts @@ -0,0 +1,40 @@ +export const ROOM_COLLECTION = 'community.beachwave.room' as const; + +export type RoomStatus = 'live' | 'ended'; + +export interface BeachwaveRoomRecord { + title: string; + description?: string; + livekitRoom: string; + status: RoomStatus; + createdAt: string; + endedAt?: string; + hosts?: string[]; +} + +export interface BeachwaveRoom { + uri: string; + cid?: string; + authorDid: string; + record: BeachwaveRoomRecord; +} + +export interface CreateRoomInput { + title: string; + description?: string; + livekitRoom?: string; + hosts?: string[]; +} + +export interface JoinRoomResult { + room: BeachwaveRoom; + livekitRoom: string; +} + +export interface RepositoryClient { + did: string; + createRecord(collection: string, record: unknown): Promise<{ uri: string; cid?: string }>; + updateRecord(uri: string, record: unknown): Promise<{ uri: string; cid?: string }>; + getRecord(uri: string): Promise<{ uri: string; cid?: string; value: unknown }>; + listRecords(collection: string, repo?: string): Promise>; +} diff --git a/src/sdk/validation.ts b/src/sdk/validation.ts new file mode 100644 index 0000000..52b2338 --- /dev/null +++ b/src/sdk/validation.ts @@ -0,0 +1,19 @@ +import type { BeachwaveRoomRecord } from './types.js'; + +export function assertRoomRecord(value: unknown): asserts value is BeachwaveRoomRecord { + if (!value || typeof value !== 'object') throw new Error('Room record must be an object'); + const record = value as Record; + if (typeof record.title !== 'string' || record.title.trim().length === 0) throw new Error('Room title is required'); + if (record.title.length > 120) throw new Error('Room title must be 120 characters or fewer'); + if (record.description !== undefined && (typeof record.description !== 'string' || record.description.length > 1000)) throw new Error('Room description must be 1000 characters or fewer'); + if (typeof record.livekitRoom !== 'string' || record.livekitRoom.trim().length === 0) throw new Error('LiveKit room is required'); + if (record.status !== 'live' && record.status !== 'ended') throw new Error('Room status must be live or ended'); + if (typeof record.createdAt !== 'string' || Number.isNaN(Date.parse(record.createdAt))) throw new Error('createdAt must be an ISO datetime'); + if (record.endedAt !== undefined && (typeof record.endedAt !== 'string' || Number.isNaN(Date.parse(record.endedAt)))) throw new Error('endedAt must be an ISO datetime'); + if (record.hosts !== undefined && (!Array.isArray(record.hosts) || record.hosts.some((host) => typeof host !== 'string' || !host.startsWith('did:')))) throw new Error('hosts must be DID strings'); +} + +export function makeLiveKitRoomName(did: string, title: string, now = new Date()): string { + const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '').slice(0, 48) || 'room'; + return `${did.replace(/[^a-zA-Z0-9]/g, '_')}_${slug}_${now.getTime()}`; +} diff --git a/test/sdk.test.js b/test/sdk.test.js new file mode 100644 index 0000000..4e6c242 --- /dev/null +++ b/test/sdk.test.js @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createRoom, endRoom, joinRoom, listRooms } from '../dist/sdk/index.js'; +import { MemoryRepositoryClient } from '../dist/sdk/memory-client.js'; + +test('creates, lists, joins, and ends a room', async () => { + const client = new MemoryRepositoryClient('did:example:host'); + const room = await createRoom(client, { title: 'Morning Dive', description: 'Daily ocean audio' }); + + assert.equal(room.record.status, 'live'); + assert.equal(room.record.hosts?.[0], 'did:example:host'); + assert.match(room.record.livekitRoom, /morning-dive/); + + assert.equal((await listRooms(client)).length, 1); + assert.equal((await joinRoom(client, room.uri)).livekitRoom, room.record.livekitRoom); + + const ended = await endRoom(client, room.uri); + assert.equal(ended.record.status, 'ended'); + assert.equal((await listRooms(client)).length, 0); + await assert.rejects(() => joinRoom(client, room.uri), /ended room/); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..536999d --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": true, + "outDir": "dist", + "rootDir": "src", + "skipLibCheck": true + }, + "include": [ + "src/**/*.ts" + ], + "exclude": [] +} diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..153531f --- /dev/null +++ b/vercel.json @@ -0,0 +1,4 @@ +{ + "buildCommand": "npm run build", + "outputDirectory": "." +} -- knotmirror 0.0.1