feat: make each plugin an npm workspace built by a termix-plugin CLI

This commit is contained in:
LukeGus committed 2026-09-22 15:09:50 -05:00
1 parent 4758016f41
commit 5796186a1c
448 files changed
+3087 -2003

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# Changelog
## 1.0.0
Bundled with Termix 2.9.0.
+22
View File
@@ -0,0 +1,22 @@
# Network Topology
Visualize hosts and their connections as an interactive graph, saved per user.
Bundled with Termix and enabled by default.
## Layout
manifest.json id, capabilities and what this plugin contributes
src/backend/ activate(ctx) / deactivate(), plus the routes
src/frontend/ the UI it registers
locales/en.json its strings (English only; the rest are translated)
tests/backend/ vitest, node
tests/frontend/ vitest, jsdom
## Commands
npm run build bundle into dist/
npm run test run this plugin's tests
npm run typecheck
See packages/plugin-sdk/ARCHITECTURE.md for the contract this follows.
@@ -1,60 +0,0 @@
/**
* Network Topology - first-party, in-process plugin.
*
* Unlike the other first-party plugins (see src/backend/plugins/first-party.ts),
* this one does not own a transport or touch the shared SSH pool -- its two
* routes are plain per-user JSON CRUD against a single repository. It runs
* in-process anyway to keep its existing /network-topology URL and its
* existing dedicated table (network_topology, keyed by userId) rather than
* moving onto /plugin-api/network-topology/* and the generic key-value
* ctx.storage the worker tier would require, matching how fleets/proxmox/
* automations were migrated in place rather than reworked around the worker
* ctx boundary.
*
* Like fleets and proxmox, this plugin does not get its own port -- it
* registers its Express router with the always-mounted /network-topology
* dispatcher in src/backend/database/routes/network-topology-dispatch.ts.
*
* routes.ts is what used to be
* src/backend/database/routes/network-topology.ts, moved here and rewritten
* from `export default router` into
* startNetworkTopologyService()/stopNetworkTopologyService(), called from
* activate()/deactivate() below. The network_topology table and its
* repository stay in core (src/backend/database/db/schema.ts,
* src/backend/database/repositories/network-topology-repository.ts) -- this
* plugin system has no owned-table migration mechanism of its own, and the
* table carries an FK into core's users table.
*/
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* Loads a module by its path relative to this file's own directory.
*
* The plugin ships beside dist/backend, so in a built server the compiled
* .js for routes.js sits right next to this .mjs. Under vitest/dev nothing
* imports this plugin directly (the loader loads in-process plugins with a
* plain dynamic import, no tsx loader involved), so the only layout that
* needs to resolve here is the built one.
*/
async function loadRelative(relativePath) {
const here = path.dirname(fileURLToPath(import.meta.url));
const target = path.join(here, `${relativePath}.js`);
return import(new URL(`file://${target.replace(/\\/g, "/")}`).href);
}
let routesModule = null;
export async function activate(ctx) {
routesModule = await loadRelative("routes");
routesModule.startNetworkTopologyService();
ctx.log.info("Network Topology router registered at /network-topology");
}
export async function deactivate() {
if (routesModule) {
routesModule.stopNetworkTopologyService();
routesModule = null;
}
}
+1
View File
@@ -0,0 +1 @@
{}
-2
View File
@@ -25,8 +25,6 @@
}
]
},
"backend": "backend/index.mjs",
"frontend": "frontend/index.mjs",
"locales": "locales",
"platforms": ["linux", "win32", "darwin"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@termix-plugin/network-topology",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "termix-plugin build",
"test": "termix-plugin test",
"typecheck": "tsc -p tsconfig.json",
"validate": "termix-plugin validate"
},
"devDependencies": {
"@termix/plugin-sdk": "*"
}
}
@@ -0,0 +1,14 @@
import type { PluginContext } from "@termix/plugin-sdk/backend";
import {
startNetworkTopologyService,
stopNetworkTopologyService,
} from "./routes.js";
export async function activate(ctx: PluginContext) {
startNetworkTopologyService();
ctx.log.info("Network Topology router registered at /network-topology");
}
export async function deactivate() {
stopNetworkTopologyService();
}
@@ -1,12 +1,12 @@
import express from "express";
import { AuthManager } from "../../../src/backend/utils/auth-manager.js";
import type { AuthenticatedRequest } from "../../../src/types/index.js";
import { databaseLogger } from "../../../src/backend/utils/logger.js";
import { createCurrentNetworkTopologyRepository } from "../../../src/backend/database/repositories/factory.js";
import { AuthManager } from "../../../../src/backend/utils/auth-manager.js";
import type { AuthenticatedRequest } from "../../../../src/types/index.js";
import { databaseLogger } from "../../../../src/backend/utils/logger.js";
import { createCurrentNetworkTopologyRepository } from "../../../../src/backend/database/repositories/factory.js";
import {
registerNetworkTopologyRouter,
unregisterNetworkTopologyRouter,
} from "../../../src/backend/database/routes/network-topology-dispatch.js";
} from "../../../../src/backend/database/routes/network-topology-dispatch.js";
export const router = express.Router();
@@ -0,0 +1,73 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "../../../../../src/backend/tests/database/repositories/test-support.js";
import { NetworkTopologyRepository } from "../../../../../src/backend/database/repositories/network-topology-repository.js";
describe("NetworkTopologyRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<NetworkTopologyRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new NetworkTopologyRepository(context, onWrite);
}
it("finds, creates, and updates topology by user id", async () => {
const repo = await createRepository();
expect(await repo.findByUserId("user-1")).toBeNull();
await repo.upsertForUser(
"user-1",
JSON.stringify({ nodes: [{ id: "host-1" }], edges: [] }),
"2026-06-27T00:00:00.000Z",
);
expect(await repo.findByUserId("user-1")).toMatchObject({
userId: "user-1",
topology: '{"nodes":[{"id":"host-1"}],"edges":[]}',
updatedAt: "2026-06-27T00:00:00.000Z",
});
await repo.upsertForUser(
"user-1",
JSON.stringify({ nodes: [], edges: [{ id: "edge-1" }] }),
"2026-06-27T01:00:00.000Z",
);
expect(await repo.findByUserId("user-1")).toMatchObject({
userId: "user-1",
topology: '{"nodes":[],"edges":[{"id":"edge-1"}]}',
updatedAt: "2026-06-27T01:00:00.000Z",
});
});
it("deletes topology and only triggers writes for changed rows", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertForUser("user-1", "{}");
await repo.upsertForUser("user-1", '{"nodes":[]}');
expect(writeCount).toBe(2);
expect(await repo.deleteByUserId("missing")).toBe(0);
expect(writeCount).toBe(2);
expect(await repo.deleteByUserId("user-1")).toBe(1);
expect(writeCount).toBe(3);
expect(await repo.findByUserId("user-1")).toBeNull();
});
});
@@ -0,0 +1,154 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { Request, Response, Router } from "express";
const state = vi.hoisted(() => ({
currentUserId: "user-1" as string | undefined,
records: new Map<string, { userId: string; topology: string | null }>(),
}));
vi.mock("../../../../src/backend/database/db/index.js", () => ({ db: {} }));
vi.mock("../../../../src/backend/utils/logger.js", () => ({
databaseLogger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../../../src/backend/utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(req: Record<string, unknown>, _res: unknown, next: () => void) => {
req.userId = state.currentUserId;
next();
},
}),
},
}));
vi.mock("../../../../src/backend/database/repositories/factory.js", () => ({
createCurrentNetworkTopologyRepository: () => ({
findByUserId: async (userId: string) => state.records.get(userId) ?? null,
upsertForUser: async (userId: string, topology: string) => {
state.records.set(userId, { userId, topology });
},
}),
}));
vi.mock(
"../../../../src/backend/database/routes/network-topology-dispatch.js",
() => ({
registerNetworkTopologyRouter: vi.fn(),
unregisterNetworkTopologyRouter: vi.fn(),
}),
);
const { router } = await import("../../src/backend/routes.js");
function findLayer(method: string, path: string) {
const stack = (router as unknown as Router).stack as Array<{
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: (req: Request, res: Response) => unknown }>;
};
}>;
const layer = stack.find(
(l) => l.route?.path === path && l.route?.methods[method],
);
if (!layer?.route) throw new Error(`No route for ${method} ${path}`);
return layer.route.stack[layer.route.stack.length - 1].handle;
}
function makeReqRes(overrides: { body?: Record<string, unknown> }) {
const req = {
userId: state.currentUserId,
body: overrides.body ?? {},
headers: {},
} as unknown as Request;
const res = {
statusCode: 200,
jsonBody: null as unknown,
status(code: number) {
(this as unknown as { statusCode: number }).statusCode = code;
return this;
},
json(payload: unknown) {
(this as unknown as { jsonBody: unknown }).jsonBody = payload;
return this;
},
} as unknown as Response & { statusCode: number; jsonBody: unknown };
return { req, res };
}
async function invoke(
method: string,
path: string,
overrides: { body?: Record<string, unknown> } = {},
) {
const handler = findLayer(method, path);
const { req, res } = makeReqRes(overrides);
await handler(req, res);
return res as unknown as {
statusCode: number;
jsonBody: Record<string, unknown> | null;
};
}
beforeEach(() => {
state.currentUserId = "user-1";
state.records = new Map();
});
describe("GET /network-topology", () => {
it("returns null when the user has no saved topology", async () => {
const res = await invoke("get", "/");
expect(res.jsonBody).toBeNull();
});
it("returns the parsed topology when one exists", async () => {
state.records.set("user-1", {
userId: "user-1",
topology: JSON.stringify({ nodes: [{ id: "host-1" }], edges: [] }),
});
const res = await invoke("get", "/");
expect(res.jsonBody).toEqual({ nodes: [{ id: "host-1" }], edges: [] });
});
it("rejects an unauthenticated request", async () => {
state.currentUserId = undefined;
const res = await invoke("get", "/");
expect(res.statusCode).toBe(401);
});
});
describe("POST /network-topology", () => {
it("saves the topology and returns success", async () => {
const res = await invoke("post", "/", {
body: { topology: { nodes: [], edges: [] } },
});
expect(res.jsonBody).toEqual({ success: true });
expect(state.records.get("user-1")?.topology).toBe(
JSON.stringify({ nodes: [], edges: [] }),
);
});
it("rejects a request with no topology", async () => {
const res = await invoke("post", "/", { body: {} });
expect(res.statusCode).toBe(400);
});
it("rejects an unauthenticated request", async () => {
state.currentUserId = undefined;
const res = await invoke("post", "/", { body: { topology: {} } });
expect(res.statusCode).toBe(401);
});
});
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "@termix/plugin-sdk/tsconfig.plugin.json",
"compilerOptions": {
"paths": {
"@/types/*": ["../../src/types/*"],
"@/*": ["../../src/ui/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "tests/**/*.ts", "tests/**/*.tsx"]
}
@@ -0,0 +1,3 @@
import { pluginVitestConfig } from "@termix/plugin-sdk/vitest-preset";
export default pluginVitestConfig(import.meta.url);