Refine plugin contract (todo §2); derive id/mount from folder (isValidPluginId), apiVersion literal not HOST_API_VERSION, nav icon = Lucide, drop redundant basePath
This commit is contained in:
@@ -5,17 +5,19 @@ import {
|
||||
definePlugin,
|
||||
findConflicts,
|
||||
HOST_API_VERSION,
|
||||
isValidPluginId,
|
||||
parseSemver,
|
||||
type Plugin,
|
||||
type PluginManifest,
|
||||
} from "./plugin.ts";
|
||||
|
||||
// A representative manifest exercising every field — its existence type-checks the contract
|
||||
// (handler return variants, nav fragment, permission decls, hooks). The README example.
|
||||
const scheduling: Plugin = definePlugin({
|
||||
apiVersion: HOST_API_VERSION,
|
||||
basePath: "/scheduling",
|
||||
// A representative manifest exercising every field — its existence type-checks the contract.
|
||||
// `apiVersion` is a literal: a plugin pins the version it was built against, so importing
|
||||
// HOST_API_VERSION would always equal the host and defeat the check. No `id`/`basePath` — the
|
||||
// host derives both from the plugin's folder name.
|
||||
const scheduling: PluginManifest = definePlugin({
|
||||
apiVersion: "1.0.0",
|
||||
hooks: { onBoot: () => {} },
|
||||
id: "scheduling",
|
||||
nav: [{
|
||||
children: [{ href: "/scheduling/shifts", id: "scheduling:shifts", label: "Shifts", permission: "scheduling:read" }],
|
||||
icon: "i-cal", id: "scheduling:root", label: "Scheduling",
|
||||
@@ -28,12 +30,19 @@ const scheduling: Plugin = definePlugin({
|
||||
],
|
||||
});
|
||||
|
||||
test("definePlugin returns the manifest unchanged — it only types; validation is at discovery (§2)", () => {
|
||||
const m: Plugin = { apiVersion: "1.0.0", basePath: "/x", id: "x" };
|
||||
test("definePlugin returns the manifest unchanged — id/mount come from the folder, not the manifest", () => {
|
||||
const m: PluginManifest = { apiVersion: "1.0.0" };
|
||||
assert.equal(definePlugin(m), m); // identity, not a copy
|
||||
assert.equal(scheduling.routes?.length, 3);
|
||||
});
|
||||
|
||||
test("isValidPluginId accepts kebab-case folder names and rejects everything else", () => {
|
||||
for (const ok of ["scheduling", "people", "people-directory"]) assert.ok(isValidPluginId(ok), ok);
|
||||
for (const bad of ["People", "people_dir", "people-", "-people", "people--dir", "people1", "", "a/b"]) {
|
||||
assert.ok(!isValidPluginId(bad), bad);
|
||||
}
|
||||
});
|
||||
|
||||
test("parseSemver follows the semver core, rejecting ranges, prefixes, leading zeros and missing parts", () => {
|
||||
assert.deepEqual(parseSemver("1.2.3"), { major: 1, minor: 2, patch: 3 });
|
||||
assert.deepEqual(parseSemver("1.2.3-rc.1+build.5"), { major: 1, minor: 2, patch: 3 }); // prerelease/build tolerated, ignored
|
||||
@@ -54,44 +63,37 @@ test("checkApiVersion: semver compat — equal/patch ok, older minor warns, newe
|
||||
}
|
||||
});
|
||||
|
||||
// Minimal valid plugin, overridable per case.
|
||||
const p = (over: Partial<Plugin> & Pick<Plugin, "id" | "basePath">): Plugin =>
|
||||
definePlugin({ apiVersion: HOST_API_VERSION, ...over });
|
||||
// A minimal discovered plugin (id = folder name; mount path is the derived `/<id>`), per case.
|
||||
const p = (over: Partial<Plugin> & Pick<Plugin, "id">): Plugin => ({ apiVersion: "1.0.0", ...over });
|
||||
|
||||
test("findConflicts: a clean set has none", () => {
|
||||
assert.deepEqual(findConflicts([p({ basePath: "/a", id: "a" }), p({ basePath: "/b", id: "b" })]), []);
|
||||
assert.deepEqual(findConflicts([p({ id: "a" }), p({ id: "b" })]), []);
|
||||
});
|
||||
|
||||
test("findConflicts: duplicate id, overlapping basePath, and colliding route are loud errors", () => {
|
||||
const dupId = findConflicts([p({ basePath: "/a", id: "a" }), p({ basePath: "/b", id: "a" })]);
|
||||
test("findConflicts: a duplicate id and a colliding route are loud errors", () => {
|
||||
const dupId = findConflicts([p({ id: "a" }), p({ id: "a" })]);
|
||||
assert.ok(dupId.some((c) => c.kind === "id" && c.level === "error"));
|
||||
|
||||
const sameBase = findConflicts([p({ basePath: "/x", id: "a" }), p({ basePath: "/x", id: "b" })]);
|
||||
assert.ok(sameBase.some((c) => c.kind === "basePath" && c.level === "error"));
|
||||
|
||||
// A basePath that is a path-prefix of another also overlaps (routes would shadow).
|
||||
const prefix = findConflicts([p({ basePath: "/x", id: "a" }), p({ basePath: "/x/y", id: "b" })]);
|
||||
assert.ok(prefix.some((c) => c.kind === "basePath" && c.level === "error" && c.plugins.includes("a") && c.plugins.includes("b")));
|
||||
|
||||
// Cross-plugin routes can't collide (unique `/<id>` prefix); two identical routes in one can.
|
||||
const noop = () => {};
|
||||
const dupRoute = findConflicts([p({
|
||||
basePath: "/a", id: "a",
|
||||
id: "a",
|
||||
routes: [{ handler: noop, method: "GET", path: "/t" }, { handler: noop, method: "GET", path: "/t" }],
|
||||
})]);
|
||||
assert.ok(dupRoute.some((c) => c.kind === "route" && c.level === "error"));
|
||||
assert.ok(dupRoute.some((c) => c.kind === "route" && c.level === "error" && c.message.includes("/a/t")));
|
||||
});
|
||||
|
||||
test("findConflicts: duplicate nav id is an error, a shared permission token only warns", () => {
|
||||
const navDup = findConflicts([
|
||||
p({ basePath: "/a", id: "a", nav: [{ id: "dup", label: "A" }] }),
|
||||
p({ basePath: "/b", id: "b", nav: [{ id: "dup", label: "B" }] }),
|
||||
p({ id: "a", nav: [{ id: "dup", label: "A" }] }),
|
||||
p({ id: "b", nav: [{ id: "dup", label: "B" }] }),
|
||||
]);
|
||||
assert.ok(navDup.some((c) => c.kind === "nav-id" && c.level === "error" && c.plugins.includes("a") && c.plugins.includes("b")));
|
||||
|
||||
// Sharing a permission across plugins is legitimate (shared role) → warn, not error.
|
||||
const permDup = findConflicts([
|
||||
p({ basePath: "/a", id: "a", permissions: [{ token: "shared:read" }] }),
|
||||
p({ basePath: "/b", id: "b", permissions: [{ token: "shared:read" }] }),
|
||||
p({ id: "a", permissions: [{ token: "shared:read" }] }),
|
||||
p({ id: "b", permissions: [{ token: "shared:read" }] }),
|
||||
]);
|
||||
assert.ok(permDup.some((c) => c.kind === "permission" && c.level === "warn"));
|
||||
});
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
// It only declares types + pure rules; the §2 discovery/router wire them to the filesystem
|
||||
// and HTTP. Philosophy: a powerful, predictable, overload-friendly API that fails loud at
|
||||
// boot/discovery rather than sandboxing at runtime.
|
||||
//
|
||||
// A plugin's identity comes from its folder under plugins/: the folder name is the `id`
|
||||
// (validated by isValidPluginId) and the mount path is `/<id>`. Neither is written in the
|
||||
// manifest — the host derives them at discovery, so they can't drift or be claimed twice.
|
||||
|
||||
import type { RequestContext } from "./context.ts";
|
||||
import type { NavNode } from "./nav.ts";
|
||||
@@ -27,7 +31,7 @@ export type RouteHandler = (ctx: RequestContext) => Promise<RouteResult | void>
|
||||
export interface Route {
|
||||
handler: RouteHandler;
|
||||
method: HttpMethod;
|
||||
path: string; // relative to basePath; ":name" segments become ctx.params.name
|
||||
path: string; // relative to the plugin's mount path `/<id>`; ":name" segments → ctx.params.name
|
||||
permission?: string; // coarse gate (a role token); checked before the handler runs
|
||||
}
|
||||
|
||||
@@ -45,20 +49,35 @@ export interface PluginHooks {
|
||||
onResponse?: (ctx: RequestContext, result: RouteResult | null) => Promise<void> | void;
|
||||
}
|
||||
|
||||
export interface Plugin {
|
||||
apiVersion: string; // semver of the host contract this plugin targets (e.g. HOST_API_VERSION)
|
||||
basePath: string; // unique mount prefix, e.g. "/scheduling"; must not overlap another plugin's
|
||||
// The authored manifest — a plugin's `plugin.ts` default-exports this. No `id`/mount path: the
|
||||
// host derives them from the folder name at discovery (see Plugin).
|
||||
export interface PluginManifest {
|
||||
apiVersion: string; // semver of the host contract this targets — write a literal, NOT HOST_API_VERSION (see docs)
|
||||
hooks?: PluginHooks;
|
||||
id: string; // globally unique; namespaces views, /public/<id>/, and nav/permission tokens
|
||||
nav?: NavNode[]; // fragment merged into the global menu (composeNav); ids must be globally unique
|
||||
nav?: NavNode[]; // fragment merged into the menu (composeNav); node `icon` is a Lucide sprite id (src/icons.ts), node ids must be globally unique
|
||||
permissions?: PermissionDecl[];
|
||||
routes?: Route[];
|
||||
}
|
||||
|
||||
// A discovered plugin: the manifest plus the `id` the host read from the folder name. Mounted
|
||||
// at `/<id>`, with views/static namespaced under the id.
|
||||
export interface Plugin extends PluginManifest {
|
||||
id: string;
|
||||
}
|
||||
|
||||
// Identity helper: types the manifest, returns it unchanged. Validation happens at discovery
|
||||
// (§2), so a plugin may equally be a plain typed object. Mirrors Vite's `defineConfig`.
|
||||
export function definePlugin(plugin: Plugin): Plugin {
|
||||
return plugin;
|
||||
export function definePlugin(manifest: PluginManifest): PluginManifest {
|
||||
return manifest;
|
||||
}
|
||||
|
||||
// A plugin id (its folder name) — lowercase letters in dash-separated segments: no digits,
|
||||
// uppercase, or leading/trailing/double dashes. Tight on purpose: the id forms the mount path
|
||||
// `/<id>`, the view/static namespace, and the central-override target.
|
||||
const PLUGIN_ID = /^[a-z]+(?:-[a-z]+)*$/;
|
||||
|
||||
export function isValidPluginId(id: string): boolean {
|
||||
return PLUGIN_ID.test(id);
|
||||
}
|
||||
|
||||
export interface Semver {
|
||||
@@ -112,15 +131,16 @@ export function checkApiVersion(pluginVersion: unknown, hostVersion: string = HO
|
||||
}
|
||||
|
||||
export interface PluginConflict {
|
||||
kind: "basePath" | "id" | "nav-id" | "permission" | "route";
|
||||
kind: "id" | "nav-id" | "permission" | "route";
|
||||
level: "error" | "warn";
|
||||
message: string;
|
||||
plugins: string[]; // unique ids involved
|
||||
}
|
||||
|
||||
// The conflict rules: defined, loud resolution — never last-write-wins. Pure over the discovered
|
||||
// manifests; discovery throws on any "error" and logs every "warn". Shared permission tokens are
|
||||
// the one intentional overlap, so they warn rather than error.
|
||||
// plugins; discovery throws on any "error" and logs every "warn". Mount-path (`/<id>`) uniqueness
|
||||
// is structural — it follows from the id check, so it needs no rule of its own. Shared permission
|
||||
// tokens are the one intentional overlap, so they warn rather than error.
|
||||
export function findConflicts(plugins: Plugin[]): PluginConflict[] {
|
||||
const out: PluginConflict[] = [];
|
||||
|
||||
@@ -130,18 +150,8 @@ export function findConflicts(plugins: Plugin[]): PluginConflict[] {
|
||||
if (n > 1) out.push({ kind: "id", level: "error", message: `${n} plugins share id "${id}"; ids must be globally unique`, plugins: [id] });
|
||||
}
|
||||
|
||||
for (let i = 0; i < plugins.length; i++) {
|
||||
for (let j = i + 1; j < plugins.length; j++) {
|
||||
const a = plugins[i] as Plugin;
|
||||
const b = plugins[j] as Plugin;
|
||||
if (basePathOverlap(a.basePath, b.basePath)) {
|
||||
out.push({ kind: "basePath", level: "error", message: `basePath "${a.basePath}" (${a.id}) overlaps "${b.basePath}" (${b.id})`, plugins: uniq([a.id, b.id]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collect(plugins, (plugin, push) => {
|
||||
for (const route of plugin.routes ?? []) push(`${route.method} ${joinPath(plugin.basePath, route.path)}`);
|
||||
for (const route of plugin.routes ?? []) push(`${route.method} ${fullPath(plugin.id, route.path)}`);
|
||||
}).forEach((owners, key) => {
|
||||
if (owners.length > 1) out.push({ kind: "route", level: "error", message: `${owners.length} routes resolve to "${key}"`, plugins: uniq(owners) });
|
||||
});
|
||||
@@ -173,16 +183,9 @@ function collectNavIds(nodes: NavNode[] | undefined, push: (id: string) => void)
|
||||
}
|
||||
}
|
||||
|
||||
const trimSlash = (s: string): string => s.replace(/\/+$/, "");
|
||||
|
||||
function basePathOverlap(a: string, b: string): boolean {
|
||||
const x = trimSlash(a);
|
||||
const y = trimSlash(b);
|
||||
return x === y || y.startsWith(`${x}/`) || x.startsWith(`${y}/`);
|
||||
}
|
||||
|
||||
function joinPath(basePath: string, path: string): string {
|
||||
return `${trimSlash(basePath)}${path.startsWith("/") ? path : `/${path}`}`;
|
||||
// A route's full path = the plugin's mount path `/<id>` + the route path.
|
||||
function fullPath(id: string, path: string): string {
|
||||
return `/${id}${path.startsWith("/") ? path : `/${path}`}`;
|
||||
}
|
||||
|
||||
function uniq(xs: string[]): string[] {
|
||||
|
||||
Reference in New Issue
Block a user