Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,196 @@
# OpenSpec Change: enterprise-discord-client
- **Change ID**: enterprise-discord-client
- **Package**: `@suaveplan/discord-client`
- **Category**: universal
- **Target path**: `universal/social/discord-client`
- **Status**: IN PROGRESS
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/discord-client.md`
---
## Summary
Deliver `@suaveplan/discord-client` on the genesis branch from scratch at enterprise quality. The package provides a generic Discord API client: Webhook-based message delivery (text, embeds, files), Bot REST API wrappers for channel messaging, guild info, member lookups, message reactions, thread management, Slash-command interaction responses, Component interaction acknowledgement, and a `DiscordClient` facade. Injectable fetch; no `discord.js` dependency. Genesis adds structured errors, Zod schemas, OTel instrumentation, retry with circuit breaker, rate-limit awareness (per-route bucket tracking), and `AbortSignal` cancellation.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | `DiscordError`; `DISCORD.*` error codes |
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock` |
| `@suaveplan/retry` (`workspace:^`) | Retry + circuit breaker for API calls |
| `@suaveplan/crypto` (`workspace:^`) | Ed25519 interaction signature verification |
| `zod` (`catalog:forms`) | Schema validation |
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
---
## Public API surface
### `DiscordClient`
```ts
class DiscordClient {
constructor(options: DiscordClientOptions)
// Webhooks
sendWebhook(webhookUrl: string, payload: WebhookPayload): Promise<DiscordMessage>
executeWebhook(options: ExecuteWebhookOptions): Promise<DiscordMessage>
// Messages
sendMessage(channelId: string, payload: MessagePayload): Promise<DiscordMessage>
editMessage(channelId: string, messageId: string, payload: MessagePayload): Promise<DiscordMessage>
deleteMessage(channelId: string, messageId: string): Promise<void>
addReaction(channelId: string, messageId: string, emoji: string): Promise<void>
// Channels / Threads
getChannel(channelId: string): Promise<DiscordChannel>
createThread(channelId: string, messageId: string, options: ThreadOptions): Promise<DiscordChannel>
// Guild / Members
getGuild(guildId: string): Promise<DiscordGuild>
getMember(guildId: string, userId: string): Promise<DiscordMember>
}
interface DiscordClientOptions {
token: string
applicationId?: string
publicKey?: string // Ed25519 public key for interaction verification
retryOptions?: RetryOptions
fetch?: typeof globalThis.fetch
clock?: Clock
logger?: LoggerLike
}
```
### Embed builder
```ts
function createEmbed(): EmbedBuilder
interface EmbedBuilder {
title(text: string): EmbedBuilder
description(text: string): EmbedBuilder
color(hex: number): EmbedBuilder
field(name: string, value: string, inline?: boolean): EmbedBuilder
footer(text: string, iconUrl?: string): EmbedBuilder
thumbnail(url: string): EmbedBuilder
image(url: string): EmbedBuilder
timestamp(date?: Date): EmbedBuilder
build(): DiscordEmbed
}
```
### Interaction handling
```ts
function verifyDiscordInteraction(
body: string,
signature: string,
timestamp: string,
publicKey: string
): Promise<boolean>
function parseInteraction(body: unknown): DiscordInteraction
```
### Error codes
```ts
type DiscordErrorCode =
| 'DISCORD_AUTH_FAILED'
| 'DISCORD_API_ERROR'
| 'DISCORD_RATE_LIMITED'
| 'DISCORD_SIGNATURE_INVALID'
| 'DISCORD_CHANNEL_NOT_FOUND'
| 'DISCORD_MESSAGE_NOT_FOUND'
| 'DISCORD_ABORTED'
```
---
## Genesis additions
1. **`DiscordError`** extends `SuaveplanError` with seven stable codes.
2. **Zod schemas** for `MessagePayload`, `WebhookPayload`, `DiscordEmbed`, `DiscordMessage`, `DiscordInteraction`, `DiscordChannel`, `DiscordGuild`, `DiscordMember`.
3. **Per-route rate-limit bucket tracking** — parses `X-RateLimit-*` response headers and enforces bucket-level backoff before the next request on the same route.
4. **Ed25519 interaction verification** — delegates to `@suaveplan/crypto`'s `ed25519.verify` for interaction signature verification.
5. **OTel instrumentation** — span `discord.api_call` with attribute `discord.endpoint`; counter `discord.api_total`; histogram `discord.api_duration_ms`.
6. **Property-based tests** — Embed builder produces valid JSON for arbitrary chained calls; rate-limit bucket parser correctly handles all header combinations.
---
## File layout
```text
universal/social/discord-client/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts
error-codes.ts
constants/
index.ts
types/
common.ts
common.md
core/
discord-client/
discord-client.ts
discord-client.md
discord-client.types.ts
discord-client.test.ts
index.ts
api-caller/
api-caller.ts
api-caller.md
api-caller.test.ts
index.ts
rate-limiter/
rate-limiter.ts
rate-limiter.md
rate-limiter.test.ts
index.ts
embeds/
embed-builder/
embed-builder.ts
embed-builder.md
embed-builder.test.ts
index.ts
interactions/
interaction-verifier/
interaction-verifier.ts
interaction-verifier.md
interaction-verifier.test.ts
index.ts
interaction-parser/
interaction-parser.ts
interaction-parser.md
interaction-parser.test.ts
index.ts
__benchmarks__/
discord-client.bench.ts
tests/
integration.test.ts
property.test.ts
```
---
## Impact
**Downstream consumers**: `@suaveplan/message-bridge`, `@suaveplan/notification-channel`.
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/retry`, `@suaveplan/crypto`.

View File

@@ -0,0 +1,71 @@
# Tasks: enterprise-discord-client
**Change ID**: enterprise-discord-client
**Package**: `@suaveplan/discord-client`
**Target path**: `universal/social/discord-client`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/retry`, `@suaveplan/crypto`
---
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Scaffold
- [ ] Create `universal/social/discord-client/` with `src/`, `tests/`, `src/__benchmarks__/` and all feature subdirectories per the layout in `proposal.md`.
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, correct `exports` map, `dependencies`, and `devDependencies`.
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
---
## 2. Types + errors
- [ ] `src/types/common.ts` — `DiscordClientOptions`, `MessagePayload`, `WebhookPayload`, `ExecuteWebhookOptions`, `ThreadOptions`, `DiscordMessage`, `DiscordChannel`, `DiscordGuild`, `DiscordMember`, `DiscordEmbed`, `DiscordInteraction`.
- [ ] `src/types/common.md` (≥200 words, both examples, API reference).
- [ ] `src/error-codes.ts` — `DiscordErrorCode` (7 codes), metadata, register, eager call.
- [ ] `src/types/schemas.ts` + `schemas.md` — Zod schemas.
---
## 3. Core modules
- [ ] **`src/core/rate-limiter/`** — `RateLimiter`: parses `X-RateLimit-Bucket`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` headers; tracks per-bucket state; `waitIfNeeded(bucket)` returns a `Promise` that resolves after the reset time when `remaining === 0`. Tests: no-op when remaining > 0, waits when remaining = 0, multiple buckets tracked independently.
- [ ] **`src/core/api-caller/`** — `ApiCaller`: wraps `fetch` to `https://discord.com/api/v10/`; sets `Authorization: Bot` header; invokes `RateLimiter.waitIfNeeded`; parses JSON; throws `DISCORD_API_ERROR` on non-2xx; handles 429 (uses `retry_after`). Tests: success, 401, 404, 429 rate-limit.
- [ ] **`src/core/discord-client/`** — `DiscordClient`: implements all public methods via `ApiCaller`. Tests: `sendMessage`, `editMessage`, `deleteMessage`, `addReaction`, `createThread`, `getGuild`, `getMember`, `sendWebhook`.
- [ ] **`src/embeds/embed-builder/`** — `createEmbed()`: fluent builder; `build()` returns `DiscordEmbed`. Tests: title+description, with fields, with footer, with image, timestamp auto-set.
- [ ] **`src/interactions/interaction-verifier/`** — `verifyDiscordInteraction(body, signature, timestamp, publicKey)`: Ed25519 verify via `@suaveplan/crypto`. Tests: valid, tampered body, wrong key.
- [ ] **`src/interactions/interaction-parser/`** — `parseInteraction(body)`: Zod validation. Tests: slash command, button component, select component, invalid throws.
---
## 4. OTel instrumentation
- [ ] Span `discord.api_call` with attribute `discord.endpoint`; counter `discord.api_total`; histogram `discord.api_duration_ms`.
---
## 5. Property-based tests (`tests/property.test.ts`)
- [ ] Embed builder: for arbitrary sequences of field additions, `build()` produces `fields` array with correct structure and length.
- [ ] Rate-limiter bucket: parsing arbitrary valid header combinations never throws and always produces a non-negative remaining count.
---
## 6. Benchmarks (`src/__benchmarks__/discord-client.bench.ts`)
- [ ] `createEmbed` builder chain (10 fields) 100 000 times.
---
## 7. Docs + verify
- [ ] One `.md` per implementation file (≥200 words, both examples, API reference). Root `README.md`.
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/discord-client` — green.
- [ ] `bunx turbo test:coverage --filter=@suaveplan/discord-client` — 100%.
- [ ] `bun scripts/publish.ts --package @suaveplan/discord-client`.
- [ ] Archive: `openspec/archive/2026-04-24-enterprise-discord-client/`.