B3: catalog taxonomy CRUD (categories, vendors, technologies, functions)

Create/rename/deactivate for the four taxonomy tables. Deactivate not
delete; slug frozen after creation; FKs ON DELETE RESTRICT.
- src/db/schema.ts: four tables + relations (ON DELETE RESTRICT FKs)
- src/lib/slug.ts: slugify (lowercase, ASCII-fold, collapse runs) + 6 tests
- src/db/catalog.ts: listCatalog (active filter), deactivateCatalog (soft
  delete), per-entity create*/update* (slug generated at create, frozen on
  update; update patches only present fields)
- src/app/api/dev/catalog/route.ts: GET/POST/PATCH; Zod per entity; DB
  constraint errors mapped to 409 (dup slug) / 400 (dangling FK) via cause
  chain
- drizzle/0003_whole_crystal.sql
Verification: typecheck, lint, 36 unit tests (+6), build, db:migrate all
exit 0. Runtime smoke: create -> rename keeps slug -> deactivate hides from
pickers but row persists (all four types); partial PATCH preserves omitted
fields; validation 400/400/400/409.
This commit is contained in:
Tiel Coder
2026-11-18 01:00:10 +00:00
parent 26b31978e2
commit 9f7a65b136
9 changed files with 2425 additions and 3 deletions
+281
View File
@@ -0,0 +1,281 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import {
listCatalog,
deactivateCatalog,
createCategory,
updateCategory,
createVendor,
updateVendor,
createTechnology,
updateTechnology,
createFunction,
updateFunction,
} from "@/db/catalog";
const JSON_HEADERS = { "content-type": "application/json" };
const typeSchema = z.enum(["categories", "vendors", "technologies", "functions"]);
const idSchema = z.string().min(1);
/* ---- create schemas (slug is generated server-side, never sent in) ---- */
const categoryCreateSchema = z.object({
name: z.string().min(1),
description: z.string().nullable().optional(),
colorHex: z.string().nullable().optional(),
icon: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
const vendorCreateSchema = z.object({
name: z.string().min(1),
supportUrl: z.string().nullable().optional(),
supportPhone: z.string().nullable().optional(),
notes: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
const technologyCreateSchema = z.object({
name: z.string().min(1),
vendorId: z.string().min(1),
categoryId: z.string().min(1),
modelNumber: z.string().nullable().optional(),
versionLabel: z.string().nullable().optional(),
docsUrl: z.string().nullable().optional(),
purchasedOn: z.string().nullable().optional(),
serialNumber: z.string().nullable().optional(),
successorTechnologyId: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
const functionCreateSchema = z.object({
name: z.string().min(1),
categoryId: z.string().min(1),
description: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
/* ---- update schemas (name editable; slug frozen) ---- */
const categoryUpdateSchema = z.object({
name: z.string().min(1).optional(),
description: z.string().nullable().optional(),
colorHex: z.string().nullable().optional(),
icon: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
const vendorUpdateSchema = z.object({
name: z.string().min(1).optional(),
supportUrl: z.string().nullable().optional(),
supportPhone: z.string().nullable().optional(),
notes: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
const technologyUpdateSchema = z.object({
name: z.string().min(1).optional(),
modelNumber: z.string().nullable().optional(),
versionLabel: z.string().nullable().optional(),
docsUrl: z.string().nullable().optional(),
purchasedOn: z.string().nullable().optional(),
serialNumber: z.string().nullable().optional(),
successorTechnologyId: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
const functionUpdateSchema = z.object({
name: z.string().min(1).optional(),
description: z.string().nullable().optional(),
sortOrder: z.number().int().optional(),
});
async function readBody(req: NextRequest) {
try {
return await req.json();
} catch {
return null;
}
}
const bad = (message: string) =>
new Response(JSON.stringify({ error: message }), {
status: 400,
headers: JSON_HEADERS,
});
const ok = (row: unknown) =>
new Response(JSON.stringify({ row }), {
status: 200,
headers: JSON_HEADERS,
});
const created = (row: unknown) =>
new Response(JSON.stringify({ row }), {
status: 201,
headers: JSON_HEADERS,
});
/**
* Map Postgres constraint violations to client errors so admins get a clear
* message instead of an empty 500: 23505 = duplicate slug, 23503 = dangling
* FK (vendor/category id that does not exist).
*/
const dbError = (err: unknown) => {
// The pg driver wraps the Postgres error in a cause chain; walk it to find
// the SQLSTATE (23505 = duplicate, 23503 = dangling FK).
let code: string | undefined;
let node: { code?: string; cause?: unknown } | null = err as {
code?: string;
cause?: unknown;
} | null;
while (node) {
if (node.code) {
code = node.code;
break;
}
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
}
if (code === "23505") {
return new Response(JSON.stringify({ error: "a row with this slug already exists" }), {
status: 409,
headers: JSON_HEADERS,
});
}
if (code === "23503") {
return new Response(JSON.stringify({ error: "referenced row does not exist" }), {
status: 400,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ error: "internal error" }), {
status: 500,
headers: JSON_HEADERS,
});
};
/** GET /api/dev/catalog?type=categories&active=true — list pickers rows. */
export const GET = async (req: NextRequest) => {
const type = typeSchema.safeParse(req.nextUrl.searchParams.get("type"));
if (!type.success) {
return new Response(JSON.stringify({ error: "invalid type" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const active = req.nextUrl.searchParams.get("active") !== "false";
const rows = await listCatalog(type.data, { active });
return new Response(JSON.stringify({ type: type.data, rows }), {
status: 200,
headers: JSON_HEADERS,
});
};
/** POST /api/dev/catalog { type, ...createFields } — create (slug generated). */
export const POST = async (req: NextRequest) => {
const body = await readBody(req);
if (!body || typeof body !== "object") {
return new Response(JSON.stringify({ error: "invalid body" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const type = typeSchema.safeParse((body as { type?: unknown }).type);
if (!type.success) {
return new Response(JSON.stringify({ error: "invalid type" }), {
status: 400,
headers: JSON_HEADERS,
});
}
try {
switch (type.data) {
case "categories": {
const parsed = categoryCreateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return created(await createCategory(parsed.data));
}
case "vendors": {
const parsed = vendorCreateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return created(await createVendor(parsed.data));
}
case "technologies": {
const parsed = technologyCreateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return created(await createTechnology(parsed.data));
}
case "functions": {
const parsed = functionCreateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return created(await createFunction(parsed.data));
}
}
} catch (err) {
return dbError(err);
}
};
/**
* PATCH /api/dev/catalog { type, id, ...updateFields } — rename / edit.
* PATCH { type, id, active: false } — deactivate (soft delete).
* `slug` is never accepted here: it freezes after creation.
*/
export const PATCH = async (req: NextRequest) => {
const body = await readBody(req);
if (!body || typeof body !== "object") {
return new Response(JSON.stringify({ error: "invalid body" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const type = typeSchema.safeParse((body as { type?: unknown }).type);
if (!type.success) {
return new Response(JSON.stringify({ error: "invalid type" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const id = idSchema.safeParse((body as { id?: unknown }).id);
if (!id.success) {
return new Response(JSON.stringify({ error: "invalid id" }), {
status: 400,
headers: JSON_HEADERS,
});
}
// Deactivate path: explicit active=false, no editable fields applied.
try {
if ((body as { active?: unknown }).active === false) {
const row = await deactivateCatalog(type.data, id.data);
return new Response(JSON.stringify({ row }), {
status: 200,
headers: JSON_HEADERS,
});
}
switch (type.data) {
case "categories": {
const parsed = categoryUpdateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return ok(await updateCategory(id.data, parsed.data));
}
case "vendors": {
const parsed = vendorUpdateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return ok(await updateVendor(id.data, parsed.data));
}
case "technologies": {
const parsed = technologyUpdateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return ok(await updateTechnology(id.data, parsed.data));
}
case "functions": {
const parsed = functionUpdateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
return ok(await updateFunction(id.data, parsed.data));
}
}
} catch (err) {
return dbError(err);
}
};
+284
View File
@@ -0,0 +1,284 @@
/**
* Catalog data access — the four leaf tables of the skill taxonomy
* (ARCHITECTURE §4.3): skill_categories, vendors, technologies, functions.
*
* Integrity rules (enforced here, not just the UI):
* - Deactivate, never delete — `active` flips to false; the row persists so
* history (skills, technologies, assignments) is preserved.
* - Slug freezes after creation — `update*` rewrites only editable fields and
* never touches `slug`; the display name stays editable.
* - Slugs are generated from the name at create time (src/lib/slug.ts).
*
* Read path: `listCatalog(type, { active: true })` returns only active rows —
* that is what pickers render. `active: false` returns the full set (audit).
*/
import { asc, eq } from "drizzle-orm";
import { db } from "@/db";
import {
skillCategories,
vendors,
technologies,
functions,
} from "@/db/schema";
import { slugify } from "@/lib/slug";
export type CatalogType = "categories" | "vendors" | "technologies" | "functions";
/** The four tables, keyed by the public type name. */
const TABLES = {
categories: skillCategories,
vendors: vendors,
technologies: technologies,
functions: functions,
} as const;
/* ---------------------------------------------------------- generic ops */
/**
* List catalog rows. `active: true` (default) returns only rows visible in
* pickers; `active: false` returns every row including deactivated ones.
*/
export async function listCatalog(
type: CatalogType,
{ active = true }: { active?: boolean } = {},
) {
const table = TABLES[type];
const rows = await db
.select()
.from(table)
.where(active ? eq(table.active, true) : undefined)
.orderBy(asc(table.sortOrder), table.name);
return rows;
}
/** Soft-delete: flip `active` to false. The row persists for history. */
export async function deactivateCatalog(type: CatalogType, id: string) {
const table = TABLES[type];
const [row] = await db
.update(table)
.set({ active: false, updatedAt: new Date() })
.where(eq(table.id, id))
.returning();
return row;
}
/* ---------------------------------------------------------- categories */
export type CategoryCreate = {
name: string;
description?: string | null;
colorHex?: string | null;
icon?: string | null;
sortOrder?: number;
};
export async function createCategory(fields: CategoryCreate) {
const now = new Date();
const [row] = await db
.insert(skillCategories)
.values({
id: crypto.randomUUID(),
slug: slugify(fields.name),
name: fields.name,
description: fields.description ?? null,
colorHex: fields.colorHex ?? null,
icon: fields.icon ?? null,
sortOrder: fields.sortOrder ?? 0,
active: true,
createdAt: now,
})
.returning();
return row;
}
export type CategoryUpdate = {
name?: string;
description?: string | null;
colorHex?: string | null;
icon?: string | null;
sortOrder?: number;
};
/** Rename / edit — `slug` is intentionally excluded (frozen after creation). */
export async function updateCategory(id: string, fields: CategoryUpdate) {
const patch: Record<string, unknown> = { updatedAt: new Date() };
if (fields.name !== undefined) patch.name = fields.name;
if (fields.description !== undefined) patch.description = fields.description;
if (fields.colorHex !== undefined) patch.colorHex = fields.colorHex;
if (fields.icon !== undefined) patch.icon = fields.icon;
if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder;
const [row] = await db
.update(skillCategories)
.set(patch)
.where(eq(skillCategories.id, id))
.returning();
return row;
}
/* ---------------------------------------------------------- vendors */
export type VendorCreate = {
name: string;
supportUrl?: string | null;
supportPhone?: string | null;
notes?: string | null;
sortOrder?: number;
};
export async function createVendor(fields: VendorCreate) {
const now = new Date();
const [row] = await db
.insert(vendors)
.values({
id: crypto.randomUUID(),
slug: slugify(fields.name),
name: fields.name,
supportUrl: fields.supportUrl ?? null,
supportPhone: fields.supportPhone ?? null,
notes: fields.notes ?? null,
sortOrder: fields.sortOrder ?? 0,
active: true,
createdAt: now,
})
.returning();
return row;
}
export type VendorUpdate = {
name?: string;
supportUrl?: string | null;
supportPhone?: string | null;
notes?: string | null;
sortOrder?: number;
};
export async function updateVendor(id: string, fields: VendorUpdate) {
const patch: Record<string, unknown> = { updatedAt: new Date() };
if (fields.name !== undefined) patch.name = fields.name;
if (fields.supportUrl !== undefined) patch.supportUrl = fields.supportUrl;
if (fields.supportPhone !== undefined) patch.supportPhone = fields.supportPhone;
if (fields.notes !== undefined) patch.notes = fields.notes;
if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder;
const [row] = await db
.update(vendors)
.set(patch)
.where(eq(vendors.id, id))
.returning();
return row;
}
/* ---------------------------------------------------------- technologies */
export type TechnologyCreate = {
name: string;
vendorId: string;
categoryId: string;
modelNumber?: string | null;
versionLabel?: string | null;
docsUrl?: string | null;
purchasedOn?: string | null;
serialNumber?: string | null;
successorTechnologyId?: string | null;
sortOrder?: number;
};
export async function createTechnology(fields: TechnologyCreate) {
const now = new Date();
const [row] = await db
.insert(technologies)
.values({
id: crypto.randomUUID(),
slug: slugify(fields.name),
name: fields.name,
vendorId: fields.vendorId,
categoryId: fields.categoryId,
modelNumber: fields.modelNumber ?? null,
versionLabel: fields.versionLabel ?? null,
docsUrl: fields.docsUrl ?? null,
purchasedOn: fields.purchasedOn ?? null,
serialNumber: fields.serialNumber ?? null,
successorTechnologyId: fields.successorTechnologyId ?? null,
sortOrder: fields.sortOrder ?? 0,
active: true,
createdAt: now,
})
.returning();
return row;
}
export type TechnologyUpdate = {
name?: string;
modelNumber?: string | null;
versionLabel?: string | null;
docsUrl?: string | null;
purchasedOn?: string | null;
serialNumber?: string | null;
successorTechnologyId?: string | null;
sortOrder?: number;
};
export async function updateTechnology(id: string, fields: TechnologyUpdate) {
const patch: Record<string, unknown> = { updatedAt: new Date() };
if (fields.name !== undefined) patch.name = fields.name;
if (fields.modelNumber !== undefined) patch.modelNumber = fields.modelNumber;
if (fields.versionLabel !== undefined) patch.versionLabel = fields.versionLabel;
if (fields.docsUrl !== undefined) patch.docsUrl = fields.docsUrl;
if (fields.purchasedOn !== undefined) patch.purchasedOn = fields.purchasedOn;
if (fields.serialNumber !== undefined) patch.serialNumber = fields.serialNumber;
if (fields.successorTechnologyId !== undefined)
patch.successorTechnologyId = fields.successorTechnologyId;
if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder;
const [row] = await db
.update(technologies)
.set(patch)
.where(eq(technologies.id, id))
.returning();
return row;
}
/* ---------------------------------------------------------- functions */
export type FunctionCreate = {
name: string;
categoryId: string;
description?: string | null;
sortOrder?: number;
};
export async function createFunction(fields: FunctionCreate) {
const now = new Date();
const [row] = await db
.insert(functions)
.values({
id: crypto.randomUUID(),
slug: slugify(fields.name),
name: fields.name,
categoryId: fields.categoryId,
description: fields.description ?? null,
sortOrder: fields.sortOrder ?? 0,
active: true,
createdAt: now,
})
.returning();
return row;
}
export type FunctionUpdate = {
name?: string;
description?: string | null;
sortOrder?: number;
};
export async function updateFunction(id: string, fields: FunctionUpdate) {
const patch: Record<string, unknown> = { updatedAt: new Date() };
if (fields.name !== undefined) patch.name = fields.name;
if (fields.description !== undefined) patch.description = fields.description;
if (fields.sortOrder !== undefined) patch.sortOrder = fields.sortOrder;
const [row] = await db
.update(functions)
.set(patch)
.where(eq(functions.id, id))
.returning();
return row;
}
+156 -3
View File
@@ -5,9 +5,8 @@
* users → roles → services → service_instances → slots → assignments
*
* Deliberately NOT here (added in later units, do not add "while I'm in the schema"):
* - notification_preferences (B2), notification_templates/rules/outbox (later)
* - Catalog taxonomy: skill_categories, vendors, technologies, functions,
* skills, position_skills, user_skills, skill_assessments, growth_goals (B3)
* - notification_templates/rules/outbox (later)
* - skills, position_skills, user_skills, skill_assessments, growth_goals (C1-C6)
* - service_role_requirements, unavailability, events, notifications outbox
*
* Conventions (ARCHITECTURE §4.2):
@@ -252,6 +251,123 @@ export const assignments = pgTable(
],
);
/* ------------------------------------------------------------- catalog */
/**
* Skill taxonomy — five admin-defined tables with zero hardcoded lists
* (ARCHITECTURE §4.3). B3 writes the four leaf tables; `skills` (composed from
* them) arrives in C1. Integrity rules enforced here: deactivate-only (no hard
* delete — `ON DELETE RESTRICT` on every FK), slugs frozen after creation.
*/
export const skillCategories = pgTable(
"skill_categories",
{
id: text("id").primaryKey(),
slug: text("slug").unique().notNull(),
/** Editable — the display name an admin renames. */
name: text("name").notNull(),
description: text("description"),
colorHex: text("color_hex"),
icon: text("icon"),
sortOrder: integer("sort_order").notNull().default(0),
active: boolean("active").notNull().default(true),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
},
(table) => [
index("skill_categories_slug_idx").on(table.slug),
index("skill_categories_active_idx").on(table.active),
],
);
export const vendors = pgTable(
"vendors",
{
id: text("id").primaryKey(),
slug: text("slug").unique().notNull(),
name: text("name").notNull(),
supportUrl: text("support_url"),
supportPhone: text("support_phone"),
notes: text("notes"),
sortOrder: integer("sort_order").notNull().default(0),
active: boolean("active").notNull().default(true),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
},
(table) => [
index("vendors_slug_idx").on(table.slug),
index("vendors_active_idx").on(table.active),
],
);
export const technologies = pgTable(
"technologies",
{
id: text("id").primaryKey(),
slug: text("slug").unique().notNull(),
name: text("name").notNull(),
vendorId: text("vendor_id")
.notNull()
.references(() => vendors.id, { onDelete: "restrict" }),
categoryId: text("category_id")
.notNull()
.references(() => skillCategories.id, { onDelete: "restrict" }),
modelNumber: text("model_number"),
versionLabel: text("version_label"),
docsUrl: text("docs_url"),
/** Local-date asset tracking, stored as "YYYY-MM-DD" (string mode). */
purchasedOn: date("purchased_on", { mode: "string" }),
serialNumber: text("serial_number"),
retiredAt: timestamp("retired_at", { mode: "date", withTimezone: true }),
/** "ATEM Mini Pro → ATEM SDI Pro ISO" migration hint. Plain text (no
* self-FK): the pointer is a soft hint validated at the app layer, so a
* self-referential FK does not create a circular schema type. */
successorTechnologyId: text("successor_technology_id"),
sortOrder: integer("sort_order").notNull().default(0),
active: boolean("active").notNull().default(true),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
},
(table) => [
index("technologies_slug_idx").on(table.slug),
index("technologies_active_idx").on(table.active),
index("technologies_vendor_idx").on(table.vendorId),
index("technologies_category_idx").on(table.categoryId),
],
);
export const functions = pgTable(
"functions",
{
id: text("id").primaryKey(),
slug: text("slug").unique().notNull(),
name: text("name").notNull(),
/** Functions are grouped, not enumerated — one category each. */
categoryId: text("category_id")
.notNull()
.references(() => skillCategories.id, { onDelete: "restrict" }),
description: text("description"),
sortOrder: integer("sort_order").notNull().default(0),
active: boolean("active").notNull().default(true),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
},
(table) => [
index("functions_slug_idx").on(table.slug),
index("functions_active_idx").on(table.active),
index("functions_category_idx").on(table.categoryId),
],
);
/* ------------------------------------------------------------- relations */
export const usersRelations = relations(users, ({ many }) => ({
@@ -279,6 +395,39 @@ export const assignmentRelations = relations(assignments, ({ one }) => ({
user: one(users),
}));
export const skillCategoriesRelations = relations(
skillCategories,
({ many }) => ({
technologies: many(technologies),
functions: many(functions),
}),
);
export const vendorsRelations = relations(vendors, ({ many }) => ({
technologies: many(technologies),
}));
export const technologiesRelations = relations(
technologies,
({ one }) => ({
vendor: one(vendors, { fields: [technologies.vendorId], references: [vendors.id] }),
category: one(
skillCategories,
{ fields: [technologies.categoryId], references: [skillCategories.id] },
),
}),
);
export const functionsRelations = relations(
functions,
({ one }) => ({
category: one(
skillCategories,
{ fields: [functions.categoryId], references: [skillCategories.id] },
),
}),
);
/**
* The schema object Drizzle uses for migrations and the query layer.
* Phase A2 core only; catalog + downstream tables are added in their own units.
@@ -291,6 +440,10 @@ export const schema = {
serviceInstances,
slots,
assignments,
skillCategories,
vendors,
technologies,
functions,
};
export type Schema = typeof schema;
+31
View File
@@ -0,0 +1,31 @@
import { describe, it, expect } from "vitest";
import { slugify } from "@/lib/slug";
describe("slugify", () => {
it("lowercases a single word", () => {
expect(slugify("Audio")).toBe("audio");
});
it("replaces spaces with single hyphens", () => {
expect(slugify("ATEM Mini Pro")).toBe("atem-mini-pro");
});
it("drops punctuation and collapses runs", () => {
expect(slugify("Allen & Heath")).toBe("allen-heath");
expect(slugify("OBS Studio!!")).toBe("obs-studio");
});
it("trims leading/trailing hyphens", () => {
expect(slugify(" & Audio ")).toBe("audio");
});
it("keeps alphanumerics in place", () => {
expect(slugify("QL5")).toBe("ql5");
expect(slugify("ProPresenter 7")).toBe("propresenter-7");
});
it("ASCII-folds accented Latin letters", () => {
expect(slugify("Café Signal")).toBe("cafe-signal");
expect(slugify("Zoë")).toBe("zoe");
});
});
+38
View File
@@ -0,0 +1,38 @@
/**
* Slug generator for the skill taxonomy (ARCHITECTURE §4.3).
*
* Slugs freeze after creation — they appear in URLs, ICS exports and
* notification links — so they are generated deterministically from the
* display name at create time and never rewritten on rename.
*/
/**
* Turn a display name into a URL-safe slug: lowercase, ASCII-folded,
* non-alphanumeric runs collapsed to a single hyphen, edges trimmed.
*
* "Audio" -> "audio"
* "ATEM Mini Pro" -> "atem-mini-pro"
* "Allen & Heath" -> "allen-heath"
* "QL5" -> "ql5"
*/
export function slugify(name: string): string {
return name
// Basic Latin fold: accented / special Latin letters → ASCII.
.normalize("NFKD")
.replace(/[\u00C0-\u00FF]/g, (ch) => {
const folded: Record<string, string> = {
À: "A", Á: "A", Â: "A", Ã: "A", Ä: "A", Å: "A", Æ: "AE", Ç: "C",
È: "E", É: "E", Ê: "E", Ë: "E", Ì: "I", Í: "I", Î: "I", Ï: "I",
Ð: "D", Ñ: "N", Ò: "O", Ó: "O", Ô: "O", Õ: "O", Ö: "O", "×": "x",
Ù: "U", Ú: "U", Û: "U", Ü: "U", Ý: "Y", Þ: "Th",
};
return folded[ch] ?? "";
})
// Drop any remaining non-ASCII (chars outside the Latin-1 block).
.replace(/[^\u0000-\u007F]/g, "")
// Lowercase before the alphanumerics-only run collapse below.
.toLowerCase()
// Any non-alphanumeric run → single hyphen.
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}