cards/docs/marketplace/archive/code/services/decks.ts
Till JS 7dbbf63523 Phase 12 R2: Marketplace-Backend α + β — Authors + Deck-Init + Publish
Routes (additiv unter /api/v1/marketplace/*):
- POST/GET /authors/me — eigenes Author-Profil anlegen/updaten/lesen
- GET /authors/:slug — public Profile-Lookup (banned-reason gestrippt)
- POST /decks — Deck-Init (Slug-Validation + Pflicht-Author-Profil +
  CHECK auf paid + Pro-License)
- POST /decks/:slug/publish — Versions-Snapshot mit per-Karte
  cardContentHash aus @cards/domain, per-Version-Hash, AI-Mod-Stub-Log,
  atomarer latest_version_id-Bump in Drizzle-Transaction
- PATCH /decks/:slug — Metadaten-Update (Owner-Only)
- GET /decks/:slug — Public-Detail mit optional-auth-Middleware

Geport aus cards-decommission-base:services/cards-server/, mit
Greenfield-Anpassungen:
- Hashing über @cards/domain.cardContentHash (gemeinsame SoT
  zwischen privatem cards.cards und marketplace.deck_cards), per-
  Version-Hash als SHA-256 über sortierte Karten-Hashes mit Ord-Prefix
- AI-Moderation als R2-Stub (pass+rationale+model='stub'),
  echte mana-llm-Anbindung in späterer Welle
- Auth-Middleware-Shape an Greenfield (userId/tier/authMode in
  c.get(...) statt user-Object), optional-auth als Schwester für
  anonymen Public-Read
- Hono-typing: outer Marketplace-Decks-Router ist Partial<AuthVars>
  weil Public-GET kein JWT braucht; Auth-Subroute ist strict

Lese-Referenz:
- 3331 LOC altes cards-server-Code (routes, services, middleware,
  lib) unter docs/marketplace/archive/code/ archiviert. Read-only,
  nicht im Build-Path.

Verifikation:
- 16 neue Vitest-Tests (Slug + Version-Hash), 72 gesamt grün
- type-check 0 errors
- E2E-Smoke gegen lokale cards-api: Cardecky-Author + Deck
  r2-stoische-ethik mit 3 Karten v1.0.0 (basic + basic + cloze),
  per-Karten-Hashes geschrieben, ai_moderation_log-Row da, semver-409
  + paid-422-Errors verifiziert. Smoke-Daten danach aufgeräumt.

Verbleibend für R3+: Discovery (explore + search), Engagement (stars/
subscribe/fork), Smart-Merge mit FSRS-State-Erhalt; danach R4 PRs +
Card-Discussions, R5 Frontend-Routes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:13:58 +02:00

223 lines
6.5 KiB
TypeScript

/**
* Deck service — init + publish.
*
* `init` claims a slug and creates a `cards.decks` row with no
* version yet (so authors can fiddle with metadata before their first
* publish). `publish` runs the AI-mod first-pass, computes per-card
* + per-version content hashes, writes a new immutable version + its
* cards, and atomically updates `latest_version_id` on the deck.
*
* Per MARKETPLACE_PLAN: a `block` verdict from AI mod refuses the
* publish outright. A `flag` verdict still publishes (so the deck
* isn't blocked on slow human review) but writes a row into
* `ai_moderation_log` so the moderation inbox surfaces it.
*/
import { and, eq, sql } from 'drizzle-orm';
import type { Database } from '../db/connection';
import { publicDecks, publicDeckVersions, publicDeckCards, aiModerationLog } from '../db/schema';
import { validateSlug } from '../lib/slug';
import { hashCard, hashVersionCards } from '../lib/hash';
import { moderateDeckContent } from '../lib/ai-moderation';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../lib/errors';
export interface InitDeckInput {
slug: string;
title: string;
description?: string;
language?: string;
license?: string;
priceCredits?: number;
}
export interface PublishInput {
semver: string;
changelog?: string;
cards: {
type:
| 'basic'
| 'basic-reverse'
| 'cloze'
| 'type-in'
| 'image-occlusion'
| 'audio'
| 'multiple-choice';
fields: Record<string, string>;
}[];
}
export interface PublishResult {
deck: typeof publicDecks.$inferSelect;
version: typeof publicDeckVersions.$inferSelect;
moderation: { verdict: 'pass' | 'flag' | 'block'; categories: string[] };
}
const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)$/;
function validatePrice(price: number, license: string) {
if (price < 0) throw new BadRequestError('priceCredits cannot be negative');
if (price > 0 && license !== 'Cardecky-Pro-Only-1.0') {
throw new BadRequestError('Paid decks must use the Cardecky-Pro-Only-1.0 license');
}
}
export class DeckService {
constructor(
private readonly db: Database,
private readonly llmUrl: string
) {}
async init(ownerUserId: string, input: InitDeckInput) {
const validation = validateSlug(input.slug);
if (!validation.ok) throw new BadRequestError(`Slug invalid: ${validation.reason}`);
const license = input.license ?? 'Cardecky-Personal-Use-1.0';
const priceCredits = input.priceCredits ?? 0;
validatePrice(priceCredits, license);
const existing = await this.db.query.publicDecks.findFirst({
where: eq(publicDecks.slug, input.slug),
});
if (existing) throw new ConflictError('Slug already taken');
const [created] = await this.db
.insert(publicDecks)
.values({
slug: input.slug,
title: input.title,
description: input.description,
language: input.language,
license,
priceCredits,
ownerUserId,
})
.returning();
return created;
}
async getBySlug(slug: string) {
const deck = await this.db.query.publicDecks.findFirst({
where: eq(publicDecks.slug, slug),
});
if (!deck) throw new NotFoundError('Deck not found');
const version = deck.latestVersionId
? await this.db.query.publicDeckVersions.findFirst({
where: eq(publicDeckVersions.id, deck.latestVersionId),
})
: null;
return { deck, latestVersion: version };
}
async publish(ownerUserId: string, slug: string, input: PublishInput): Promise<PublishResult> {
if (!SEMVER_RE.test(input.semver)) {
throw new BadRequestError('semver must look like 1.0.0');
}
if (input.cards.length === 0) {
throw new BadRequestError('A version needs at least one card');
}
const deck = await this.db.query.publicDecks.findFirst({
where: eq(publicDecks.slug, slug),
});
if (!deck) throw new NotFoundError('Deck not found');
if (deck.ownerUserId !== ownerUserId) {
throw new ForbiddenError('Only the deck owner can publish');
}
if (deck.isTakedown) throw new ForbiddenError('Deck is under takedown');
// semver must be strictly greater than the latest published
// version so version history stays linear.
if (deck.latestVersionId) {
const latest = await this.db.query.publicDeckVersions.findFirst({
where: eq(publicDeckVersions.id, deck.latestVersionId),
});
if (latest && !semverGreater(input.semver, latest.semver)) {
throw new ConflictError(`semver ${input.semver} must be > ${latest.semver}`);
}
}
// 1) AI moderation first-pass.
const moderation = await moderateDeckContent(
{
title: deck.title,
description: deck.description ?? undefined,
cards: input.cards.map((c) => ({ fields: c.fields })),
},
this.llmUrl
);
if (moderation.verdict === 'block') {
throw new ForbiddenError(
`Refused by content moderation: ${moderation.rationale || 'no rationale'}`
);
}
// 2) Compute hashes.
const cardsWithOrd = input.cards.map((c, i) => ({ ...c, ord: i }));
const versionContentHash = hashVersionCards(cardsWithOrd);
// 3) Insert version + cards + flip latest_version_id atomically.
const result = await this.db.transaction(async (tx) => {
const [version] = await tx
.insert(publicDeckVersions)
.values({
deckId: deck.id,
semver: input.semver,
changelog: input.changelog,
contentHash: versionContentHash,
cardCount: cardsWithOrd.length,
})
.returning();
await tx.insert(publicDeckCards).values(
cardsWithOrd.map((c) => ({
versionId: version.id,
type: c.type,
fields: c.fields,
ord: c.ord,
contentHash: hashCard(c),
}))
);
await tx.insert(aiModerationLog).values({
versionId: version.id,
verdict: moderation.verdict,
categories: moderation.categories,
model: moderation.model,
rationale: moderation.rationale,
});
const [updatedDeck] = await tx
.update(publicDecks)
.set({ latestVersionId: version.id })
.where(and(eq(publicDecks.id, deck.id)))
.returning();
return { deck: updatedDeck, version };
});
return {
deck: result.deck,
version: result.version,
moderation: { verdict: moderation.verdict, categories: moderation.categories },
};
}
}
function semverGreater(a: string, b: string): boolean {
const matchA = a.match(SEMVER_RE);
const matchB = b.match(SEMVER_RE);
if (!matchA || !matchB) return false;
for (let i = 1; i <= 3; i++) {
const da = Number.parseInt(matchA[i], 10);
const db = Number.parseInt(matchB[i], 10);
if (da > db) return true;
if (da < db) return false;
}
return false;
}
// Silence unused-binding lint for `sql` import — we keep it ready for
// upcoming routes (server-side orderings / counts).
void sql;