@terreno/admin-backend 0.3.2 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/adminApp.ts CHANGED
@@ -1,22 +1,68 @@
1
1
  import {
2
+ APIError,
3
+ asyncHandler,
4
+ authenticateMiddleware,
5
+ BackgroundTask,
6
+ type BackgroundTaskDocument,
2
7
  getOpenApiSpecForModel,
8
+ logger,
3
9
  type ModelRouterOptions,
4
10
  modelRouter,
5
11
  Permissions,
12
+ type ScriptContext,
13
+ type ScriptResult,
14
+ type ScriptRunner,
15
+ TaskCancelledError,
6
16
  } from "@terreno/api";
7
- import type express from "express";
17
+ import express from "express";
18
+ import {DateTime} from "luxon";
19
+ import type mongoose from "mongoose";
8
20
  import type {Model} from "mongoose";
9
21
 
22
+ /**
23
+ * Configuration for a single model in the admin panel.
24
+ */
25
+ export interface AdminFieldOverride {
26
+ /** Widget to use for this field in the admin form (e.g., "markdown") */
27
+ widget?: string;
28
+ }
29
+
10
30
  export interface AdminModelConfig {
31
+ /** The Mongoose model to expose in the admin panel */
11
32
  model: Model<any>;
33
+ /** Route path for this model's endpoints, relative to basePath (e.g., "/users") */
12
34
  routePath: string;
35
+ /** Human-readable name shown in the admin UI (e.g., "Users") */
13
36
  displayName: string;
37
+ /** Field names to display in the list view table */
14
38
  listFields: string[];
39
+ /** Default sort order for list queries (e.g., "-created"). Defaults to "-created" if not provided. */
15
40
  defaultSort?: string;
41
+ /** Per-field overrides for widget type and other display options */
42
+ fieldOverrides?: Record<string, AdminFieldOverride>;
16
43
  }
17
44
 
45
+ /**
46
+ * Configuration for a script that can be run from the admin panel.
47
+ */
48
+ export interface AdminScriptConfig {
49
+ /** Unique name for this script (used as route key) */
50
+ name: string;
51
+ /** Human-readable description shown in the admin UI */
52
+ description: string;
53
+ /** The function that executes the script. Must return string[] results. */
54
+ runner: ScriptRunner;
55
+ }
56
+
57
+ /**
58
+ * Configuration options for the AdminApp plugin.
59
+ */
18
60
  export interface AdminOptions {
61
+ /** Array of model configurations to expose in the admin panel */
19
62
  models: AdminModelConfig[];
63
+ /** Array of scripts that can be run from the admin panel */
64
+ scripts?: AdminScriptConfig[];
65
+ /** Base path for all admin routes. Defaults to "/admin". */
20
66
  basePath?: string;
21
67
  }
22
68
 
@@ -27,6 +73,7 @@ interface AdminFieldMeta {
27
73
  enum?: string[];
28
74
  default?: any;
29
75
  ref?: string;
76
+ widget?: string;
30
77
  }
31
78
 
32
79
  interface AdminModelMeta {
@@ -38,8 +85,14 @@ interface AdminModelMeta {
38
85
  fields: Record<string, AdminFieldMeta>;
39
86
  }
40
87
 
88
+ interface AdminScriptMeta {
89
+ name: string;
90
+ description: string;
91
+ }
92
+
41
93
  interface AdminConfigResponse {
42
94
  models: AdminModelMeta[];
95
+ scripts: AdminScriptMeta[];
43
96
  }
44
97
 
45
98
  const extractFieldMeta = (
@@ -65,13 +118,74 @@ const extractFieldMeta = (
65
118
  return fields;
66
119
  };
67
120
 
121
+ /**
122
+ * TerrenoPlugin that auto-generates admin CRUD endpoints for Mongoose models.
123
+ *
124
+ * Creates a metadata endpoint (`GET {basePath}/config`) and full CRUD routes for each
125
+ * configured model. All routes require `Permissions.IsAdmin`.
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * import {AdminApp} from "@terreno/admin-backend";
130
+ * import {User, Todo} from "./models";
131
+ *
132
+ * const admin = new AdminApp({
133
+ * basePath: "/admin",
134
+ * models: [
135
+ * {
136
+ * model: User,
137
+ * routePath: "/users",
138
+ * displayName: "Users",
139
+ * listFields: ["email", "name", "admin"],
140
+ * defaultSort: "-created",
141
+ * },
142
+ * {
143
+ * model: Todo,
144
+ * routePath: "/todos",
145
+ * displayName: "Todos",
146
+ * listFields: ["title", "completed", "ownerId"],
147
+ * },
148
+ * ],
149
+ * });
150
+ *
151
+ * // Register with TerrenoApp
152
+ * new TerrenoApp({ userModel: User })
153
+ * .register(admin)
154
+ * .start();
155
+ * ```
156
+ *
157
+ * @see AdminOptions for configuration options
158
+ * @see AdminModelConfig for model configuration
159
+ * @see TerrenoPlugin for the plugin interface
160
+ */
68
161
  export class AdminApp {
69
162
  private options: AdminOptions;
70
163
 
164
+ /**
165
+ * Create a new AdminApp plugin.
166
+ *
167
+ * @param options - Admin panel configuration including models and base path
168
+ */
71
169
  constructor(options: AdminOptions) {
72
170
  this.options = options;
73
171
  }
74
172
 
173
+ /**
174
+ * Register admin routes with the Express application.
175
+ *
176
+ * Creates:
177
+ * - `GET {basePath}/config` - Returns metadata for all configured models
178
+ * - CRUD endpoints for each model at `{basePath}{model.routePath}`:
179
+ * - `GET /` - List with pagination
180
+ * - `POST /` - Create
181
+ * - `GET /:id` - Read single item
182
+ * - `PATCH /:id` - Update
183
+ * - `DELETE /:id` - Delete
184
+ *
185
+ * All endpoints require `Permissions.IsAdmin` authentication.
186
+ *
187
+ * @param app - The Express application instance to register with
188
+ */
75
189
  register(app: express.Application): void {
76
190
  const basePath = this.options.basePath ?? "/admin";
77
191
  const modelConfigs = this.options.models;
@@ -96,6 +210,15 @@ export class AdminApp {
96
210
  }
97
211
  }
98
212
 
213
+ // Apply field overrides (e.g., widget: "markdown")
214
+ if (config.fieldOverrides) {
215
+ for (const [key, override] of Object.entries(config.fieldOverrides)) {
216
+ if (fields[key] && override.widget) {
217
+ fields[key].widget = override.widget;
218
+ }
219
+ }
220
+ }
221
+
99
222
  return {
100
223
  defaultSort: config.defaultSort ?? "-created",
101
224
  displayName: config.displayName,
@@ -106,7 +229,14 @@ export class AdminApp {
106
229
  };
107
230
  });
108
231
 
109
- const configResponse: AdminConfigResponse = {models: configModels};
232
+ // Build script metadata for config response
233
+ const scriptConfigs = this.options.scripts ?? [];
234
+ const configScripts: AdminScriptMeta[] = scriptConfigs.map((script) => ({
235
+ description: script.description,
236
+ name: script.name,
237
+ }));
238
+
239
+ const configResponse: AdminConfigResponse = {models: configModels, scripts: configScripts};
110
240
 
111
241
  // GET /admin/config
112
242
  app.get(`${basePath}/config`, (_req, res) => {
@@ -128,5 +258,203 @@ export class AdminApp {
128
258
 
129
259
  app.use(`${basePath}${config.routePath}`, modelRouter(config.model, routerOptions));
130
260
  }
261
+
262
+ // Mount script routes
263
+ if (scriptConfigs.length > 0) {
264
+ const scriptsRouter = express.Router();
265
+ scriptsRouter.use(authenticateMiddleware());
266
+
267
+ this.mountScriptRoutes(scriptsRouter, scriptConfigs);
268
+
269
+ app.use(`${basePath}/scripts`, scriptsRouter);
270
+ }
271
+ }
272
+
273
+ private mountScriptRoutes(router: express.Router, scripts: AdminScriptConfig[]): void {
274
+ const scriptsByName = new Map(scripts.map((s) => [s.name, s]));
275
+
276
+ // POST /admin/scripts/:name/run — Execute a script
277
+ router.post(
278
+ "/:name/run",
279
+ asyncHandler(async (req: express.Request<{name: string}>, res: express.Response) => {
280
+ const user = req.user as {_id: unknown; admin?: boolean; name?: string} | undefined;
281
+ if (!user?.admin) {
282
+ throw new APIError({status: 403, title: "Only admins can run scripts"});
283
+ }
284
+
285
+ const script = scriptsByName.get(req.params.name);
286
+ if (!script) {
287
+ throw new APIError({status: 404, title: `Script not found: ${req.params.name}`});
288
+ }
289
+
290
+ const isWetRun = req.query.wetRun === "true";
291
+ const now = DateTime.now().toJSDate();
292
+
293
+ let task: BackgroundTaskDocument;
294
+ try {
295
+ task = (await BackgroundTask.create({
296
+ createdBy: user._id as mongoose.Types.ObjectId,
297
+ isDryRun: !isWetRun,
298
+ logs: [
299
+ {level: "info", message: `Script started by ${user.name ?? "admin"}`, timestamp: now},
300
+ ],
301
+ progress: {message: "Starting...", percentage: 0, stage: "Queued"},
302
+ startedAt: now,
303
+ status: "running",
304
+ taskType: script.name,
305
+ })) as BackgroundTaskDocument;
306
+ } catch (err: unknown) {
307
+ const detail = err instanceof Error ? err.message : String(err);
308
+ logger.error(`Failed to create background task for ${script.name}: ${detail}`);
309
+ throw new APIError({
310
+ detail,
311
+ status: 500,
312
+ title: `Failed to create background task for script: ${script.name}`,
313
+ });
314
+ }
315
+
316
+ // Build context for cancellation and progress reporting
317
+ const ctx: ScriptContext = {
318
+ addLog: async (level, message) => {
319
+ const current = await BackgroundTask.findById(task._id);
320
+ if (current) {
321
+ await current.addLog(level, message);
322
+ }
323
+ },
324
+ checkCancellation: async () => {
325
+ await BackgroundTask.checkCancellation(task._id.toString());
326
+ },
327
+ updateProgress: async (percentage, stage, message) => {
328
+ const current = await BackgroundTask.findById(task._id);
329
+ if (current) {
330
+ await current.updateProgress(percentage, stage, message);
331
+ }
332
+ },
333
+ };
334
+
335
+ // Run the script asynchronously — use atomic updates to avoid overwriting
336
+ // cancellation or other intermediate state changes.
337
+ void (async () => {
338
+ try {
339
+ const result: ScriptResult = await script.runner(isWetRun, ctx);
340
+
341
+ // Atomically update only if still running (don't overwrite cancellation)
342
+ await BackgroundTask.findOneAndUpdate(
343
+ {_id: task._id, status: "running"},
344
+ {
345
+ $set: {
346
+ completedAt: DateTime.now().toJSDate(),
347
+ progress: {message: "Done", percentage: 100, stage: "Complete"},
348
+ result: result.results,
349
+ status: result.success ? "completed" : "failed",
350
+ },
351
+ }
352
+ );
353
+ } catch (err: unknown) {
354
+ if (err instanceof TaskCancelledError) {
355
+ return;
356
+ }
357
+ const message = err instanceof Error ? err.message : String(err);
358
+ logger.error(`Script ${script.name} failed: ${message}`);
359
+
360
+ // Atomically update only if still running
361
+ await BackgroundTask.findOneAndUpdate(
362
+ {_id: task._id, status: "running"},
363
+ {
364
+ $set: {
365
+ completedAt: DateTime.now().toJSDate(),
366
+ error: message,
367
+ result: [message],
368
+ status: "failed",
369
+ },
370
+ }
371
+ );
372
+ }
373
+ })();
374
+
375
+ return res.status(201).json({taskId: task._id.toString()});
376
+ })
377
+ );
378
+
379
+ // GET /admin/scripts/tasks/:id — Poll task status
380
+ router.get(
381
+ "/tasks/:id",
382
+ asyncHandler(async (req: express.Request<{id: string}>, res: express.Response) => {
383
+ const user = req.user as {_id: unknown; admin?: boolean} | undefined;
384
+ if (!user?.admin) {
385
+ throw new APIError({status: 403, title: "Only admins can view tasks"});
386
+ }
387
+
388
+ let task;
389
+ try {
390
+ task = await BackgroundTask.findById(req.params.id);
391
+ } catch (err: unknown) {
392
+ const detail = err instanceof Error ? err.message : String(err);
393
+ throw new APIError({detail, status: 400, title: "Invalid task ID"});
394
+ }
395
+ if (!task) {
396
+ throw new APIError({status: 404, title: "Task not found"});
397
+ }
398
+
399
+ return res.json({task: task.toObject()});
400
+ })
401
+ );
402
+
403
+ // DELETE /admin/scripts/tasks/:id — Cancel a running task
404
+ router.delete(
405
+ "/tasks/:id",
406
+ asyncHandler(async (req: express.Request<{id: string}>, res: express.Response) => {
407
+ const user = req.user as {_id: unknown; admin?: boolean; name?: string} | undefined;
408
+ if (!user?.admin) {
409
+ throw new APIError({status: 403, title: "Only admins can cancel tasks"});
410
+ }
411
+
412
+ let task;
413
+ try {
414
+ task = await BackgroundTask.findById(req.params.id);
415
+ } catch (err: unknown) {
416
+ const detail = err instanceof Error ? err.message : String(err);
417
+ throw new APIError({detail, status: 400, title: "Invalid task ID"});
418
+ }
419
+ if (!task) {
420
+ throw new APIError({status: 404, title: "Task not found"});
421
+ }
422
+
423
+ if (task.status !== "pending" && task.status !== "running") {
424
+ throw new APIError({
425
+ status: 400,
426
+ title: `Cannot cancel task with status: ${task.status}`,
427
+ });
428
+ }
429
+
430
+ // Atomically cancel only if still running/pending (avoids race with completion)
431
+ const cancelled = await BackgroundTask.findOneAndUpdate(
432
+ {_id: task._id, status: {$in: ["pending", "running"]}},
433
+ {
434
+ $push: {
435
+ logs: {
436
+ level: "info",
437
+ message: `Task cancelled by ${user.name ?? "admin"}`,
438
+ timestamp: DateTime.now().toJSDate(),
439
+ },
440
+ },
441
+ $set: {
442
+ completedAt: DateTime.now().toJSDate(),
443
+ status: "cancelled",
444
+ },
445
+ },
446
+ {new: true}
447
+ );
448
+
449
+ if (!cancelled) {
450
+ throw new APIError({
451
+ status: 409,
452
+ title: "Task already completed or cancelled",
453
+ });
454
+ }
455
+
456
+ return res.json({message: "Task cancelled", task: cancelled.toObject()});
457
+ })
458
+ );
131
459
  }
132
460
  }