feat: rebuild workshop
This commit is contained in:
42 files changed
+3436
-2
No files matched your search
@@ -0,0 +1,289 @@
|
||||
import PocketBase, { ClientResponseError } from "pocketbase";
|
||||
|
||||
import type {
|
||||
WorkshopAccountState,
|
||||
WorkshopModerationAction,
|
||||
WorkshopReport,
|
||||
WorkshopRole,
|
||||
WorkshopSubmissionDetail,
|
||||
WorkshopSubmissionInput,
|
||||
WorkshopSubmissionSummary,
|
||||
WorkshopSubmissionType,
|
||||
WorkshopUser,
|
||||
WorkshopVote,
|
||||
} from "./schema";
|
||||
|
||||
import {
|
||||
WORKSHOP_API_URL,
|
||||
WorkshopError,
|
||||
schemaVersionForType,
|
||||
workshopAccountStateSchema,
|
||||
workshopErrorCodeSchema,
|
||||
workshopModerationActionSchema,
|
||||
workshopReportSchema,
|
||||
workshopRoleSchema,
|
||||
workshopSubmissionDetailSchema,
|
||||
workshopSubmissionInputSchema,
|
||||
workshopSubmissionSummarySchema,
|
||||
workshopScreenshotsSchema,
|
||||
workshopUserSchema,
|
||||
workshopVoteSchema,
|
||||
} from "./schema";
|
||||
|
||||
export interface WorkshopListOptions {
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
type?: WorkshopSubmissionType | "all";
|
||||
sort?: "top" | "newest";
|
||||
search?: string;
|
||||
author?: string;
|
||||
}
|
||||
|
||||
export interface WorkshopPage<T> {
|
||||
page: number;
|
||||
perPage: number;
|
||||
totalPages: number;
|
||||
totalItems: number;
|
||||
items: T[];
|
||||
}
|
||||
|
||||
const errorCodeForStatus = (status: number) => {
|
||||
if (status === 401) return "authentication_required" as const;
|
||||
if (status === 403) return "forbidden" as const;
|
||||
if (status === 404) return "not_found" as const;
|
||||
if (status === 409) return "conflict" as const;
|
||||
if (status === 429) return "rate_limited" as const;
|
||||
if (status >= 500) return "unavailable" as const;
|
||||
return "unknown" as const;
|
||||
};
|
||||
|
||||
const asWorkshopError = (error: unknown, fallback: string) => {
|
||||
if (error instanceof WorkshopError) return error;
|
||||
if (error instanceof ClientResponseError) {
|
||||
const message = error.data?.message || error.message || fallback;
|
||||
const messageCode =
|
||||
message === "Account is disabled"
|
||||
? "account_disabled"
|
||||
: message === "Account cannot publish submissions"
|
||||
? "posting_banned"
|
||||
: undefined;
|
||||
const parsedCode = workshopErrorCodeSchema.safeParse(messageCode ?? error.data?.data?.code ?? error.data?.code);
|
||||
const code = parsedCode.success ? parsedCode.data : errorCodeForStatus(error.status);
|
||||
return new WorkshopError(code, message, error.status);
|
||||
}
|
||||
return new WorkshopError("unknown", error instanceof Error ? error.message : fallback);
|
||||
};
|
||||
|
||||
export class WorkshopClient {
|
||||
readonly pocketBase: PocketBase;
|
||||
|
||||
constructor(readonly baseUrl = WORKSHOP_API_URL) {
|
||||
this.pocketBase = new PocketBase(baseUrl.replace(/\/$/, ""));
|
||||
}
|
||||
|
||||
get currentUser(): WorkshopUser | null {
|
||||
const record = this.pocketBase.authStore.record;
|
||||
if (!record) return null;
|
||||
return workshopUserSchema.parse({
|
||||
id: record.id,
|
||||
displayName: record.displayName || record.name || record.username || "Community member",
|
||||
avatarUrl: record.avatarUrl || record.avatar || "",
|
||||
role: workshopRoleSchema.catch("member").parse(record.role),
|
||||
state: workshopAccountStateSchema.catch("active").parse(record.state),
|
||||
});
|
||||
}
|
||||
|
||||
subscribeToAuth(listener: (user: WorkshopUser | null) => void) {
|
||||
return this.pocketBase.authStore.onChange(() => listener(this.currentUser), true);
|
||||
}
|
||||
|
||||
async refreshAuth() {
|
||||
if (!this.pocketBase.authStore.isValid) return null;
|
||||
try {
|
||||
await this.pocketBase.collection("users").authRefresh();
|
||||
return this.currentUser;
|
||||
} catch {
|
||||
this.pocketBase.authStore.clear();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async signInWithGitHub() {
|
||||
try {
|
||||
await this.pocketBase.collection("users").authWithOAuth2({ provider: "github" });
|
||||
return this.currentUser;
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "GitHub sign-in failed");
|
||||
}
|
||||
}
|
||||
|
||||
signOut() {
|
||||
this.pocketBase.authStore.clear();
|
||||
}
|
||||
|
||||
async list(options: WorkshopListOptions = {}): Promise<WorkshopPage<WorkshopSubmissionSummary>> {
|
||||
const filters: string[] = [];
|
||||
if (options.type && options.type !== "all")
|
||||
filters.push(this.pocketBase.filter("type = {:type}", { type: options.type }));
|
||||
if (options.search?.trim())
|
||||
filters.push(this.pocketBase.filter("title ~ {:search}", { search: options.search.trim() }));
|
||||
if (options.author) filters.push(this.pocketBase.filter("author = {:author}", { author: options.author }));
|
||||
try {
|
||||
const result = await this.pocketBase
|
||||
.collection("workshop_listings")
|
||||
.getList(options.page ?? 1, options.perPage ?? 24, {
|
||||
filter: filters.join(" && "),
|
||||
sort: options.sort === "newest" ? "-created" : "-score,-created",
|
||||
});
|
||||
return { ...result, items: result.items.map((item) => workshopSubmissionSummarySchema.parse(item)) };
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to load Workshop submissions");
|
||||
}
|
||||
}
|
||||
|
||||
async get(id: string): Promise<WorkshopSubmissionDetail> {
|
||||
try {
|
||||
return workshopSubmissionDetailSchema.parse(await this.pocketBase.collection("submissions").getOne(id));
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Submission not found");
|
||||
}
|
||||
}
|
||||
|
||||
fileUrl(submissionId: string, filename: string, thumb?: string) {
|
||||
const query = thumb ? `?thumb=${encodeURIComponent(thumb)}` : "";
|
||||
return `${this.baseUrl}/api/files/submissions/${submissionId}/${encodeURIComponent(filename)}${query}`;
|
||||
}
|
||||
|
||||
async create(input: WorkshopSubmissionInput, screenshots: File[] = []) {
|
||||
const parsed = workshopSubmissionInputSchema.parse(input);
|
||||
workshopScreenshotsSchema.parse(screenshots);
|
||||
const data = new FormData();
|
||||
Object.entries(parsed).forEach(([key, value]) => data.set(key, value));
|
||||
data.set("schemaVersion", schemaVersionForType(parsed.type));
|
||||
screenshots.forEach((file) => data.append("screenshots", file));
|
||||
try {
|
||||
const result = await this.pocketBase.collection("submissions").create(data);
|
||||
return this.get(result.id);
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to publish submission");
|
||||
}
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
input: WorkshopSubmissionInput,
|
||||
screenshots: File[] = [],
|
||||
removedScreenshots: string[] = [],
|
||||
) {
|
||||
const parsed = workshopSubmissionInputSchema.parse(input);
|
||||
workshopScreenshotsSchema.parse(screenshots);
|
||||
const data = new FormData();
|
||||
Object.entries(parsed).forEach(([key, value]) => data.set(key, value));
|
||||
screenshots.forEach((file) => data.append("screenshots+", file));
|
||||
removedScreenshots.forEach((filename) => data.append("screenshots-", filename));
|
||||
try {
|
||||
await this.pocketBase.collection("submissions").update(id, data);
|
||||
return this.get(id);
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to update submission");
|
||||
}
|
||||
}
|
||||
|
||||
async delete(id: string) {
|
||||
try {
|
||||
await this.pocketBase.collection("submissions").delete(id);
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to delete submission");
|
||||
}
|
||||
}
|
||||
|
||||
async vote(submissionId: string, value: 1 | -1): Promise<WorkshopVote | null> {
|
||||
const filter = this.pocketBase.filter("submission = {:submission} && user = {:user}", {
|
||||
submission: submissionId,
|
||||
user: this.currentUser?.id ?? "",
|
||||
});
|
||||
try {
|
||||
const existing = await this.pocketBase
|
||||
.collection("votes")
|
||||
.getFirstListItem(filter)
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof ClientResponseError && error.status === 404) return null;
|
||||
throw error;
|
||||
});
|
||||
if (existing?.value === value) {
|
||||
await this.pocketBase.collection("votes").delete(existing.id);
|
||||
return null;
|
||||
}
|
||||
const record = existing
|
||||
? await this.pocketBase.collection("votes").update(existing.id, { value })
|
||||
: await this.pocketBase.collection("votes").create({ submission: submissionId, value });
|
||||
return workshopVoteSchema.parse(record);
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to save vote");
|
||||
}
|
||||
}
|
||||
|
||||
async report(submission: string, category: WorkshopReport["category"], explanation: string) {
|
||||
try {
|
||||
return workshopReportSchema.parse(
|
||||
await this.pocketBase.collection("reports").create({ submission, category, explanation }),
|
||||
);
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to submit report");
|
||||
}
|
||||
}
|
||||
|
||||
async moderate(path: string, body: Record<string, unknown>) {
|
||||
try {
|
||||
return await this.pocketBase.send(`/api/workshop/moderation/${path}`, { method: "POST", body });
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Moderation action failed");
|
||||
}
|
||||
}
|
||||
|
||||
removeSubmission(id: string, reason: string) {
|
||||
return this.moderate(`submissions/${id}/remove`, { reason });
|
||||
}
|
||||
|
||||
updateAccountState(id: string, state: WorkshopAccountState, reason: string) {
|
||||
return this.moderate(`users/${id}/state`, { state, reason });
|
||||
}
|
||||
|
||||
updateRole(id: string, role: WorkshopRole, reason: string) {
|
||||
return this.moderate(`users/${id}/role`, { role, reason });
|
||||
}
|
||||
|
||||
resolveReport(id: string, status: "resolved" | "dismissed", reason: string) {
|
||||
return this.moderate(`reports/${id}/resolve`, { status, reason });
|
||||
}
|
||||
|
||||
async listReports(status: "open" | "resolved" | "dismissed" = "open") {
|
||||
try {
|
||||
const result = await this.pocketBase.collection("reports").getList(1, 100, {
|
||||
filter: this.pocketBase.filter("status = {:status}", { status }),
|
||||
sort: "-created",
|
||||
});
|
||||
return result.items.map((item) => workshopReportSchema.parse(item));
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to load reports");
|
||||
}
|
||||
}
|
||||
|
||||
async listUsers() {
|
||||
try {
|
||||
const result = await this.pocketBase.collection("users").getList(1, 200, { sort: "displayName" });
|
||||
return result.items.map((item) => workshopUserSchema.parse(item));
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to load users");
|
||||
}
|
||||
}
|
||||
|
||||
async listModerationActions(): Promise<WorkshopModerationAction[]> {
|
||||
try {
|
||||
const result = await this.pocketBase.collection("moderation_actions").getList(1, 100, { sort: "-created" });
|
||||
return result.items.map((item) => workshopModerationActionSchema.parse(item));
|
||||
} catch (error) {
|
||||
throw asWorkshopError(error, "Failed to load moderation history");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./client";
|
||||
export * from "./schema";
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CSS_SCHEMA_VERSION,
|
||||
WIDGET_SCHEMA_VERSION,
|
||||
schemaVersionForType,
|
||||
validateWorkshopContent,
|
||||
workshopExportFilename,
|
||||
workshopScreenshotsSchema,
|
||||
workshopSubmissionInputSchema,
|
||||
} from "./schema";
|
||||
|
||||
const validWidget = {
|
||||
$schema: WIDGET_SCHEMA_VERSION,
|
||||
name: "Status",
|
||||
url: "https://example.com/api/status",
|
||||
authType: "none",
|
||||
method: "GET",
|
||||
displayType: "singleValue",
|
||||
displayConfig: {
|
||||
type: "singleValue",
|
||||
jsonPath: "$.value",
|
||||
label: "Status",
|
||||
unit: "",
|
||||
valueSize: "md",
|
||||
labelPosition: "above",
|
||||
},
|
||||
};
|
||||
|
||||
describe("Workshop contracts", () => {
|
||||
it("accepts the canonical custom widget export", () => {
|
||||
expect(validateWorkshopContent("widget", JSON.stringify(validWidget)).success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects missing and mismatched widget schemas", () => {
|
||||
const { $schema: _, ...missing } = validWidget;
|
||||
expect(validateWorkshopContent("widget", JSON.stringify(missing)).success).toBe(false);
|
||||
expect(
|
||||
validateWorkshopContent("widget", JSON.stringify({ ...validWidget, displayConfig: { type: "raw" } })).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("enforces CSS and input limits", () => {
|
||||
expect(validateWorkshopContent("css", " ").success).toBe(false);
|
||||
expect(
|
||||
workshopSubmissionInputSchema.safeParse({
|
||||
type: "css",
|
||||
title: "Theme",
|
||||
description: "",
|
||||
content: "body { color: red; }",
|
||||
changelog: "",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns stable schema versions and safe filenames", () => {
|
||||
expect(schemaVersionForType("widget")).toBe(WIDGET_SCHEMA_VERSION);
|
||||
expect(schemaVersionForType("css")).toBe(CSS_SCHEMA_VERSION);
|
||||
expect(workshopExportFilename("My / Theme!", "css")).toBe("my-theme.css");
|
||||
});
|
||||
|
||||
it("validates screenshot count, MIME type, and size", () => {
|
||||
expect(workshopScreenshotsSchema.safeParse([{ size: 1024, type: "image/png" }]).success).toBe(true);
|
||||
expect(workshopScreenshotsSchema.safeParse([{ size: 1024, type: "image/svg+xml" }]).success).toBe(false);
|
||||
expect(workshopScreenshotsSchema.safeParse([{ size: 6 * 1024 * 1024, type: "image/webp" }]).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
import { customWidgetImportSchema } from "@homarr/validation/custom-widget";
|
||||
import { z } from "zod";
|
||||
|
||||
export const WORKSHOP_API_URL = "https://store.homarr.dev";
|
||||
export const WORKSHOP_WEB_URL = "https://homarr.dev/workshop";
|
||||
export const WIDGET_SCHEMA_VERSION = "homarr-custom-widget-v2";
|
||||
export const CSS_SCHEMA_VERSION = "homarr-custom-css-v1";
|
||||
export const MAX_CSS_LENGTH = 16_384;
|
||||
export const MAX_CONTENT_LENGTH = 1_000_000;
|
||||
export const MAX_SCREENSHOTS = 5;
|
||||
export const MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024;
|
||||
export const WORKSHOP_SCREENSHOT_MIME_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;
|
||||
|
||||
export const workshopSubmissionTypeSchema = z.enum(["widget", "css"]);
|
||||
export type WorkshopSubmissionType = z.infer<typeof workshopSubmissionTypeSchema>;
|
||||
|
||||
export const workshopRoleSchema = z.enum(["member", "moderator", "admin"]);
|
||||
export type WorkshopRole = z.infer<typeof workshopRoleSchema>;
|
||||
|
||||
export const workshopAccountStateSchema = z.enum(["active", "posting_banned", "disabled"]);
|
||||
export type WorkshopAccountState = z.infer<typeof workshopAccountStateSchema>;
|
||||
|
||||
export const workshopReportCategorySchema = z.enum(["malicious", "spam", "copyright", "inappropriate", "other"]);
|
||||
export const workshopReportStatusSchema = z.enum(["open", "resolved", "dismissed"]);
|
||||
|
||||
export const workshopUserSchema = z.object({
|
||||
id: z.string(),
|
||||
displayName: z.string(),
|
||||
avatarUrl: z.string().optional().default(""),
|
||||
role: workshopRoleSchema,
|
||||
state: workshopAccountStateSchema,
|
||||
});
|
||||
export type WorkshopUser = z.infer<typeof workshopUserSchema>;
|
||||
|
||||
const submissionBaseSchema = z.object({
|
||||
id: z.string(),
|
||||
type: workshopSubmissionTypeSchema,
|
||||
title: z.string(),
|
||||
description: z.string().default(""),
|
||||
schemaVersion: z.string(),
|
||||
screenshots: z.array(z.string()).default([]),
|
||||
revision: z.number().int().positive(),
|
||||
changelog: z.string().default(""),
|
||||
author: z.string(),
|
||||
authorName: z.string(),
|
||||
score: z.number().int(),
|
||||
upvotes: z.number().int(),
|
||||
downvotes: z.number().int(),
|
||||
created: z.string(),
|
||||
updated: z.string(),
|
||||
});
|
||||
|
||||
export const workshopSubmissionSummarySchema = submissionBaseSchema;
|
||||
export type WorkshopSubmissionSummary = z.infer<typeof workshopSubmissionSummarySchema>;
|
||||
|
||||
export const workshopSubmissionDetailSchema = submissionBaseSchema.extend({ content: z.string() });
|
||||
export type WorkshopSubmissionDetail = z.infer<typeof workshopSubmissionDetailSchema>;
|
||||
|
||||
export const workshopSubmissionInputSchema = z
|
||||
.object({
|
||||
type: workshopSubmissionTypeSchema,
|
||||
title: z.string().trim().min(3).max(100),
|
||||
description: z.string().trim().max(2_000).default(""),
|
||||
content: z.string().min(1).max(MAX_CONTENT_LENGTH),
|
||||
changelog: z.string().trim().max(2_000).default(""),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
const result = validateWorkshopContent(input.type, input.content);
|
||||
if (!result.success) context.addIssue({ code: "custom", message: result.error, path: ["content"] });
|
||||
});
|
||||
export type WorkshopSubmissionInput = z.infer<typeof workshopSubmissionInputSchema>;
|
||||
|
||||
export const workshopScreenshotSchema = z.object({
|
||||
size: z.number().max(MAX_SCREENSHOT_BYTES, "Each screenshot must be at most 5 MiB"),
|
||||
type: z.enum(WORKSHOP_SCREENSHOT_MIME_TYPES, { error: "Screenshots must be PNG, JPEG, or WebP" }),
|
||||
});
|
||||
export const workshopScreenshotsSchema = z.array(workshopScreenshotSchema).max(MAX_SCREENSHOTS);
|
||||
|
||||
export const workshopVoteSchema = z.object({
|
||||
id: z.string(),
|
||||
submission: z.string(),
|
||||
user: z.string(),
|
||||
value: z.union([z.literal(1), z.literal(-1)]),
|
||||
});
|
||||
export type WorkshopVote = z.infer<typeof workshopVoteSchema>;
|
||||
|
||||
export const workshopReportSchema = z.object({
|
||||
id: z.string(),
|
||||
submission: z.string(),
|
||||
reporter: z.string(),
|
||||
category: workshopReportCategorySchema,
|
||||
explanation: z.string(),
|
||||
status: workshopReportStatusSchema,
|
||||
created: z.string(),
|
||||
updated: z.string(),
|
||||
});
|
||||
export type WorkshopReport = z.infer<typeof workshopReportSchema>;
|
||||
|
||||
export const workshopModerationActionSchema = z.object({
|
||||
id: z.string(),
|
||||
actor: z.string(),
|
||||
action: z.enum(["remove_submission", "set_account_state", "set_role", "resolve_report"]),
|
||||
targetType: z.string(),
|
||||
targetId: z.string(),
|
||||
reason: z.string(),
|
||||
snapshot: z.string().default(""),
|
||||
created: z.string(),
|
||||
});
|
||||
export type WorkshopModerationAction = z.infer<typeof workshopModerationActionSchema>;
|
||||
|
||||
export const workshopErrorCodeSchema = z.enum([
|
||||
"authentication_required",
|
||||
"account_disabled",
|
||||
"posting_banned",
|
||||
"forbidden",
|
||||
"not_found",
|
||||
"invalid_submission",
|
||||
"conflict",
|
||||
"rate_limited",
|
||||
"unavailable",
|
||||
"unknown",
|
||||
]);
|
||||
export type WorkshopErrorCode = z.infer<typeof workshopErrorCodeSchema>;
|
||||
|
||||
export class WorkshopError extends Error {
|
||||
constructor(
|
||||
public readonly code: WorkshopErrorCode,
|
||||
message: string,
|
||||
public readonly status?: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "WorkshopError";
|
||||
}
|
||||
}
|
||||
|
||||
export type WorkshopValidationResult = { success: true; data: unknown } | { success: false; error: string };
|
||||
|
||||
export function validateWorkshopContent(type: WorkshopSubmissionType, content: string): WorkshopValidationResult {
|
||||
if (type === "css") {
|
||||
if (!content.trim()) return { success: false, error: "CSS cannot be empty" };
|
||||
if (content.length > MAX_CSS_LENGTH) {
|
||||
return { success: false, error: `CSS must be at most ${MAX_CSS_LENGTH} characters` };
|
||||
}
|
||||
return { success: true, data: content };
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(content);
|
||||
const result = customWidgetImportSchema.safeParse(parsed);
|
||||
if (!result.success || result.data.$schema !== WIDGET_SCHEMA_VERSION) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.success
|
||||
? "Widget schema identifier is required"
|
||||
: (result.error.issues[0]?.message ?? "Invalid widget"),
|
||||
};
|
||||
}
|
||||
return { success: true, data: result.data };
|
||||
} catch {
|
||||
return { success: false, error: "Widget content is not valid JSON" };
|
||||
}
|
||||
}
|
||||
|
||||
export const schemaVersionForType = (type: WorkshopSubmissionType) =>
|
||||
type === "widget" ? WIDGET_SCHEMA_VERSION : CSS_SCHEMA_VERSION;
|
||||
|
||||
export function workshopExportFilename(title: string, type: WorkshopSubmissionType) {
|
||||
const safeTitle =
|
||||
title
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "") || "homarr-workshop";
|
||||
return `${safeTitle}.${type === "widget" ? "json" : "css"}`;
|
||||
}
|
||||
Reference in new issue
Block a user