@terreno/admin-backend 0.10.0 → 0.11.0

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
@@ -6,6 +6,7 @@ import {
6
6
  type BackgroundTaskDocument,
7
7
  checkPermissions,
8
8
  getOpenApiSpecForModel,
9
+ type JSONValue,
9
10
  logger,
10
11
  type ModelRouterOptions,
11
12
  modelRouter,
@@ -15,6 +16,7 @@ import {
15
16
  type ScriptResult,
16
17
  type ScriptRunner,
17
18
  TaskCancelledError,
19
+ type User,
18
20
  VersionConfig,
19
21
  } from "@terreno/api";
20
22
  import express from "express";
@@ -31,6 +33,8 @@ export interface AdminFieldOverride {
31
33
  }
32
34
 
33
35
  export interface AdminModelConfig {
36
+ // noExplicitAny: Model must accept any document type for the generic admin panel;
37
+ // Model<unknown> breaks callers since Model<T> is invariant in T.
34
38
  /** The Mongoose model to expose in the admin panel */
35
39
  model: Model<any>;
36
40
  /** Route path for this model's endpoints, relative to basePath (e.g., "/users") */
@@ -78,12 +82,18 @@ interface AdminFieldMeta {
78
82
  required: boolean;
79
83
  description?: string;
80
84
  enum?: string[];
81
- default?: any;
85
+ default?: unknown;
82
86
  ref?: string;
83
87
  searchable?: boolean;
84
88
  widget?: string;
85
- /** For array fields: metadata about each item's sub-fields */
89
+ /** For array fields of sub-documents: metadata about each item's sub-fields */
86
90
  items?: Record<string, AdminFieldMeta>;
91
+ /** For array fields of primitives: the item type (string/number/boolean/objectid) */
92
+ itemType?: string;
93
+ /** For array fields of primitives: enum values for each item */
94
+ itemEnum?: string[];
95
+ /** For array fields of ObjectId refs: the referenced model name */
96
+ itemRef?: string;
87
97
  }
88
98
 
89
99
  interface AdminModelMeta {
@@ -107,11 +117,16 @@ interface AdminConfigResponse {
107
117
  scripts: AdminScriptMeta[];
108
118
  }
109
119
 
110
- const toPlainObject = (value: any): any => {
111
- if (value && typeof value === "object" && typeof value.toObject === "function") {
112
- return value.toObject();
120
+ const toPlainObject = (value: unknown): Record<string, unknown> => {
121
+ if (
122
+ value &&
123
+ typeof value === "object" &&
124
+ "toObject" in value &&
125
+ typeof value.toObject === "function"
126
+ ) {
127
+ return (value as {toObject: () => Record<string, unknown>}).toObject();
113
128
  }
114
- return value;
129
+ return value as Record<string, unknown>;
115
130
  };
116
131
 
117
132
  const removeHiddenFields = (value: unknown, hiddenFieldSet: Set<string>): unknown => {
@@ -121,7 +136,7 @@ const removeHiddenFields = (value: unknown, hiddenFieldSet: Set<string>): unknow
121
136
  if (!value || typeof value !== "object") {
122
137
  return value;
123
138
  }
124
- const plainValue = toPlainObject(value as any);
139
+ const plainValue = toPlainObject(value);
125
140
  const nextValue: Record<string, unknown> = {};
126
141
  for (const [key, fieldValue] of Object.entries(plainValue)) {
127
142
  if (!hiddenFieldSet.has(key)) {
@@ -131,8 +146,25 @@ const removeHiddenFields = (value: unknown, hiddenFieldSet: Set<string>): unknow
131
146
  return nextValue;
132
147
  };
133
148
 
149
+ interface OpenApiProperty {
150
+ default?: unknown;
151
+ description?: string;
152
+ enum?: string[];
153
+ $ref?: string;
154
+ type?: string;
155
+ format?: string;
156
+ items?: {
157
+ properties?: Record<string, OpenApiProperty>;
158
+ required?: string[];
159
+ type?: string;
160
+ enum?: string[];
161
+ format?: string;
162
+ $ref?: string;
163
+ };
164
+ }
165
+
134
166
  const extractFieldMeta = (
135
- properties: Record<string, any>,
167
+ properties: Record<string, OpenApiProperty>,
136
168
  required: string[]
137
169
  ): Record<string, AdminFieldMeta> => {
138
170
  const fields: Record<string, AdminFieldMeta> = {};
@@ -151,7 +183,21 @@ const extractFieldMeta = (
151
183
  // For array fields, extract item sub-field metadata
152
184
  if (prop.type === "array" && prop.items?.properties) {
153
185
  const itemRequired: string[] = prop.items.required ?? [];
154
- fields[key].items = extractFieldMeta(prop.items.properties, itemRequired);
186
+ fields[key].items = extractFieldMeta(
187
+ prop.items.properties as Record<string, OpenApiProperty>,
188
+ itemRequired
189
+ );
190
+ }
191
+
192
+ // For array fields of primitives, capture the item type and enum
193
+ if (prop.type === "array" && prop.items && !prop.items.properties) {
194
+ const itemProp = prop.items as OpenApiProperty;
195
+ if (itemProp.type) {
196
+ fields[key].itemType = itemProp.type;
197
+ }
198
+ if (itemProp.enum) {
199
+ fields[key].itemEnum = itemProp.enum;
200
+ }
155
201
  }
156
202
 
157
203
  // Check for ObjectId references in the raw property
@@ -236,7 +282,10 @@ export class AdminApp {
236
282
 
237
283
  // Build config response with field metadata from Mongoose schemas
238
284
  const configModels: AdminModelMeta[] = modelConfigs.map((config) => {
239
- const {properties, required} = getOpenApiSpecForModel(config.model);
285
+ const {properties, required} = getOpenApiSpecForModel(config.model) as {
286
+ properties: Record<string, OpenApiProperty>;
287
+ required: string[];
288
+ };
240
289
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
241
290
  const filteredProperties = Object.fromEntries(
242
291
  Object.entries(properties).filter(([key]) => !hiddenFieldSet.has(key))
@@ -252,10 +301,39 @@ export class AdminApp {
252
301
  if (pathOptions?.ref) {
253
302
  field.ref = pathOptions.ref;
254
303
  }
255
- // Handle array of refs
304
+ // Handle array of refs (legacy: also set ref for back-compat)
256
305
  if (Array.isArray(pathOptions?.type) && pathOptions.type[0]?.ref) {
257
306
  field.ref = pathOptions.type[0].ref;
258
307
  }
308
+ // For arrays, use the caster to infer the primitive item type/ref.
309
+ // Mongoose caster.instance is "String" | "Number" | "Boolean" | "ObjectID".
310
+ if (schemaPath.instance === "Array") {
311
+ const caster = (
312
+ schemaPath as unknown as {
313
+ caster?: {instance?: string; options?: {ref?: string; enum?: string[]}};
314
+ }
315
+ ).caster;
316
+ if (caster?.instance && !field.items) {
317
+ const instanceToType: Record<string, string> = {
318
+ Boolean: "boolean",
319
+ Number: "number",
320
+ ObjectID: "objectid",
321
+ ObjectId: "objectid",
322
+ SchemaObjectId: "objectid",
323
+ String: "string",
324
+ };
325
+ const mapped = instanceToType[caster.instance];
326
+ if (mapped) {
327
+ field.itemType = mapped;
328
+ }
329
+ if (caster.options?.ref) {
330
+ field.itemRef = caster.options.ref;
331
+ }
332
+ if (caster.options?.enum) {
333
+ field.itemEnum = caster.options.enum;
334
+ }
335
+ }
336
+ }
259
337
  }
260
338
  }
261
339
 
@@ -302,7 +380,9 @@ export class AdminApp {
302
380
  `${basePath}/config`,
303
381
  authenticateMiddleware(),
304
382
  asyncHandler(async (req, res) => {
305
- if (!(await checkPermissions("read", [Permissions.IsAdmin], req.user as any))) {
383
+ if (
384
+ !(await checkPermissions("read", [Permissions.IsAdmin], req.user as User | undefined))
385
+ ) {
306
386
  throw new APIError({status: 403, title: "Admin access required"});
307
387
  }
308
388
  return res.json(configResponse);
@@ -315,7 +395,9 @@ export class AdminApp {
315
395
  versionConfigPath,
316
396
  authenticateMiddleware(),
317
397
  asyncHandler(async (req, res) => {
318
- if (!(await checkPermissions("read", [Permissions.IsAdmin], req.user as any))) {
398
+ if (
399
+ !(await checkPermissions("read", [Permissions.IsAdmin], req.user as User | undefined))
400
+ ) {
319
401
  throw new APIError({status: 403, title: "Admin access required"});
320
402
  }
321
403
  const config = await VersionConfig.findOneOrNone({_singleton: "config"});
@@ -335,7 +417,9 @@ export class AdminApp {
335
417
  versionConfigPath,
336
418
  authenticateMiddleware(),
337
419
  asyncHandler(async (req, res) => {
338
- if (!(await checkPermissions("update", [Permissions.IsAdmin], req.user as any))) {
420
+ if (
421
+ !(await checkPermissions("update", [Permissions.IsAdmin], req.user as User | undefined))
422
+ ) {
339
423
  throw new APIError({status: 403, title: "Admin access required"});
340
424
  }
341
425
  const raw = req.body as Record<string, unknown>;
@@ -459,6 +543,7 @@ export class AdminApp {
459
543
  // Mount modelRouter for each model with IsAdmin permissions
460
544
  for (const config of modelConfigs) {
461
545
  const hiddenFieldSet = new Set(config.hiddenFields ?? []);
546
+ // noExplicitAny: ModelRouterOptions<any> matches the Model<any> from AdminModelConfig.
462
547
  const routerOptions: ModelRouterOptions<any> = {
463
548
  ...(openApi ? {openApi: openApi as OpenApiMiddleware} : {}),
464
549
  permissions: {
@@ -470,8 +555,8 @@ export class AdminApp {
470
555
  },
471
556
  responseHandler:
472
557
  hiddenFieldSet.size > 0
473
- ? async (value, _method, _request, _options): Promise<any> =>
474
- removeHiddenFields(value, hiddenFieldSet) as any
558
+ ? async (value, _method, _request, _options): Promise<JSONValue> =>
559
+ removeHiddenFields(value, hiddenFieldSet) as JSONValue
475
560
  : undefined,
476
561
  sort: config.defaultSort ?? "-created",
477
562
  };