import { raw } from 'hono/html'; import type { Hono } from 'hono'; import type { AppEnv, Ctx, User } from '../env'; import { importFromGithub, refreshStale, REPO_SKILL_LIMIT } from '../lib/github'; import { getImport, importItems, processNextItem, startRepoShare, type ImportItemView, type ImportRow } from '../lib/imports'; import { copySendOptions, installPlan, installSendOptions, multiAgentCopy } from '../lib/install'; import { parseSkillMd, renderMarkdown } from '../lib/markdown'; import { ipKey, rateLimit } from '../lib/ratelimit'; import type { Finding } from '../lib/scan'; import { setFlash } from '../lib/session'; import { addComment, addReview, canView, COMMENT_LIMITS, listComments, removeComment, type CommentRow, CATEGORIES, categoryCounts, categoryName, cleanCategory, fileReport, getSkillCard, getSkillCardById, getVersion, latestVersion, likeSkill, listSkills, PLATFORMS, platformName, readVersionFile, readVersionFiles, recordInstall, removeReview, setSkillState, splitPlatforms, submitSkill, unlikeSkill, type ManifestEntry, type SkillCard as SkillCardRow, type VersionRow, } from '../lib/skills'; import { SEEDS, tierFor } from '../lib/tiers'; import { clampInt, compactNumber, dateLabel, HttpError, plural, safeNext, timeAgo } from '../lib/util'; import { makeZip } from '../lib/zip'; import { icon } from '../views/art'; import { AgentBadge, Avatar, Copy, Empty, LikeButton, Pager, SendToAgent, SkillCard, Stars, stateLabel, TierBadge } from '../views/components'; import { render } from '../views/layout'; const SORTS = [ { key: 'trending', label: 'Trending' }, { key: 'top', label: 'Top' }, { key: 'new', label: 'New' }, ]; function requireUser(c: Ctx): User { const u = c.get('user'); if (!u) throw new HttpError(401, 'Sign in first.'); return u; } async function loadSkill(c: Ctx): Promise { const viewer = c.get('user'); const skill = await getSkillCard(c.env, c.req.param('handle')!, c.req.param('slug')!, viewer?.id); if (!skill || skill.state === 'removed' || !canView(skill, viewer)) throw new HttpError(404, 'That skill was not found.'); return skill; } /** The version a viewer should see: the approved one, or for the owner and admins the newest. */ async function visibleVersion(c: Ctx, skill: SkillCardRow, preferLatest = false): Promise { const viewer = c.get('user'); const privileged = !!viewer && (viewer.id === skill.owner_id || !!viewer.is_admin); if (privileged && (preferLatest || !skill.current_version_id)) return latestVersion(c.env, skill.id); return getVersion(c.env, skill.current_version_id); } const ShareForm = ({ c, replant, error, values }: { c: Ctx; replant?: SkillCardRow | null; error?: string; values?: Record }) => { const v = values ?? {}; const platformChecks = (
Works with {PLATFORMS.map((p) => ( ))}
); if (replant) { return ( ); } return ( ); }; const ITEM_STATE: Record = { queued: { label: 'Waiting to be read', cls: '' }, working: { label: 'Reading', cls: 'pill-pending' }, submitted: { label: 'In review', cls: 'pill-pending' }, updated: { label: 'New version in review', cls: 'pill-pending' }, unchanged: { label: 'No change', cls: '' }, skipped: { label: 'Left out', cls: 'pill-rejected' }, failed: { label: 'Could not be read', cls: 'pill-rejected' }, }; /** What the member sees for one skill of their shared repo: how reading went, then the reviewer's decision once there is one. */ function itemState(i: ImportItemView): { label: string; cls: string; note: string | null } { if (i.version_status === 'approved') return { label: 'Approved', cls: 'pill-verified', note: null }; if (i.version_status === 'rejected') return { label: 'Not approved', cls: 'pill-rejected', note: i.decision_note ? `Reviewer note: ${i.decision_note}` : null }; if (i.version_status === 'superseded') return { label: 'Replaced by a newer version', cls: '', note: null }; const st = ITEM_STATE[i.status] ?? { label: i.status, cls: '' }; return { ...st, note: i.detail }; } const RepoSharePage = ({ c, imp, items, ownerHandle }: { c: Ctx; imp: ImportRow; items: ImportItemView[]; ownerHandle: string }) => { const reading = imp.status === 'reading'; const left = items.filter((i) => i.status === 'queued' || i.status === 'working').length; const inReview = items.filter((i) => i.version_status === 'pending').length; const approved = items.filter((i) => i.version_status === 'approved').length; return ( ); }; /** Comments on a skill: plain text from signed-in members, on shared skills and picks alike. */ const Comments = ({ c, skill, comments, base }: { c: Ctx; skill: SkillCardRow; comments: CommentRow[]; base: string }) => { const viewer = c.get('user'); return (

{icon('comment', 20)} Comments ({comments.length})

{skill.state !== 'live' ? null : viewer ? (
Posting as @{viewer.handle}. Be kind and stay on the skill.
) : (

Sign in to leave a comment.

)} {comments.length ? (
    {comments.map((m) => (
  • {m.display_name} @{m.handle} {m.is_agent ? : null} {m.user_id === skill.owner_id && !m.is_agent ? Author : null}

    {m.body}

    {viewer ? (
    {viewer.id === m.user_id || viewer.is_admin ? (
    ) : (
    )}
    ) : null}
  • ))}
) : (

No comments yet. Be the first.

)}
); }; /** Share a skill's page: the phone's share sheet where there is one, otherwise the link is copied. */ const ShareButton = ({ c, skill, by }: { c: Ctx; skill: SkillCardRow; by: string }) => { const url = `${c.env.SITE_URL}/skills/${skill.owner_handle}/${skill.slug}`; const text = `${skill.title} by ${by}, an agent skill on Skillfarm`; return ( ); }; const FindingsList = ({ findings }: { findings: Finding[] }) => findings.length ? (
    {findings.slice(0, 30).map((f) => (
  • {f.rule} {f.file} {f.line ? `:${f.line}` : ''} {f.excerpt ? {f.excerpt} : null}
  • ))}
) : (

The pattern scan found nothing.

); export { FindingsList }; /** The page for one of Sprout's picks. There are no files here: it credits the maker and sends people to the maker's repo. */ async function pickPage(c: Ctx, skill: SkillCardRow) { const viewer = c.get('user'); const admin = !!viewer?.is_admin; const repo = skill.github_repo ? await c.env.DB.prepare('SELECT * FROM repo_signals WHERE repo_full_name = ?').bind(skill.github_repo).first<{ stars: number; forks: number; pushed_at: string | null; license_spdx: string | null; archived: number; unavailable: number; fetched_at: number }>() : null; refreshStale(c.env, c.executionCtx, [skill]); const more = skill.category ? (await listSkills(c.env, { category: skill.category, sort: 'top', limit: 4, viewerId: viewer?.id })).filter((s) => s.id !== skill.id).slice(0, 3) : []; const source = skill.source_url ?? `https://github.com/${skill.github_repo}`; const maker = skill.maker ?? skill.github_repo ?? 'its maker'; const platforms = splitPlatforms(skill.platforms); const license = skill.license ?? repo?.license_spdx ?? null; const sends = skill.state === 'live' ? installSendOptions(c.env.SITE_URL, skill, installPlan(c.env.SITE_URL, skill)) : []; const copy = skill.state === 'live' ? multiAgentCopy(skill) : null; const comments = await listComments(c.env, skill.id); const pickBase = `/skills/${skill.owner_handle}/${skill.slug}`; return render( c, { title: `${skill.title} by ${maker}`, description: skill.summary, noindex: skill.state !== 'live', active: 'skills' },
{skill.state !== 'live' ?
{stateLabel(skill.state)}. This pick is not public.
: null}

Sprout's pick

{skill.title}

{skill.summary}

{skill.owner_name} recommends this {skill.pick_note ?

{skill.pick_note}

: null}

Sprout is the Skillfarm agent. This skill belongs to {maker}. {copy ? 'Skillfarm links to the original, and keeps a converted copy for other agents, described below.' : "Skillfarm links to it and hosts no copy, so you always install the maker's current version."} Stars are for the whole repo.

{copy ? (

Multi-agent version

A copy of this skill, converted by Skillfarm so it reads the same in Claude Code, Codex CLI and Gemini CLI. {maker} wrote it and keeps the credit. The author's text is unchanged, and{' '} the notice lists every change.

{copy.agents.map((a, i) => ( ))}
{copy.agents.map((a, i) => ( ))}

Read the converted copy on GitHub

) : null}

{copy ? 'Install the original' : 'Install'}

{skill.install_hint ? ( <>

From the maker's own instructions. {skill.install_hint.trimStart().startsWith('/') ? 'Type this inside Claude Code.' : skill.install_hint.trimStart().startsWith('$') ? 'Type this inside Codex.' : 'Run this in your terminal.'} Read the skill first, the same way you would read a script before you run it.

) : (

Follow the install steps in the maker's README. Read the skill before you install it, the same way you would read a script before you run it.

)}

Open {skill.github_path ? 'the skill folder' : 'the repo'} on GitHub

{more.length ? (

More in {categoryName(skill.category)}

See all
{more.map((s) => )}
) : null}

Did you make this skill? You can share it yourself and it will be listed under your name. To have this pick changed or removed, use Report on this page.

{viewer ? (
{icon('flag', 15)} Report this pick
) : null}
, ); } export function registerSkills(app: Hono) { app.get('/skills', async (c) => { const viewer = c.get('user'); const q = (c.req.query('q') ?? '').trim().slice(0, 80); const sort = SORTS.some((s) => s.key === c.req.query('sort')) ? c.req.query('sort')! : q ? 'top' : 'trending'; const platform = PLATFORMS.some((p) => p.key === c.req.query('platform')) ? c.req.query('platform')! : ''; const category = cleanCategory(c.req.query('category')) ?? ''; const from = c.req.query('from') === 'sprout' ? 'sprout' : c.req.query('from') === 'growers' ? 'growers' : ''; const page = clampInt(c.req.query('page'), 1, 500, 1); const per = 24; const [rows, counts] = await Promise.all([ listSkills(c.env, { q, sort, platform, category, kind: from === 'sprout' ? 'link' : from === 'growers' ? 'hosted' : undefined, limit: per + 1, offset: (page - 1) * per, viewerId: viewer?.id }), categoryCounts(c.env), ]); const skills = rows.slice(0, per); refreshStale(c.env, c.executionCtx, skills); const filtered = !!(q || platform || category || from); const qs = (over: Record) => { const p = new URLSearchParams(); const all = { q, sort, platform, category, from, ...over }; for (const [k, val] of Object.entries(all)) if (val) p.set(k, val); return `/skills?${p.toString()}`; }; return render( c, { title: q ? `Skills matching "${q}"` : category ? `${categoryName(category)} skills` : from === 'sprout' ? "Sprout's picks" : 'Browse skills', description: 'Browse the curated list of agent skills on Skillfarm: skills shared by growers, each reviewed before it went live, and picks from around the web recommended by Sprout with credit to their makers.', active: 'skills', },

Browse skills

A curated list. Every skill a grower shares is reviewed by a person before it goes live, and Sprout adds picks from around the web.

Category
Works with
{from === 'sprout' ? (

Sprout is the Skillfarm agent. Its picks are skills made by other people. Each one names its maker and links to their repo, where you install it and get their updates.

) : null} {skills.length ? (
{skills.map((s) => )}
) : (

{filtered ? 'Try a broader search, or be the one who shares it.' : 'Skillfarm just opened. Yours could be the first.'}

Share a skill
)} per} base={qs({})} />
, ); }); app.get('/share', async (c) => { const user = c.get('user'); if (!user) return c.redirect(`/signin?next=${encodeURIComponent('/share' + new URL(c.req.url).search)}`); let replant: SkillCardRow | null = null; const values: Record = {}; const rid = c.req.query('replant'); if (rid) { replant = await getSkillCardById(c.env, rid); if (!replant || replant.state !== 'live' || replant.kind === 'link') throw new HttpError(404, 'That skill cannot be replanted.'); const v = await getVersion(c.env, replant.current_version_id); const md = v ? await readVersionFile(c.env, v, 'SKILL.md') : null; values.skill_md = md ? new TextDecoder().decode(md) : ''; values.platforms = replant.platforms; } return render(c, { title: replant ? 'Replant a skill' : 'Share your skills', noindex: true }, ); }); // Members share a repo, never a single file. The one exception is a replant, which starts from someone else's skill. app.post('/share', async (c) => { const user = requireUser(c); const form = await c.req.parseBody({ all: true }); const str = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : ''); const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string'); const values = { repo_url: str('repo_url') || str('github_url'), skill_md: str('skill_md'), title: str('title'), summary: str('summary'), platforms: platforms.join(',') }; let replant: SkillCardRow | null = null; try { if (!str('rights')) throw new HttpError(400, 'Confirm that you have the right to share these skills.'); if (!(await rateLimit(c.env, `submit:${user.id}`, 12, 3600))) throw new HttpError(429, 'That is a lot of submissions in one hour. Take a break and try again.'); if (str('replant')) { replant = await getSkillCardById(c.env, str('replant')); if (!replant || replant.state !== 'live' || replant.kind === 'link') throw new HttpError(404, 'That skill cannot be replanted.'); const md = values.skill_md.replace(/\r\n/g, '\n'); if (md.trim().length < 40) throw new HttpError(400, 'Paste the contents of your SKILL.md.'); const result = await submitSkill(c.env, c.executionCtx, { user, source: 'web', files: [{ path: 'SKILL.md', data: new TextEncoder().encode(md) }], title: values.title, summary: values.summary, platforms, category: replant.category, replantedFrom: replant, }); setFlash(c, 'ok', 'Submitted. It is in the review queue, and you will get an email when it is approved or denied.'); return c.redirect(`/skills/${result.ownerHandle}/${result.skill.slug}`); } if (!values.repo_url.trim()) throw new HttpError(400, 'Paste the address of your GitHub repo.'); const imp = await startRepoShare(c.env, { user, source: 'web', url: values.repo_url, platforms }); return c.redirect(`/share/repo/${imp.id}`); } catch (e) { if (!(e instanceof HttpError)) throw e; if (e.code.startsWith('open:')) { setFlash(c, 'ok', e.message); return c.redirect(`/share/repo/${e.code.slice(5)}`); } return render(c, { title: replant ? 'Replant a skill' : 'Share your skills', noindex: true }, , e.status); } }); const loadImport = async (c: Ctx): Promise<{ imp: ImportRow; ownerHandle: string }> => { const user = requireUser(c); const imp = await getImport(c.env, c.req.param('id')!); if (!imp || (imp.user_id !== user.id && !user.is_admin)) throw new HttpError(404, 'That shared repo was not found.'); const owner = imp.user_id === user.id ? user : await c.env.DB.prepare('SELECT handle FROM users WHERE id = ?').bind(imp.user_id).first<{ handle: string }>(); return { imp, ownerHandle: owner?.handle ?? '' }; }; app.get('/share/repo/:id', async (c) => { const { imp, ownerHandle } = await loadImport(c); const items = await importItems(c.env, imp.id); return render(c, { title: `Sharing ${imp.repo}`, noindex: true }, ); }); // Read the next skill of a shared repo. The page calls this until nothing is left; one skill per call keeps every request small. app.post('/share/repo/:id/next', async (c) => { const { imp } = await loadImport(c); const step = imp.status === 'reading' ? await processNextItem(c.env, c.executionCtx, imp.id) : { left: 0, processed: false }; if ((c.req.header('accept') ?? '').includes('application/json')) return c.json({ left: step.left, found: imp.found }); return c.redirect(`/share/repo/${imp.id}`); }); app.get('/skills/:handle/:slug', async (c) => { const viewer = c.get('user'); const skill = await loadSkill(c); const own = viewer?.id === skill.owner_id; const admin = !!viewer?.is_admin; if (skill.kind === 'link') return pickPage(c, skill); const version = await visibleVersion(c, skill); const latest = own || admin ? await latestVersion(c.env, skill.id) : null; const tab = ['files', 'reviews'].includes(c.req.query('tab') ?? '') ? c.req.query('tab')! : 'readme'; const manifest: ManifestEntry[] = version ? JSON.parse(version.manifest) : []; const [mdBytes, reviews, parent, repo, replants] = await Promise.all([ version ? readVersionFile(c.env, version, 'SKILL.md') : Promise.resolve(null), c.env.DB.prepare( `SELECT r.id, r.rating, r.body, r.created_at, r.user_id, u.handle, u.display_name, u.avatar_key, u.avatar_fallback, u.seeds_total FROM reviews r JOIN users u ON u.id = r.user_id WHERE r.skill_id = ? AND r.removed_at IS NULL ORDER BY r.created_at DESC LIMIT 50`, ).bind(skill.id).all<{ id: string; rating: number; body: string; created_at: number; user_id: string; handle: string; display_name: string; avatar_key: string | null; avatar_fallback: string | null; seeds_total: number }>(), skill.replanted_from_skill_id ? getSkillCardById(c.env, skill.replanted_from_skill_id) : Promise.resolve(null), skill.github_repo ? c.env.DB.prepare('SELECT * FROM repo_signals WHERE repo_full_name = ?').bind(skill.github_repo).first<{ stars: number; forks: number; pushed_at: string | null; license_spdx: string | null; archived: number; unavailable: number; fetched_at: number }>() : Promise.resolve(null), c.env.DB.prepare("SELECT COUNT(*) AS n FROM skills WHERE replanted_from_skill_id = ? AND state = 'live'").bind(skill.id).first<{ n: number }>(), ]); const comments = await listComments(c.env, skill.id); refreshStale(c.env, c.executionCtx, [skill]); const md = mdBytes ? new TextDecoder().decode(mdBytes) : ''; const body = md ? parseSkillMd(md).body : ''; const base = `/skills/${skill.owner_handle}/${skill.slug}`; const site = c.env.SITE_URL; const platforms = splitPlatforms(skill.platforms); const plan = installPlan(site, skill, { fileCount: manifest.length }); const sends = skill.state === 'live' ? installSendOptions(site, skill, plan) : []; const myReview = viewer ? reviews.results.find((r) => r.user_id === viewer.id) : null; const rating = skill.reviews_count ? (skill.rating_sum / skill.reviews_count).toFixed(1) : null; const pending = latest && latest.status === 'pending' ? latest : null; const rejected = latest && latest.status === 'rejected' && latest.id !== skill.current_version_id ? latest : null; return render( c, { title: `${skill.title} by ${skill.owner_handle}`, description: skill.summary, noindex: skill.state !== 'live', active: 'skills' },
{skill.state !== 'live' ? (
{stateLabel(skill.state)}.{' '} {skill.state === 'pending' ? 'Only you and the moderators can see this page until it is approved.' : skill.state === 'rejected' ? 'This skill is not public. Fix the issue below and submit a new version.' : 'This skill is not public.'}
) : null} {skill.state === 'live' && pending ?
Update in review. Version {pending.version} is waiting for a moderator. The approved version stays live until then.
: null} {rejected ? (
Version {rejected.version} was not approved. {rejected.decision_note ? `Reviewer note: ${rejected.decision_note}` : 'No reviewer note was left.'}
) : null} {(own || admin) && latest && latest.status !== 'approved' && JSON.parse(latest.scan_report).length ? (
What the pattern scan flagged in version {latest.version}

These are automatic matches for a reviewer to check. Some are false alarms.

) : null}

{skill.title}

{skill.summary}

{skill.owner_name} @{skill.owner_handle} {skill.verified_owner ? {icon('check', 14)} Verified owner : null}
{parent ? (

{icon('replant', 17)} Replanted from{' '} {parent.state === 'live' ? {parent.title} : {parent.title}} by @{parent.owner_handle}

) : null}
{skill.state === 'live' ? (

Install

{plan.source === 'github' ? <>This skill installs straight from its public repo, {plan.repo}. Read the files first. : 'Read the files first. This copies the reviewed files into your agent\'s skills folder.'}

{plan.agents.map((a, i) => ( ))}
{plan.agents.map((a, i) => ( ))}

New to this? Help has setup prompts and answers.

) : null} {tab === 'readme' ? (
{body ? raw(renderMarkdown(body)) :

This skill has no readable SKILL.md.

}
) : null} {tab === 'files' ? (
    {manifest.map((m) => (
  • {icon('file', 18)} {m.path} {m.size < 1024 ? `${m.size} B` : `${(m.size / 1024).toFixed(1)} KB`}
  • ))}
) : null} {tab === 'reviews' ? (
{viewer && !own && !myReview && skill.state === 'live' ? (

Write a review

Tried it? Say how it went. A review earns you {SEEDS.review} Seeds.

Rating {[1, 2, 3, 4, 5].map((n) => ( ))}
) : null} {!viewer ?

Sign in to review this skill.

: null} {reviews.results.length ? (
    {reviews.results.map((r) => (
  • {r.display_name} @{r.handle} {'●'.repeat(r.rating)}{'○'.repeat(5 - r.rating)}

    {r.body}

    {viewer && (viewer.id === r.user_id || admin) ? (
    ) : null}
  • ))}
) : (

Be the first to say how this skill worked for you.

)}
) : null}
{viewer && !own ? (
{icon('flag', 15)} Report this skill
) : null} {own ? (
Remove this skill

This takes the skill down and reverses the Seeds it earned. It cannot be undone.

) : null}
, ); }); app.get('/skills/:handle/:slug/file/*', async (c) => { const skill = await loadSkill(c); const version = await visibleVersion(c, skill, c.req.query('v') === 'latest'); const base = `/skills/${skill.owner_handle}/${skill.slug}`; const path = decodeURIComponent(new URL(c.req.url).pathname.slice(new URL(c.req.url).pathname.indexOf('/file/') + 6)); const data = version ? await readVersionFile(c.env, version, path) : null; if (!data) throw new HttpError(404, 'That file was not found.'); const text = new TextDecoder().decode(data); return render( c, { title: `${path} in ${skill.title}`, noindex: true, active: 'skills' },

{skill.title} / Files / {path}

{path}

{text}
, ); }); app.get('/skills/:handle/:slug/download', async (c) => { const viewer = c.get('user'); const skill = await loadSkill(c); const version = await getVersion(c.env, skill.current_version_id); if (!version || skill.state !== 'live') throw new HttpError(404, 'This skill is not available to download.'); const ip = c.req.header('cf-connecting-ip') ?? 'local'; if (!(await rateLimit(c.env, `dl:${await ipKey(c.env, ip)}`, 120, 3600))) throw new HttpError(429, 'Too many downloads from this network. Try again later.'); const files = await readVersionFiles(c.env, version); c.executionCtx.waitUntil(recordInstall(c.env, skill, viewer, ip, c.req.header('user-agent') ?? '').catch((e) => console.error('install count failed', e))); const headers: Record = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }; if (files.length === 1) { return new Response(files[0].data, { headers: { ...headers, 'content-type': 'text/markdown; charset=utf-8', 'content-disposition': 'attachment; filename="SKILL.md"' } }); } return new Response(makeZip(files), { headers: { ...headers, 'content-type': 'application/zip', 'content-disposition': `attachment; filename="${skill.slug}.zip"` } }); }); app.get('/skills/:handle/:slug/edit', async (c) => { const user = c.get('user'); const skill = await loadSkill(c); if (!user || user.id !== skill.owner_id || skill.kind === 'link') throw new HttpError(403, 'Only the owner can update this skill.'); const v = await latestVersion(c.env, skill.id); const md = v ? await readVersionFile(c.env, v, 'SKILL.md') : null; const base = `/skills/${skill.owner_handle}/${skill.slug}`; return render( c, { title: `Update ${skill.title}`, noindex: true }, , ); }); app.post('/skills/:handle/:slug/edit', async (c) => { const user = requireUser(c); const skill = await loadSkill(c); if (user.id !== skill.owner_id) throw new HttpError(403, 'Only the owner can update this skill.'); const base = `/skills/${skill.owner_handle}/${skill.slug}`; const form = await c.req.parseBody({ all: true }); const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string'); try { if (skill.github_repo) { const [owner, repo] = skill.github_repo.split('/'); const imp = await importFromGithub(c.env, { owner, repo, path: skill.github_path ?? '' }); await submitSkill(c.env, c.executionCtx, { user, source: 'web', files: imp.files, platforms, existing: skill, github: { repo: imp.repo, path: imp.path, ref: imp.ref, ownerId: imp.info.owner_id } }); } else { const md = String(form.skill_md ?? '').replace(/\r\n/g, '\n'); await submitSkill(c.env, c.executionCtx, { user, source: 'web', files: [{ path: 'SKILL.md', data: new TextEncoder().encode(md) }], platforms, existing: skill }); } setFlash(c, 'ok', 'New version submitted for review.'); } catch (e) { if (!(e instanceof HttpError)) throw e; setFlash(c, 'error', e.message); return c.redirect(`${base}/edit`); } return c.redirect(base); }); app.post('/skills/:handle/:slug/remove', async (c) => { const user = requireUser(c); const skill = await loadSkill(c); await setSkillState(c.env, user, skill, 'removed'); setFlash(c, 'ok', `"${skill.title}" was removed.`); return c.redirect(`/u/${user.handle}`); }); app.post('/skills/:handle/:slug/reviews', async (c) => { const user = requireUser(c); const skill = await loadSkill(c); const form = await c.req.parseBody(); const base = `/skills/${skill.owner_handle}/${skill.slug}?tab=reviews`; try { await addReview(c.env, user, skill, parseInt(String(form.rating ?? ''), 10), String(form.body ?? '')); setFlash(c, 'ok', `Review posted. You earned ${SEEDS.review} Seeds.`); } catch (e) { if (!(e instanceof HttpError)) throw e; setFlash(c, 'error', e.message); } return c.redirect(base); }); app.post('/skills/:handle/:slug/comments', async (c) => { const user = requireUser(c); const skill = await loadSkill(c); const form = await c.req.parseBody(); const base = `/skills/${skill.owner_handle}/${skill.slug}`; try { const id = await addComment(c.env, user, skill, String(form.body ?? '')); setFlash(c, 'ok', 'Comment posted.'); return c.redirect(`${base}#comment-${id}`); } catch (e) { if (!(e instanceof HttpError)) throw e; setFlash(c, 'error', e.message); return c.redirect(`${base}#comments`); } }); app.post('/comments/:id/remove', async (c) => { const user = requireUser(c); const form = await c.req.parseBody(); await removeComment(c.env, user, c.req.param('id')); setFlash(c, 'ok', 'Comment removed.'); return c.redirect(safeNext(String(form.back ?? '/'))); }); app.post('/reviews/:id/remove', async (c) => { const user = requireUser(c); const form = await c.req.parseBody(); await removeReview(c.env, user, c.req.param('id')); setFlash(c, 'ok', 'Review removed.'); return c.redirect(safeNext(String(form.back ?? '/'))); }); app.post('/report', async (c) => { const user = requireUser(c); const form = await c.req.parseBody(); try { await fileReport(c.env, user, String(form.target_type ?? ''), String(form.target_id ?? ''), String(form.reason ?? '')); setFlash(c, 'ok', 'Thanks. A moderator will look at your report.'); } catch (e) { if (!(e instanceof HttpError)) throw e; setFlash(c, 'error', e.message); } return c.redirect(safeNext(String(form.back ?? '/'))); }); // Like and unlike. Session cookie plus the same-origin check in the app middleware. const likeHandler = (on: boolean) => async (c: Ctx) => { const user = c.get('user'); if (!user) return c.json({ error: 'sign_in', message: 'Sign in to like skills.' }, 401); const skill = await getSkillCardById(c.env, c.req.param('id')!); if (!skill || skill.state !== 'live') return c.json({ error: 'not_found', message: 'That skill was not found.' }, 404); try { const res = on ? await likeSkill(c.env, user, skill) : await unlikeSkill(c.env, user, skill); return c.json(res); } catch (e) { if (e instanceof HttpError) return c.json({ error: 'refused', message: e.message }, e.status as 400); throw e; } }; app.post('/api/skills/:id/like', likeHandler(true)); app.delete('/api/skills/:id/like', likeHandler(false)); }